diff --git a/.github/workflows/core.yml b/.github/workflows/core.yml index 5dae6a218a..f5c5ba1e89 100644 --- a/.github/workflows/core.yml +++ b/.github/workflows/core.yml @@ -81,8 +81,8 @@ jobs: cargo check --locked --target "$TARGET" --features "$FEATURES" --features "$IN_PROCESS_SSH" \ -p tablepro-core -p tablepro-net -p tablepro-storage -p tablepro-ssh -p tablepro-session \ -p tablepro-foreign-import -p tablepro-ai -p tablepro-mcp -p tablepro-cloud-api -p tablepro-account -p tablepro-keys \ - -p tablepro-cli \ - -p tablepro-test-support -p tablepro-test-fixtures \ + -p tablepro-records -p tablepro-sync -p tablepro-cli \ + -p tablepro-test-support -p tablepro-test-fixtures -p tablepro-sync-testing \ -p tablepro-driver-cassandra -p tablepro-driver-clickhouse -p tablepro-driver-duckdb \ -p tablepro-driver-mongodb -p tablepro-driver-mssql -p tablepro-driver-mysql \ -p tablepro-driver-postgres -p tablepro-driver-redis -p tablepro-driver-sqlite diff --git a/Cargo.lock b/Cargo.lock index 800184b284..a382102289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7996,12 +7996,15 @@ dependencies = [ "tablepro-driver-redis", "tablepro-driver-sqlite", "tablepro-foreign-import", + "tablepro-keys", "tablepro-mcp", "tablepro-net", "tablepro-records", "tablepro-session", "tablepro-ssh", "tablepro-storage", + "tablepro-sync", + "tablepro-sync-testing", "tablepro-test-support", "tempfile", "thiserror 2.0.20", @@ -8011,6 +8014,7 @@ dependencies = [ "uniffi", "uuid", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -8226,6 +8230,38 @@ dependencies = [ "uuid", ] +[[package]] +name = "tablepro-sync" +version = "0.0.0" +dependencies = [ + "async-trait", + "secrecy", + "serde_json", + "tablepro-keys", + "tablepro-records", + "thiserror 2.0.20", + "tokio", + "uuid", + "zeroize", +] + +[[package]] +name = "tablepro-sync-testing" +version = "0.0.0" +dependencies = [ + "async-trait", + "base64 0.22.1", + "secrecy", + "serde_json", + "sha2 0.11.0", + "tablepro-keys", + "tablepro-records", + "tablepro-sync", + "tokio", + "uuid", + "zeroize", +] + [[package]] name = "tablepro-test-fixtures" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index b8a50bf949..4b4b8c8f68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,8 @@ members = [ "core/crates/session", "core/crates/ssh", "core/crates/storage", + "core/crates/sync", + "core/crates/sync/testing", "core/crates/test-fixtures", "core/crates/test-support", "core/crates/drivers/cassandra", @@ -53,6 +55,7 @@ tablepro-driver-postgres = { path = "core/crates/drivers/postgres" } tablepro-driver-redis = { path = "core/crates/drivers/redis" } tablepro-driver-sqlite = { path = "core/crates/drivers/sqlite" } tablepro-foreign-import = { path = "core/crates/foreign-import" } +tablepro-keys = { path = "core/crates/keys" } tablepro-mcp = { path = "core/crates/mcp" } tablepro-net = { path = "core/crates/net" } tablepro-records = { path = "core/crates/records" } @@ -60,6 +63,8 @@ tablepro-linux-platform = { path = "linux/crates/platform" } tablepro-session = { path = "core/crates/session" } tablepro-ssh = { path = "core/crates/ssh" } tablepro-storage = { path = "core/crates/storage" } +tablepro-sync = { path = "core/crates/sync" } +tablepro-sync-testing = { path = "core/crates/sync/testing" } tablepro-test-fixtures = { path = "core/crates/test-fixtures" } tablepro-test-support = { path = "core/crates/test-support" } async-trait = "0.1" diff --git a/apple/Packages/TableProFFI/Package.swift b/apple/Packages/TableProFFI/Package.swift index 1b2da9df93..f7b66707be 100644 --- a/apple/Packages/TableProFFI/Package.swift +++ b/apple/Packages/TableProFFI/Package.swift @@ -18,6 +18,10 @@ let package = Package( .target( name: "TableProFFI", dependencies: ["TableProFFIC"], + // UniFFI 0.31's Swift for an async foreign trait starts a Task over non-Sendable closures, which Swift 6 + // refuses (mozilla/uniffi-rs#2929). The fix ships in 0.32, which uniffi-bindgen-cs does not support yet, so + // the generated code alone is checked in Swift 5 mode; the apps stay in Swift 6. + swiftSettings: [.swiftLanguageMode(.v5)], linkerSettings: [ .linkedFramework("CoreFoundation"), .linkedFramework("Security"), diff --git a/core/AGENTS.md b/core/AGENTS.md index 0b9a44fb62..34a5cca7d0 100644 --- a/core/AGENTS.md +++ b/core/AGENTS.md @@ -15,7 +15,7 @@ This is the guide for work under `core/`. The root `AGENTS.md` holds the rules e ## Map -- `crates/core`, `crates/net`, `crates/ssh`, `crates/storage`, `crates/session`, `crates/ai`, `crates/mcp`, `crates/cloud-api`, `crates/account`, `crates/keys`, `crates/cli`: the libraries. `crates/drivers/*`: one crate per engine. `crates/ffi`: the library the Windows and Apple apps load (`ARCHITECTURE.md`, Bindings). `crates/bindgen`: the Swift binding generator. `crates/test-fixtures` and `crates/test-support`: test-only. +- `crates/core`, `crates/net`, `crates/ssh`, `crates/storage`, `crates/session`, `crates/ai`, `crates/mcp`, `crates/cloud-api`, `crates/account`, `crates/keys`, `crates/records`, `crates/sync`, `crates/cli`: the libraries. `crates/drivers/*`: one crate per engine. `crates/ffi`: the library the Windows and Apple apps load (`ARCHITECTURE.md`, Bindings). `crates/bindgen`: the Swift binding generator. `crates/test-fixtures`, `crates/test-support` and `crates/sync/testing`: test-only. - `ARCHITECTURE.md`: the crates, the graph, the platform seams and the driver layer. `docs/decisions/`: the cross-platform decisions. - The Cargo workspace and its tool settings are at the top of the repository: `Cargo.toml`, `Cargo.lock`, `rust-toolchain.toml`, `rustfmt.toml`, `clippy.toml`, `deny.toml`, `.config/nextest.toml`. - Until another app builds the core, the Linux docs hold its contracts: `linux/docs/adding-drivers.md`, `linux/docs/drivers/`, `linux/docs/error-handling.md`, `linux/docs/testing.md` and `linux/docs/storage.md`. diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index f416460fea..3862b0c3ff 100644 --- a/core/ARCHITECTURE.md +++ b/core/ARCHITECTURE.md @@ -19,6 +19,8 @@ core/crates/ ├── account/ the TablePro account: sign-in, device, entitlement and the feature gate ├── cloud-api/ tablepro-cloud's /v2 client, generated from the vendored document ├── keys/ end-to-end keys for TablePro Sync: suite tp1, key objects, wraps, envelopes +├── sync/ the sync engine for TablePro Sync and iCloud, its state file and the key flows +│ └── testing/ dev-only fakes: the /v2 server, CloudKit, the device store, the state file, the key flows ├── mcp/ the MCP server: transport, token and tools ├── cli/ the tablepro command line: parsing, the MCP client and the output formats ├── ffi/ the library C# and Swift load: one UniFFI API and the grid's C ABI @@ -55,7 +57,9 @@ core/crates/ | `cloud-api` | no workspace crate | | `account` | `cloud-api`, `core`, `storage` | | `keys` | no workspace crate | -| `ffi` | `account`, `ai`, `cli`, `core`, `foreign-import`, `mcp`, `net`, `records`, `session`, `ssh`, `storage`, and every driver behind its default `engines` feature | +| `sync` | `account`, `cloud-api`, `keys`, `records`, `storage` | +| `sync/testing` (`tablepro-sync-testing`) | `keys`, `records`, `sync` | +| `ffi` | `account`, `ai`, `cli`, `core`, `foreign-import`, `mcp`, `net`, `records`, `session`, `ssh`, `storage`, `sync`, and every driver behind its default `engines` feature | | An app, such as `linux/crates/app` | every crate above, and its platform crate | Rules, enforced by review: @@ -71,10 +75,11 @@ Rules, enforced by review: - `ai` depends on `core` and `net`. It speaks the providers' protocols and builds the prompts from what the app hands it; the app decides what a prompt may carry. - `cloud-api` depends on no workspace crate. It holds the `/v2` client `build.rs` generates from `openapi/v2.openapi-3.0.json`, what a call's problem or 429 answer means, and the one HTTP client a TablePro server is called through; the caller brings the token. `core/scripts/update-cloud-api.sh` refreshes the document. - `keys` depends on no workspace crate and does no I/O: no tokio, network or SQLite. It holds ADR 0056's encodings, key objects and checks over aws-lc-rs, and HPKE from rustls's aws-lc-rs module ([0056](docs/decisions/0056-end-to-end-keys-per-account-and-device.md), Libraries); the flows and the state file build on it. +- `sync` depends on `account`, `cloud-api`, `keys`, `records` and `storage` ([0054](docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md), Crates). Its `api` module holds the contracts its parts build against: the transports, the state file, the device store, the record adapters, the key flows and the control surface `ffi` wraps. CloudKit, the device store and each app's settings reach it through traits the app implements; it never names CloudKit's framework. - `account` depends on `cloud-api`, `core` and `storage`. It reaches the browser, the keyring and the machine ID through what the app passes in ([0016](docs/decisions/0016-tablepro-accounts.md)). - `ffi` stands in for an app outside Rust: it names every driver and passes the host's services in. No other core crate depends on it. - No core crate depends on a GUI toolkit or on a platform crate. An app, or `ffi` for one outside Rust, is the only crate that names every driver. -- `test-support` and `test-fixtures` are dev-dependencies, with one exception: `session` takes `test-support` as an optional dependency behind its `fakes` feature, which only an app's dev-dependencies turn on. +- `test-support`, `test-fixtures` and `sync/testing` are dev-dependencies, with one exception: `session` takes `test-support` as an optional dependency behind its `fakes` feature, which only an app's dev-dependencies turn on. Consequences: @@ -96,6 +101,9 @@ A value or a trait the app passes in: | `RefreshTokenVaults`, `BrowserLauncher`, `WebAuthenticator`, `MachineId`, `AppClient` and `ServerSettings` (`tablepro-account`) | the keyring through `SecretStore`, `gtk::UriLauncher`, `MachineId::derive` of what `tablepro_linux_platform::read_machine_id` reads, `AppClient::LINUX`, tablepro.app | the Core's secret store, one item per server; the `HostBrowser` callback; Windows: `MachineId::derive_machine_guid` of the registry's MachineGuid and `AppClient::WINDOWS` ([ADR 0026](docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md)); the Mac: the `HostWebAuthenticator` callback, its own 64-hex machine ID, `AppClient::MACOS` and its managed policy ([ADR 0047](docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md)) | | `Host` (`tablepro-cli`) | `LinuxHost` in the app crate: the port and switch from GSettings, the token read from the keyring, `NameHasOwner` for a running app, each connection's peer checked by `Host::verify_peer` through `tablepro_net::loopback_peer_is_ours` | `WindowsHost` in `ffi`'s `command_line`, for the `tablepro-cli` program: the port and switch from the app's `settings.json`, the token read from Credential Manager, the app's process id from the `runtime\app.lock` it holds, each peer checked to be that process through `tablepro_net::loopback_peer_process` ([0036](docs/decisions/0036-mcp-and-the-command-line-through-the-ffi.md)) | | `McpHost` (`tablepro-mcp`) | `GtkMcpHost` in the app crate: sessions from the session registry, the write question in the connection's window | `ffi`'s own: sessions `connect_saved` opened, and the `McpAppHost` callback to open a connection and ask about a write ([0036](docs/decisions/0036-mcp-and-the-command-line-through-the-ffi.md)) | +| `CloudKitTransport` (`tablepro-sync`) | none | the Apple apps' `CloudKitTransport`, an async foreign trait `TableProSyncTransport` implements over CloudKit's operations ([0054](docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md)); none on Windows | +| `HostDeviceStore` (`tablepro-sync`): the device keys, the account keys and the state file's anchor, never synced | the Secret Service; none without a keyring, which syncs team records only | the Apple apps' `HostDeviceStore` callback, Keychain items that never sync; on Windows the core's own Credential Manager items with local machine persistence | +| `HostSettings` (`tablepro-sync`) | the app's GSettings | the `HostSettings` callback | | `ForeignAppDirs` and `ForeignHost` (`tablepro-foreign-import`) | `tablepro_linux_platform::foreign_app_dirs`, the host's XDG directories inside a Flatpak, and `PlainHost`: no other app's store | `ForeignAppDirsArg` from the app; on Windows `ffi`'s own host with the user's DPAPI and Credential Manager's generic credentials ([0033](docs/decisions/0033-foreign-import-and-result-editing-through-the-ffi.md), [0039](docs/decisions/0039-dbx-passwords-from-its-key.md)), elsewhere `PlainHost` | A `cfg` split inside a crate: @@ -125,6 +133,7 @@ Each boundary error has a stable `code()`, such as `driver.timeout` or `ssh.host - One UniFFI API. `Core` lists the engines with the family each is listed under, opens a file, connects a saved connection or tests one from a form, and parses a connection URL with `tablepro_core::connection_url`, refusing one that needs a setting its record has no field for. Its `ConnectionLibrary` reads and changes the saved connections with their details and device-only settings, groups, favourites, tags and SSH and credential profiles in `connections.json` and stores their secrets, and gives the Apple apps the library's CloudKit records and merges a pull into it (`tablepro_records::cloudkit::library`). A `DatabaseSession` reads the catalog one level at a time, writes a table's sorted page at an offset and counts the table, writes a query re-run with a sort (`docs/decisions/0007-sorting-a-result.md`), picks the statement at a caret with the session's grammar (`statement_at`), says what completes at a caret for an editor in one of the server's databases as a `CompletionList` that ranks again for each word typed, read from the catalog the other views share (`complete`, over `tablepro_core::sql_syntax::completion` and `tablepro_session::completion`), says what Safe Mode lets an editor run do at the session's level and takes a level saved while it is open (`gate_run`, over `SafeModeLevel::gate`, and `set_safe_mode`), reports and waits on the session's health, opens a `QueryEditor`, and opens a `TableEditor`, which plans a table tab's typed edits into a `RowSave` and runs it (`docs/decisions/0019-row-edits-through-the-ffi.md`). `QueryEditor::run` returns a `QueryRun` at once; the app drains its events after a `RunListener` call, which comes only when no earlier one is waiting to be drained, and the last says which transaction the editor is left in. Each result set is a `ResultSet`, whose `sorted` gives the rows it holds in a column's order. - `Core::open_account` opens the TablePro account as an `AccountService`, whose `AccountListener` only signals that `status()` changed. It also shares links: `create_share` builds a result's snapshot from a `ResultSet` in Rust, and a table page's `view_sql` is the query its view stands for ([ADR 0027](docs/decisions/0027-share-links.md)). `create_share` takes the share sheet's Keep, Mask or Remove for each column, and `ResultSet::share_masking`, `share_preview` and `share_summary` start the sheet's columns from the detectors and show and count what a share sends ([ADR 0028](docs/decisions/0028-data-masking.md)). `scan_sql_for_secrets`, `scan_columns_for_secrets`, `scan_sql_for_personal_data` and `share_token_from_link` are functions of their own. So are `format_sql` and `format_sql_selection`, which reformat a script or a selection through `tablepro_core::sql_syntax::format` and keep a statement as typed where the formatter would change its tokens. +- `Core::open_sync` gives a `SyncService` over an `AccountService`: the status, a pass now, the provider and the moves between providers, the approvals, the team conflicts, the held records, the history window and every key flow a person starts ([0054](docs/decisions/0054-one-sync-engine-in-the-core-for-tablepro-sync-and-icloud.md), [0056](docs/decisions/0056-end-to-end-keys-per-account-and-device.md)). Its `SyncListener` only signals that the status or the keys changed. `CloudKitTransport` is an async foreign trait (`uniffi::export(with_foreign)`), and `HostSettings`, `HostDeviceStore` and the Mac's `HostLegacyMirror`, which reads and writes the Swift engine's metadata while the previous stable runs it, are callback interfaces. - `Core::ai_assistant` gives an `AiAssistant` over the core's one AI client and its secret store: it says whether a provider's key is kept and keeps or removes one (the key never crosses back), lists the provider's models, reads a session's catalog into the system prompt of a conversation (`start_conversation`), and streams a reply as an `AiReply`, drained after an `AiReplyListener` call as a run is. Both refuse a saved connection whose AI policy is Never with `ai.blocked`; asking under Ask is the app's ([ADR 0032](docs/decisions/0032-ai-through-the-ffi.md)). - `Core::mcp_server` gives an `McpService` that runs the MCP server on the sessions `connect_saved` opened, keeps its token in the Core's secret store, and asks the app to open a connection or approve a write through `McpAppHost`; `McpListener` only signals that `status()` or `seen_clients()` changed. The package also builds `tablepro-cli`, the Windows package's command ([0036](docs/decisions/0036-mcp-and-the-command-line-through-the-ffi.md)). - `Core::foreign_sources(dirs, depth)` lists the other apps over `tablepro_foreign_import::sources_blocking`, each with its availability (`Unreadable` with a code when its data is there and cannot be read), password offer, and whether it starts ticked or preselected; `ScanDepthTag::Presence` reads no count. `ForeignImportReview::apply` returns the ids it wrote in `ForeignImportOutcome.connection_ids` ([0057](docs/decisions/0057-a-setup-guide-shows-on-an-empty-library.md)). `keymap_preset(id, platform)` and `keymap_presets(platform)` read `tablepro_core::keymap` for the platform named, never the build target ([0058](docs/decisions/0058-shortcut-presets-from-one-file.md)). @@ -132,7 +141,7 @@ Each boundary error has a stable `code()`, such as `driver.timeout` or `ssh.host - The library owns one tokio runtime. Each async export runs on it and is aborted when the foreign side drops the call; a `CancelToken` stops it sooner, since UniFFI cannot cancel. - A result set takes rows as the driver reads them. Each column keeps a kind byte, a raw `i64` and the exact text `tablepro_core::export::value_text` writes, or a binary value's bytes, in chunks of 65,536 rows. A window only cuts and copies. - A `CoreError` carries the `code()` of each error from the outermost in; the innermost decides. -- A secret crosses as the `SecretString` custom type, a `String` to the app, so Rust holds it in `secrecy` from the lift and wipes it on drop. Still plain: the serialized buffer UniFFI frees for a record, enum, option or callback answer that carries one; for a secret going to the app (`HostSecrets::store` and `store_item`, `ParsedConnectionUrl.password`), the `String` lowered and its buffer; every string the app holds, which the generated C# records also print in full. The blob Credential Manager hands back is wiped before `CredFree`. +- A secret crosses as the `SecretString` custom type, a `String` to the app, so Rust holds it in `secrecy` from the lift and wipes it on drop. Still plain: the serialized buffer UniFFI frees for a record, enum, option or callback answer that carries one; for a secret going to the app (`HostSecrets::store` and `store_item`, `ParsedConnectionUrl.password`), the `String` lowered and its buffer; the device keys, account keys and anchor items `HostDeviceStore` loads and stores, which cross as plain bytes, wrapped in `Zeroizing` only once back in Rust; every string the app holds, which the generated C# records also print in full. The blob Credential Manager hands back is wiped before `CredFree`. How the bindings are generated, and where they live: `windows/AGENTS.md`, Bindings, for C#, and `apple/AGENTS.md`, Repository map, for Swift. diff --git a/core/crates/ffi/Cargo.toml b/core/crates/ffi/Cargo.toml index 120481b5ff..5438c22fcb 100644 --- a/core/crates/ffi/Cargo.toml +++ b/core/crates/ffi/Cargo.toml @@ -51,6 +51,7 @@ tablepro-session = { workspace = true, features = ["in-process-ssh"] } tablepro-ssh = { workspace = true, features = ["in-process"] } tablepro-records.workspace = true tablepro-storage.workspace = true +tablepro-sync.workspace = true async-trait.workspace = true chrono.workspace = true futures.workspace = true @@ -63,6 +64,7 @@ tokio-util.workspace = true tracing.workspace = true uniffi.workspace = true uuid.workspace = true +zeroize.workspace = true [target.'cfg(windows)'.dependencies] windows-sys.workspace = true @@ -70,6 +72,8 @@ windows-sys.workspace = true [dev-dependencies] tablepro-account = { workspace = true, features = ["fakes"] } tablepro-session = { workspace = true, features = ["fakes", "in-process-ssh"] } +tablepro-keys.workspace = true +tablepro-sync-testing.workspace = true tablepro-test-support.workspace = true csbindgen.workspace = true russh.workspace = true diff --git a/core/crates/ffi/src/error.rs b/core/crates/ffi/src/error.rs index b1b442f6ae..ceed70b51b 100644 --- a/core/crates/ffi/src/error.rs +++ b/core/crates/ffi/src/error.rs @@ -39,6 +39,9 @@ pub struct ErrorInfo { // What an `ai.*` error is about; the provider's own words are in `server`. #[uniffi(default = None)] pub ai: Option, + // What a `sync.*` refusal carries beyond its code: a step-up challenge, a wait, a change's code, a lock. + #[uniffi(default = None)] + pub sync: Option, } // Error details stay off the stack while bindings keep the same record values. @@ -120,6 +123,7 @@ impl CoreError { host_key: None, tls_failure: None, ai: None, + sync: None, }), } } @@ -162,6 +166,7 @@ impl ErrorInfo { _ => None, }, ai: None, + sync: None, } } @@ -176,6 +181,7 @@ impl ErrorInfo { host_key: None, tls_failure: None, ai: None, + sync: None, } } } diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 3693eea7e6..b2513fc78a 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -44,6 +44,7 @@ mod saved_queries; mod session; mod statement_at; mod structure; +mod sync; mod syntax; mod table_folders; #[cfg(test)] @@ -138,6 +139,19 @@ pub use session::{ }; pub use statement_at::StatementSpan; pub use structure::{StructureColumn, StructureForeignKey, StructureIndex, TableStructure}; +pub use sync::{ + AccountDeviceInfo, ApprovalRequestInfo, ApprovalSessionInfo, CloudKitAccount, CloudKitChanges, CloudKitDeletion, + CloudKitFailure, CloudKitFetched, CloudKitField, CloudKitOutcome, CloudKitRecord, CloudKitTransport, CloudKitValue, + ConflictChoiceTag, DeviceItemClassTag, DeviceItemTag, FingerprintInfo, GenesisOutcomeTag, HeldReasonTag, + HeldRecordInfo, HeldRestartInfo, HostDeviceStore, HostLegacyMirror, HostSettings, KeyChangeInfo, KeyNoticeInfo, + KeyNoticeKindTag, KeyStateInfo, KeyVersionStateTag, LegacyMetadataArg, LegacyRecordArg, LegacyStandingArg, + LegacyStandingTag, LegacyTombstoneArg, LockCauseTag, MemberKeyStatusTag, MemberKeysInfo, MoveBackPlanInfo, + MovePlanInfo, NewIdentityChoiceTag, PassReasonTag, PendingApprovalInfo, PendingResetInfo, RecoveryKeyDraftInfo, + RemovalReviewInfo, ResetKindTag, ResetStateTag, ReviewedDeviceInfo, ReviewedMemberInfo, RotationDraftInfo, + SessionEndTag, SessionPhaseTag, SessionRoleTag, SettingsCategoryArg, SignOutOutcomeTag, StopCauseTag, + StoppedDeviceInfo, SyncCategoriesArg, SyncConfig, SyncFailureInfo, SyncListener, SyncPhaseTag, SyncPlatformTag, + SyncRecordRef, SyncService, SyncStatusInfo, TeamConflictInfo, TeamKeysInfo, TeamRoleTag, device_item_class, +}; pub use syntax::SqlGrammarTag; pub use table_folders::{TableFolderItemRecord, TableFolderRecord, TableFolderStore, TableRefRecord}; diff --git a/core/crates/ffi/src/sync/cloudkit.rs b/core/crates/ffi/src/sync/cloudkit.rs new file mode 100644 index 0000000000..28baaacf27 --- /dev/null +++ b/core/crates/ffi/src/sync/cloudkit.rs @@ -0,0 +1,441 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use tablepro_sync::api::cloudkit as sync; + +// 0054, The CloudKit transport: Swift implements it in `TableProSyncTransport` over CloudKit's operations and decides +// nothing. The core never calls it under a lock, and dropping a call cancels the Swift task, which cancels its +// operation. Every call names the iCloud user record name the pass's state file is bound to. +#[uniffi::export(with_foreign)] +#[async_trait] +pub trait CloudKitTransport: Send + Sync { + async fn account_status(&self) -> Result; + + async fn ensure_zone(&self, account: String) -> Result<(), CloudKitFailure>; + + async fn delete_zone(&self, account: String) -> Result<(), CloudKitFailure>; + + async fn fetch_changes(&self, account: String, token: Option>) -> Result; + + async fn fetch_records(&self, account: String, names: Vec) + -> Result, CloudKitFailure>; + + async fn modify( + &self, + account: String, + saves: Vec, + deletes: Vec, + ) -> Result, CloudKitFailure>; +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CloudKitAccount { + pub user_record_name: String, +} + +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct CloudKitRecord { + pub record_type: String, + pub name: String, + // `CKRecord.encodeSystemFields(with:)`; a create sends none. + pub system_fields: Option>, + // `CKRecord.creationDate` in milliseconds, on a record CloudKit returned; None on a save. + pub created_ms: Option, + pub fields: Vec, +} + +// None clears the field. +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct CloudKitField { + pub name: String, + pub value: Option, +} + +#[derive(Debug, Clone, PartialEq, uniffi::Enum)] +pub enum CloudKitValue { + Text { value: String }, + Int64 { value: i64 }, + Double { value: f64 }, + // Milliseconds since the Unix epoch. + Timestamp { value: i64 }, + Bytes { value: Vec }, + TextList { value: Vec }, +} + +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct CloudKitChanges { + pub changed: Vec, + pub deleted: Vec, + pub unfetched: Vec, + pub token: Vec, + pub more: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CloudKitDeletion { + pub name: String, + pub record_type: String, +} + +#[derive(Debug, Clone, PartialEq, uniffi::Enum)] +pub enum CloudKitFetched { + Found { + record: CloudKitRecord, + }, + Missing { + name: String, + }, + Failed { + name: String, + code: i64, + retry_after_ms: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, uniffi::Enum)] +pub enum CloudKitOutcome { + Saved { + name: String, + system_fields: Vec, + }, + Deleted { + name: String, + }, + ServerChanged { + name: String, + server: Option, + }, + UnknownItem { + name: String, + }, + Failed { + name: String, + code: i64, + retry_after_ms: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)] +pub enum CloudKitFailure { + #[error("no iCloud account")] + NoAccount, + #[error("iCloud is restricted")] + Restricted, + #[error("the iCloud account is temporarily unavailable")] + AccountTemporarilyUnavailable, + #[error("the iCloud account changed during the call")] + AccountChanged, + #[error("the change token expired")] + TokenExpired, + #[error("the zone does not exist")] + ZoneNotFound, + #[error("the person deleted the zone")] + ZoneDeletedByUser, + #[error("the batch is over CloudKit's limit")] + LimitExceeded, + #[error("the iCloud quota is exceeded")] + QuotaExceeded, + #[error("the network failed")] + Network, + #[error("CloudKit is throttling")] + Throttled { retry_after_ms: Option }, + #[error("CloudKit failed with code {code}")] + Other { code: i64 }, +} + +// A Swift implementation that threw something it should not have is a failure the engine backs off from. +impl From for CloudKitFailure { + fn from(_: uniffi::UnexpectedUniFFICallbackError) -> Self { + Self::Other { code: -1 } + } +} + +// The host's transport under the engine's trait. +pub(crate) struct CloudKitBridge(pub(crate) Arc); + +impl std::fmt::Debug for CloudKitBridge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("CloudKitBridge") + } +} + +#[async_trait] +impl sync::CloudKitTransport for CloudKitBridge { + async fn account_status(&self) -> Result { + let account = self.0.account_status().await?; + Ok(sync::CloudKitAccount { + user_record_name: account.user_record_name, + }) + } + + async fn ensure_zone(&self, account: String) -> Result<(), sync::CloudKitFailure> { + Ok(self.0.ensure_zone(account).await?) + } + + async fn delete_zone(&self, account: String) -> Result<(), sync::CloudKitFailure> { + Ok(self.0.delete_zone(account).await?) + } + + async fn fetch_changes( + &self, + account: String, + token: Option>, + ) -> Result { + let changes = self.0.fetch_changes(account, token).await?; + Ok(sync::CloudKitChanges { + changed: changes.changed.into_iter().map(Into::into).collect(), + deleted: changes + .deleted + .into_iter() + .map(|deletion| sync::CloudKitDeletion { + name: deletion.name, + record_type: deletion.record_type, + }) + .collect(), + unfetched: changes.unfetched, + token: changes.token, + more: changes.more, + }) + } + + async fn fetch_records( + &self, + account: String, + names: Vec, + ) -> Result, sync::CloudKitFailure> { + let fetched = self.0.fetch_records(account, names).await?; + Ok(fetched + .into_iter() + .map(|fetched| match fetched { + CloudKitFetched::Found { record } => sync::CloudKitFetched::Found { record: record.into() }, + CloudKitFetched::Missing { name } => sync::CloudKitFetched::Missing { name }, + CloudKitFetched::Failed { + name, + code, + retry_after_ms, + } => sync::CloudKitFetched::Failed { + name, + code, + retry_after_ms, + }, + }) + .collect()) + } + + async fn modify( + &self, + account: String, + saves: Vec, + deletes: Vec, + ) -> Result, sync::CloudKitFailure> { + let saves = saves.into_iter().map(Into::into).collect(); + let outcomes = self.0.modify(account, saves, deletes).await?; + Ok(outcomes.into_iter().map(Into::into).collect()) + } +} + +impl From for sync::CloudKitFailure { + fn from(failure: CloudKitFailure) -> Self { + match failure { + CloudKitFailure::NoAccount => Self::NoAccount, + CloudKitFailure::Restricted => Self::Restricted, + CloudKitFailure::AccountTemporarilyUnavailable => Self::AccountTemporarilyUnavailable, + CloudKitFailure::AccountChanged => Self::AccountChanged, + CloudKitFailure::TokenExpired => Self::TokenExpired, + CloudKitFailure::ZoneNotFound => Self::ZoneNotFound, + CloudKitFailure::ZoneDeletedByUser => Self::ZoneDeletedByUser, + CloudKitFailure::LimitExceeded => Self::LimitExceeded, + CloudKitFailure::QuotaExceeded => Self::QuotaExceeded, + CloudKitFailure::Network => Self::Network, + CloudKitFailure::Throttled { retry_after_ms } => Self::Throttled { retry_after_ms }, + CloudKitFailure::Other { code } => Self::Other { code }, + } + } +} + +impl From for sync::CloudKitValue { + fn from(value: CloudKitValue) -> Self { + match value { + CloudKitValue::Text { value } => Self::Text(value), + CloudKitValue::Int64 { value } => Self::Int64(value), + CloudKitValue::Double { value } => Self::Double(value), + CloudKitValue::Timestamp { value } => Self::Timestamp(value), + CloudKitValue::Bytes { value } => Self::Bytes(value), + CloudKitValue::TextList { value } => Self::TextList(value), + } + } +} + +impl From for CloudKitValue { + fn from(value: sync::CloudKitValue) -> Self { + match value { + sync::CloudKitValue::Text(value) => Self::Text { value }, + sync::CloudKitValue::Int64(value) => Self::Int64 { value }, + sync::CloudKitValue::Double(value) => Self::Double { value }, + sync::CloudKitValue::Timestamp(value) => Self::Timestamp { value }, + sync::CloudKitValue::Bytes(value) => Self::Bytes { value }, + sync::CloudKitValue::TextList(value) => Self::TextList { value }, + } + } +} + +impl From for sync::CloudKitRecord { + fn from(record: CloudKitRecord) -> Self { + Self { + record_type: record.record_type, + name: record.name, + system_fields: record.system_fields, + created_ms: record.created_ms, + fields: record + .fields + .into_iter() + .map(|field| sync::CloudKitField { + name: field.name, + value: field.value.map(Into::into), + }) + .collect(), + } + } +} + +impl From for CloudKitRecord { + fn from(record: sync::CloudKitRecord) -> Self { + Self { + record_type: record.record_type, + name: record.name, + system_fields: record.system_fields, + created_ms: record.created_ms, + fields: record + .fields + .into_iter() + .map(|field| CloudKitField { + name: field.name, + value: field.value.map(Into::into), + }) + .collect(), + } + } +} + +impl From for sync::CloudKitOutcome { + fn from(outcome: CloudKitOutcome) -> Self { + match outcome { + CloudKitOutcome::Saved { name, system_fields } => Self::Saved { name, system_fields }, + CloudKitOutcome::Deleted { name } => Self::Deleted { name }, + CloudKitOutcome::ServerChanged { name, server } => Self::ServerChanged { + name, + server: server.map(Into::into), + }, + CloudKitOutcome::UnknownItem { name } => Self::UnknownItem { name }, + CloudKitOutcome::Failed { + name, + code, + retry_after_ms, + } => Self::Failed { + name, + code, + retry_after_ms, + }, + } + } +} + +#[cfg(test)] +mod tests { + use tablepro_sync::api::cloudkit::CloudKitTransport as _; + use tablepro_sync_testing::FakeCloudKit; + + use super::*; + + // The Swift side as the bindings see it, here over the core's fake, so the bridge is checked both ways. + struct Host(FakeCloudKit); + + #[async_trait] + impl CloudKitTransport for Host { + async fn account_status(&self) -> Result { + let account = self.0.account_status().await.map_err(|_| CloudKitFailure::NoAccount)?; + Ok(CloudKitAccount { + user_record_name: account.user_record_name, + }) + } + + async fn ensure_zone(&self, account: String) -> Result<(), CloudKitFailure> { + self.0 + .ensure_zone(account) + .await + .map_err(|_| CloudKitFailure::ZoneNotFound) + } + + async fn delete_zone(&self, account: String) -> Result<(), CloudKitFailure> { + self.0 + .delete_zone(account) + .await + .map_err(|_| CloudKitFailure::ZoneNotFound) + } + + async fn fetch_changes(&self, _: String, _: Option>) -> Result { + Err(CloudKitFailure::TokenExpired) + } + + async fn fetch_records(&self, _: String, _: Vec) -> Result, CloudKitFailure> { + Err(CloudKitFailure::Throttled { + retry_after_ms: Some(30), + }) + } + + async fn modify( + &self, + account: String, + saves: Vec, + deletes: Vec, + ) -> Result, CloudKitFailure> { + let saves = saves.into_iter().map(Into::into).collect(); + let outcomes = self + .0 + .modify(account, saves, deletes) + .await + .map_err(|_| CloudKitFailure::LimitExceeded)?; + Ok(outcomes + .into_iter() + .map(|outcome| match outcome { + sync::CloudKitOutcome::Saved { name, system_fields } => { + CloudKitOutcome::Saved { name, system_fields } + } + other => CloudKitOutcome::UnknownItem { + name: other.name().to_owned(), + }, + }) + .collect()) + } + } + + #[tokio::test] + async fn the_bridge_carries_records_outcomes_and_failures_unchanged() { + let bridge = CloudKitBridge(Arc::new(Host(FakeCloudKit::signed_in("_a")))); + bridge.ensure_zone("_a".to_owned()).await.unwrap(); + let record = sync::CloudKitRecord { + record_type: "Tag".to_owned(), + name: "Tag_A".to_owned(), + system_fields: None, + created_ms: None, + fields: vec![sync::CloudKitField { + name: "name".to_owned(), + value: Some(sync::CloudKitValue::TextList(vec!["a".to_owned()])), + }], + }; + + let outcomes = bridge.modify("_a".to_owned(), vec![record], Vec::new()).await.unwrap(); + let expired = bridge.fetch_changes("_a".to_owned(), None).await; + let throttled = bridge.fetch_records("_a".to_owned(), Vec::new()).await; + + assert!(matches!(&outcomes[0], sync::CloudKitOutcome::Saved { name, .. } if name == "Tag_A")); + assert_eq!(bridge.account_status().await.unwrap().user_record_name, "_a"); + assert_eq!(expired.unwrap_err(), sync::CloudKitFailure::TokenExpired); + assert_eq!( + throttled.unwrap_err(), + sync::CloudKitFailure::Throttled { + retry_after_ms: Some(30) + } + ); + } +} diff --git a/core/crates/ffi/src/sync/host.rs b/core/crates/ffi/src/sync/host.rs new file mode 100644 index 0000000000..a7d7c748d4 --- /dev/null +++ b/core/crates/ffi/src/sync/host.rs @@ -0,0 +1,268 @@ +// The app's sides of sync that only the app can do: its settings, kept its own way (0054, Adapters), and its device +// store, for the keys and the state file's anchor (0054, Integrity and freshness). Each call may block, so the core +// makes it on a blocking thread, never under a lock. + +use std::sync::Arc; + +use async_trait::async_trait; +use tablepro_records::Kind; +use tablepro_session::runtime::Tasks; +use tablepro_sync::api::{self as sync, AdapterError, DeviceStoreError, SettingsDocument}; +use zeroize::Zeroizing; + +use crate::host::HostSecretError; + +#[uniffi::export(callback_interface)] +pub trait HostSettings: Send + Sync { + // Every category of the platform's registry that holds a value, each as one JSON document. + fn categories(&self) -> Result, HostSecretError>; + + // None removes the category, as a deleted theme. + fn apply(&self, category: String, document: Option) -> Result<(), HostSecretError>; +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SettingsCategoryArg { + pub category: String, + pub document: String, +} + +// Keychain items that never sync: `ThisDeviceOnly` for keys, `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly` for +// the anchor (`DeviceItemClassTag`). Windows' Credential Manager and Linux's Secret Service are the core's own. +#[uniffi::export(callback_interface)] +pub trait HostDeviceStore: Send + Sync { + fn load(&self, item: DeviceItemTag) -> Result>, HostSecretError>; + + fn store(&self, item: DeviceItemTag, value: Vec) -> Result<(), HostSecretError>; + + // Deleting an item that is not there succeeds. + fn delete(&self, item: DeviceItemTag) -> Result<(), HostSecretError>; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, uniffi::Enum)] +pub enum DeviceItemClassTag { + Keys, + Anchor, +} + +// One item, named by what it holds. Ids are upper-case UUID text; a state file's name and a checkpoint are hex. +#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Enum)] +pub enum DeviceItemTag { + DeviceKeys { + origin: String, + account: String, + device_row: String, + }, + AccountKeys { + origin: String, + account: String, + av: u32, + }, + ResetKeys { + origin: String, + account: String, + reset: String, + }, + StateMacKey { + state: String, + }, + AnchorRoot { + state: String, + }, + AnchorCheckpoint { + state: String, + checkpoint: String, + part: u32, + }, +} + +impl DeviceItemTag { + pub(crate) fn of(item: &sync::DeviceItem) -> Self { + use sync::DeviceItem; + let hex = |bytes: &[u8]| bytes.iter().map(|byte| format!("{byte:02x}")).collect::(); + match item { + DeviceItem::DeviceKeys { + origin, + account, + device_row, + } => Self::DeviceKeys { + origin: origin.as_str().to_owned(), + account: account.to_wire(), + device_row: device_row.0.clone(), + }, + DeviceItem::AccountKeys { origin, account, av } => Self::AccountKeys { + origin: origin.as_str().to_owned(), + account: account.to_wire(), + av: av.get(), + }, + DeviceItem::ResetKeys { origin, account, reset } => Self::ResetKeys { + origin: origin.as_str().to_owned(), + account: account.to_wire(), + reset: reset.to_wire(), + }, + DeviceItem::StateMacKey { state } => Self::StateMacKey { state: state.0.clone() }, + DeviceItem::AnchorRoot { state } => Self::AnchorRoot { state: state.0.clone() }, + DeviceItem::AnchorCheckpoint { + state, + checkpoint, + part, + } => Self::AnchorCheckpoint { + state: state.0.clone(), + checkpoint: hex(checkpoint), + part: *part, + }, + } + } + + pub fn class(&self) -> DeviceItemClassTag { + match self { + Self::DeviceKeys { .. } | Self::AccountKeys { .. } | Self::ResetKeys { .. } => DeviceItemClassTag::Keys, + Self::StateMacKey { .. } | Self::AnchorRoot { .. } | Self::AnchorCheckpoint { .. } => { + DeviceItemClassTag::Anchor + } + } + } +} + +// Which class the host stores an item in. +#[uniffi::export] +pub fn device_item_class(item: DeviceItemTag) -> DeviceItemClassTag { + item.class() +} + +fn store_error(error: HostSecretError) -> DeviceStoreError { + match error { + HostSecretError::Unavailable { detail } => DeviceStoreError::Unavailable { detail }, + HostSecretError::Locked => DeviceStoreError::Locked, + HostSecretError::Dismissed => DeviceStoreError::Failed { + detail: "the unlock prompt was dismissed".to_owned(), + }, + HostSecretError::Failed { detail } => DeviceStoreError::Failed { detail }, + } +} + +fn failed(failure: impl std::fmt::Display) -> DeviceStoreError { + DeviceStoreError::Failed { + detail: failure.to_string(), + } +} + +// The host's device store under the engine's trait, each call on a blocking thread. +pub(crate) struct HostDeviceStoreBridge { + pub(crate) host: Arc, + pub(crate) tasks: Tasks, +} + +#[async_trait] +impl sync::HostDeviceStore for HostDeviceStoreBridge { + async fn load(&self, item: sync::DeviceItem) -> Result>>, DeviceStoreError> { + let (host, tag) = (Arc::clone(&self.host), DeviceItemTag::of(&item)); + let loaded = self + .tasks + .spawn_blocking_task(move || host.load(tag)) + .await + .map_err(failed)?; + loaded.map(|value| value.map(Zeroizing::new)).map_err(store_error) + } + + async fn store(&self, item: sync::DeviceItem, value: Zeroizing>) -> Result<(), DeviceStoreError> { + let (host, tag) = (Arc::clone(&self.host), DeviceItemTag::of(&item)); + let value = value.to_vec(); + let stored = self + .tasks + .spawn_blocking_task(move || host.store(tag, value)) + .await + .map_err(failed)?; + stored.map_err(store_error) + } + + async fn delete(&self, item: sync::DeviceItem) -> Result<(), DeviceStoreError> { + let (host, tag) = (Arc::clone(&self.host), DeviceItemTag::of(&item)); + let deleted = self + .tasks + .spawn_blocking_task(move || host.delete(tag)) + .await + .map_err(failed)?; + deleted.map_err(store_error) + } +} + +// The host's settings under the engine's trait; documents cross as JSON text. +pub(crate) struct HostSettingsBridge { + pub(crate) host: Arc, + pub(crate) kind: Kind, + pub(crate) tasks: Tasks, +} + +fn host_error(failure: impl std::fmt::Display) -> AdapterError { + AdapterError::Host { + detail: failure.to_string(), + } +} + +#[async_trait] +impl sync::HostSettings for HostSettingsBridge { + fn kind(&self) -> Kind { + self.kind + } + + async fn categories(&self) -> Result, AdapterError> { + let host = Arc::clone(&self.host); + let categories = self + .tasks + .spawn_blocking_task(move || host.categories()) + .await + .map_err(host_error)?; + categories + .map_err(host_error)? + .into_iter() + .map(|category| { + let document = serde_json::from_str(&category.document).map_err(host_error)?; + Ok(SettingsDocument { + category: category.category, + document, + }) + }) + .collect() + } + + async fn apply(&self, category: String, document: Option) -> Result<(), AdapterError> { + let host = Arc::clone(&self.host); + let document = document.map(|document| document.to_string()); + let applied = self + .tasks + .spawn_blocking_task(move || host.apply(category, document)) + .await + .map_err(host_error)?; + applied.map_err(host_error) + } +} + +#[cfg(test)] +mod tests { + use tablepro_keys::encoding::{AccountId, Origin, Version}; + use tablepro_sync::api::DeviceItem; + use tablepro_sync::api::ids::StateName; + use uuid::Uuid; + + use super::*; + + #[test] + fn an_item_keeps_its_class_across_the_boundary() { + let origin = Origin::parse("https://api.tablepro.app").unwrap(); + let keys = DeviceItem::AccountKeys { + origin, + account: AccountId(Uuid::nil()), + av: Version::new(3).unwrap(), + }; + let anchor = DeviceItem::AnchorRoot { + state: StateName("ab".repeat(32)), + }; + + let tag = DeviceItemTag::of(&anchor); + + assert_eq!(device_item_class(DeviceItemTag::of(&keys)), DeviceItemClassTag::Keys); + assert_eq!(tag.class(), DeviceItemClassTag::Anchor); + assert_eq!(tag, DeviceItemTag::AnchorRoot { state: "ab".repeat(32) }); + } +} diff --git a/core/crates/ffi/src/sync/keys.rs b/core/crates/ffi/src/sync/keys.rs new file mode 100644 index 0000000000..0a07438e65 --- /dev/null +++ b/core/crates/ffi/src/sync/keys.rs @@ -0,0 +1,508 @@ +// The end-to-end flows a person starts (core ADR 0056), over `tablepro_sync::api::KeyFlows`. Ids are upper-case +// UUID text, a team its scope name (`team_...`). + +use secrecy::SecretString; +use tablepro_sync::api::key_flows::LockCause; + +use super::service::{SyncService, unfilled}; +use crate::error::CoreError; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum LockCauseTag { + DeviceRemoved, + LeftOutOfRotation, + OwnAccountReset, + AccountEnded, + Unanchored, + PersonalStopped, +} + +impl From for LockCauseTag { + fn from(cause: LockCause) -> Self { + match cause { + LockCause::DeviceRemoved => Self::DeviceRemoved, + LockCause::LeftOutOfRotation => Self::LeftOutOfRotation, + LockCause::OwnAccountReset => Self::OwnAccountReset, + LockCause::AccountEnded => Self::AccountEnded, + LockCause::Unanchored => Self::Unanchored, + LockCause::PersonalStopped => Self::PersonalStopped, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum KeyStateInfo { + NoDeviceStore, + Unknown, + NoKeys, + NeedsApproval { request: Option }, + Approved { av: u32, key_device: String }, + Locked { cause: LockCauseTag }, +} + +// R, shown once, and the two of its 14 groups the person types back. +#[derive(Debug, Clone, uniffi::Record)] +pub struct RecoveryKeyDraftInfo { + pub draft: String, + pub text: SecretString, + pub check: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum GenesisOutcomeTag { + Created, + AnotherDeviceWon, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SignOutOutcomeTag { + Revoked, + ErasedOffline, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct FingerprintInfo { + pub words: Vec, + pub qr: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum ResetStateTag { + Pending, + Cancelled, + Superseded, + Active, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ResetKindTag { + KeepScopeKeys, + StartEmpty, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +// Why a team stopped on this device (core ADR 0062): a catch-up an owner or admin confirms again, or a wait for a +// version a restore lost, which clears by itself once its signer's device pushes it back. +pub enum StopCauseTag { + CatchUp, + RestoreWait, + // A team restart held until the person compares the restarting owner's words (core ADR 0064). + RestartHeld, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum KeyNoticeKindTag { + RecoveryKeyReplaced { account: String }, + KeysChanged { account: String }, + TeamKeyRestarted { team: String }, + RestartHeld { team: String, signer: String }, + ResetPending { reset: String }, + ResetEnded { reset: String, state: ResetStateTag }, + DeviceRemoved { device: String }, + SupersededWrap { team: String }, + Conflict { scope: String }, + ScopeStopped { scope: String, cause: StopCauseTag }, + ScopeEnded { scope: String }, + Locked { cause: LockCauseTag }, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct KeyNoticeInfo { + pub id: String, + pub kind: KeyNoticeKindTag, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ApprovalRequestInfo { + pub request: String, + pub device: Option, + pub device_name: Option, + pub platform: Option, + pub requested_at_us: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SessionRoleTag { + NewDevice, + Approver, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SessionEndTag { + User, + Mismatch, + Commitment, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum SessionPhaseTag { + Open, + Chosen, + // The five words, shown once per session. + Compare { words: Vec }, + Confirmed, + Approved, + // "Being approved on Mac mini." + TakenElsewhere, + Cancelled { reason: SessionEndTag }, + Expired, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ApprovalSessionInfo { + pub request: String, + pub role: SessionRoleTag, + pub phase: SessionPhaseTag, + pub expires_at_us: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct AccountDeviceInfo { + pub key_device: String, + pub device: Option, + pub name: Option, + pub platform: Option, + pub added_at_us: Option, + pub this_device: bool, + pub compared: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ReviewedDeviceInfo { + pub device: AccountDeviceInfo, + pub keep_by_default: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ReviewedMemberInfo { + pub team: String, + pub account: String, + pub confirmed_under_av: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct RemovalReviewInfo { + pub review: String, + pub devices: Vec, + pub members: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PendingResetInfo { + pub reset: String, + pub kind: ResetKindTag, + pub state: ResetStateTag, + pub mine: bool, + pub proposed_by: Option, + pub taken_at_us: i64, + pub held_until_us: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum KeyVersionStateTag { + Ok, + Stopped, + Ended, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum MemberKeyStatusTag { + NoKeys, + AwaitingConfirmation, + Holder, + Alert, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TeamRoleTag { + Owner, + Admin, + Editor, + Member, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct MemberKeysInfo { + pub account: String, + pub role: TeamRoleTag, + pub status: MemberKeyStatusTag, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TeamKeysInfo { + pub team: String, + pub version: Option, + pub state: KeyVersionStateTag, + pub stopped_cause: Option, + pub rotation_due: bool, + pub holder: bool, + pub members: Vec, + pub stopped: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct HeldRestartInfo { + pub team: String, + pub version: u32, + pub signer: String, + pub signer_ik: String, + pub words: FingerprintInfo, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct StoppedDeviceInfo { + pub account: String, + pub device: String, + pub version: u32, + // This account held that version, so the app offers to confirm the device again by rotating. + pub can_reconfirm: bool, +} + +#[derive(Debug, Clone, uniffi::Record)] +pub struct RotationDraftInfo { + pub recovery: RecoveryKeyDraftInfo, + pub devices: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct KeyChangeInfo { + pub account: String, + pub pinned: FingerprintInfo, + pub offered: FingerprintInfo, + pub offered_ik: String, +} + +#[uniffi::export] +impl SyncService { + pub async fn key_state(&self) -> Result { + unfilled("keys.key_state") + } + + pub async fn begin_genesis(&self) -> Result { + unfilled("keys.begin_genesis") + } + + // `typed` holds the two groups in the order `check` named them. + pub async fn finish_genesis( + &self, + draft: String, + typed: Vec, + ) -> Result { + let _ = (draft, typed); + unfilled("keys.finish_genesis") + } + + pub async fn sign_out_keys(&self) -> Result { + unfilled("keys.sign_out") + } + + // R' and the devices the rotation can keep. + pub async fn begin_replace_recovery_key(&self, recovery_key: SecretString) -> Result { + let _ = recovery_key; + unfilled("keys.begin_replace") + } + + // `keep` holds the key device ids the person ticked. + pub async fn finish_replace_recovery_key( + &self, + draft: String, + typed: Vec, + keep: Vec, + ) -> Result<(), CoreError> { + let _ = (draft, typed, keep); + unfilled("keys.finish_replace") + } + + pub async fn own_fingerprint(&self) -> Result { + unfilled("keys.own_fingerprint") + } + + pub async fn account_fingerprint(&self, account: String) -> Result { + let _ = account; + unfilled("keys.fingerprint") + } + + pub async fn compare_fingerprint_qr(&self, account: String, text: String) -> Result { + let _ = (account, text); + unfilled("keys.compare_qr") + } + + // Accepting without comparing is recorded as `first_use`. + // The pinned and the offered identity of an account under a key-change alert, to compare. + pub async fn account_key_change(&self, account: String) -> Result, CoreError> { + let _ = account; + unfilled("keys.key_change") + } + + // `offered_ik` is the one `account_key_change` showed, as base64url. + pub async fn accept_key_change( + &self, + account: String, + offered_ik: String, + compared: bool, + ) -> Result<(), CoreError> { + let _ = (account, offered_ik, compared); + unfilled("keys.accept_key_change") + } + + pub async fn key_notices(&self) -> Result, CoreError> { + unfilled("keys.notices") + } + + pub async fn dismiss_key_notice(&self, notice: String) -> Result<(), CoreError> { + let _ = notice; + unfilled("keys.dismiss_notice") + } + + pub async fn request_approval(&self) -> Result { + unfilled("keys.request_approval") + } + + pub async fn approval_requests(&self) -> Result, CoreError> { + unfilled("keys.approval_requests") + } + + pub async fn choose_approval_request(&self, request: String) -> Result { + let _ = request; + unfilled("keys.choose_request") + } + + pub async fn approval_session(&self, request: String) -> Result { + let _ = request; + unfilled("keys.approval_session") + } + + pub async fn confirm_approval_session(&self, request: String) -> Result { + let _ = request; + unfilled("keys.confirm_session") + } + + pub async fn approval_words_differ(&self, request: String) -> Result<(), CoreError> { + let _ = request; + unfilled("keys.words_differ") + } + + pub async fn cancel_approval_session(&self, request: String) -> Result<(), CoreError> { + let _ = request; + unfilled("keys.cancel_session") + } + + pub async fn account_devices(&self) -> Result, CoreError> { + unfilled("keys.account_devices") + } + + // `sync.step_up_required` until the account's step-up is fresh. + pub async fn remove_device_row(&self, device: String) -> Result<(), CoreError> { + let _ = device; + unfilled("keys.remove_device_row") + } + + pub async fn begin_device_removal( + &self, + recovery_key: SecretString, + lost: Vec, + ) -> Result { + let _ = (recovery_key, lost); + unfilled("keys.begin_removal") + } + + pub async fn finish_device_removal( + &self, + review: String, + keep: Vec, + remove: Vec, + ) -> Result<(), CoreError> { + let _ = (review, keep, remove); + unfilled("keys.finish_removal") + } + + pub async fn recover_with_recovery_key(&self, recovery_key: SecretString) -> Result<(), CoreError> { + let _ = recovery_key; + unfilled("keys.recover") + } + + pub async fn pending_reset(&self) -> Result, CoreError> { + unfilled("keys.pending_reset") + } + + pub async fn begin_reset(&self, kind: ResetKindTag) -> Result { + let _ = kind; + unfilled("keys.begin_reset") + } + + pub async fn finish_reset_proposal( + &self, + draft: String, + typed: Vec, + ) -> Result { + let _ = (draft, typed); + unfilled("keys.finish_reset_proposal") + } + + // With no recovery key, this device cancels as one certified at the current `av`. + pub async fn cancel_reset(&self, reset: String, recovery_key: Option) -> Result<(), CoreError> { + let _ = (reset, recovery_key); + unfilled("keys.cancel_reset") + } + + pub async fn activate_reset(&self, reset: String) -> Result<(), CoreError> { + let _ = reset; + unfilled("keys.activate_reset") + } + + pub async fn team_keys(&self, team: String) -> Result { + let _ = team; + unfilled("keys.team_keys") + } + + pub async fn create_team_keys(&self, team: String) -> Result<(), CoreError> { + let _ = team; + unfilled("keys.create_team_keys") + } + + pub async fn confirm_member(&self, team: String, account: String) -> Result<(), CoreError> { + let _ = (team, account); + unfilled("keys.confirm_member") + } + + pub async fn rotate_team_key(&self, team: String, remove: Vec) -> Result<(), CoreError> { + let _ = (team, remove); + unfilled("keys.rotate_team") + } + + pub async fn restart_team_key(&self, team: String, confirm: Vec) -> Result<(), CoreError> { + let _ = (team, confirm); + unfilled("keys.restart_team") + } + + // A restart this device holds until the person compares the restarting owner's words. + pub async fn held_team_restart(&self, team: String) -> Result, CoreError> { + let _ = team; + unfilled("keys.held_restart") + } + + // `signer_ik` is the one `held_team_restart` showed, as base64url; there is no accept without comparing. + pub async fn accept_team_restart(&self, team: String, signer_ik: String) -> Result<(), CoreError> { + let _ = (team, signer_ik); + unfilled("keys.accept_restart") + } + + // The envelope ids a removed party could read, for "Credentials to rotate". + pub async fn credentials_to_rotate(&self, scope: String) -> Result, CoreError> { + let _ = scope; + unfilled("keys.credentials_to_rotate") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_unfilled_call_names_the_flow_in_its_error() { + let error = unfilled::<()>("keys.begin_genesis").unwrap_err(); + + assert_eq!(error.code(), "sync.unimplemented"); + assert!(error.to_string().contains("keys.begin_genesis")); + } +} diff --git a/core/crates/ffi/src/sync/legacy.rs b/core/crates/ffi/src/sync/legacy.rs new file mode 100644 index 0000000000..22859e6771 --- /dev/null +++ b/core/crates/ffi/src/sync/legacy.rs @@ -0,0 +1,274 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use tablepro_session::runtime::Tasks; +use tablepro_sync::api::AdapterError; +use tablepro_sync::api::legacy as sync; +use tablepro_sync::api::state::Standing; +use uuid::Uuid; + +use super::cloudkit::CloudKitRecord; +use crate::host::HostSecretError; + +// The Mac's Swift sync metadata in UserDefaults and `SyncRecordCache` (core ADR 0054, Downgrade mirror). Each call +// may block, so the core makes it on a blocking thread. +#[uniffi::export(callback_interface)] +pub trait HostLegacyMirror: Send + Sync { + fn read(&self) -> Result; + + fn write(&self, metadata: LegacyMetadataArg) -> Result<(), HostSecretError>; + + fn mark(&self, dirty: Vec, tombstones: Vec) -> Result<(), HostSecretError>; +} + +#[derive(Debug, Clone, PartialEq, uniffi::Record)] +pub struct LegacyMetadataArg { + pub token: Option>, + pub dirty: Vec, + pub tombstones: Vec, + pub deferred_deletions: Vec, + pub changes_held_for_unreadable: Vec, + pub removals_pending_for_unreadable: Vec, + pub deletions_held_for_unreadable: Vec, + // Upper-case UUID text. + pub owners_kept_off_sync: Vec, + pub standing: Vec, + pub readable_record_types: Vec, + pub account: Option, + pub zone_state: Option, + pub cache: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Record)] +pub struct LegacyRecordArg { + pub record_type: String, + pub id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Record)] +pub struct LegacyTombstoneArg { + pub record: LegacyRecordArg, + // Milliseconds since the Unix epoch. + pub deleted_at_ms: i64, + pub owner: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, uniffi::Enum)] +pub enum LegacyStandingTag { + Syncs, + LocalOnly, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Record)] +pub struct LegacyStandingArg { + pub connection: String, + pub standing: LegacyStandingTag, +} + +fn uuid(text: &str) -> Result { + Uuid::parse_str(text).map_err(|_| AdapterError::Host { + detail: "the legacy metadata holds an id that is not a UUID".to_owned(), + }) +} + +fn wire_uuid(id: Uuid) -> String { + id.hyphenated().to_string().to_uppercase() +} + +impl From for sync::LegacyRecordRef { + fn from(record: LegacyRecordArg) -> Self { + Self { + record_type: record.record_type, + id: record.id, + } + } +} + +impl From for LegacyRecordArg { + fn from(record: sync::LegacyRecordRef) -> Self { + Self { + record_type: record.record_type, + id: record.id, + } + } +} + +impl From for LegacyTombstoneArg { + fn from(tombstone: sync::LegacyTombstone) -> Self { + Self { + record: tombstone.record.into(), + deleted_at_ms: tombstone.deleted_at_ms, + owner: tombstone.owner.map(wire_uuid), + } + } +} + +fn standing_tag(standing: Standing) -> LegacyStandingTag { + match standing { + Standing::Syncs => LegacyStandingTag::Syncs, + Standing::LocalOnly => LegacyStandingTag::LocalOnly, + Standing::Unknown => LegacyStandingTag::Unknown, + } +} + +fn standing(tag: LegacyStandingTag) -> Standing { + match tag { + LegacyStandingTag::Syncs => Standing::Syncs, + LegacyStandingTag::LocalOnly => Standing::LocalOnly, + LegacyStandingTag::Unknown => Standing::Unknown, + } +} + +impl LegacyMetadataArg { + fn into_metadata(self) -> Result { + Ok(sync::LegacyMetadata { + token: self.token, + dirty: self.dirty.into_iter().map(Into::into).collect(), + tombstones: self + .tombstones + .into_iter() + .map(|tombstone| { + Ok(sync::LegacyTombstone { + record: tombstone.record.into(), + deleted_at_ms: tombstone.deleted_at_ms, + owner: tombstone.owner.as_deref().map(uuid).transpose()?, + }) + }) + .collect::>()?, + deferred_deletions: self.deferred_deletions, + changes_held_for_unreadable: self.changes_held_for_unreadable, + removals_pending_for_unreadable: self.removals_pending_for_unreadable, + deletions_held_for_unreadable: self.deletions_held_for_unreadable, + owners_kept_off_sync: self + .owners_kept_off_sync + .iter() + .map(|owner| uuid(owner)) + .collect::>()?, + standing: self + .standing + .into_iter() + .map(|entry| { + Ok(sync::LegacyStanding { + connection: uuid(&entry.connection)?, + standing: standing(entry.standing), + }) + }) + .collect::>()?, + readable_record_types: self.readable_record_types, + account: self.account, + zone_state: self.zone_state, + cache: self.cache.into_iter().map(Into::into).collect(), + }) + } + + fn of(metadata: sync::LegacyMetadata) -> Self { + Self { + token: metadata.token, + dirty: metadata.dirty.into_iter().map(Into::into).collect(), + tombstones: metadata.tombstones.into_iter().map(Into::into).collect(), + deferred_deletions: metadata.deferred_deletions, + changes_held_for_unreadable: metadata.changes_held_for_unreadable, + removals_pending_for_unreadable: metadata.removals_pending_for_unreadable, + deletions_held_for_unreadable: metadata.deletions_held_for_unreadable, + owners_kept_off_sync: metadata.owners_kept_off_sync.into_iter().map(wire_uuid).collect(), + standing: metadata + .standing + .into_iter() + .map(|entry| LegacyStandingArg { + connection: wire_uuid(entry.connection), + standing: standing_tag(entry.standing), + }) + .collect(), + readable_record_types: metadata.readable_record_types, + account: metadata.account, + zone_state: metadata.zone_state, + cache: metadata.cache.into_iter().map(Into::into).collect(), + } + } +} + +fn host_error(failure: impl std::fmt::Display) -> AdapterError { + AdapterError::Host { + detail: failure.to_string(), + } +} + +pub(crate) struct LegacyMirrorBridge { + pub(crate) host: Arc, + pub(crate) tasks: Tasks, +} + +#[async_trait] +impl sync::LegacyMirror for LegacyMirrorBridge { + async fn read(&self) -> Result { + let host = Arc::clone(&self.host); + let read = self + .tasks + .spawn_blocking_task(move || host.read()) + .await + .map_err(host_error)?; + read.map_err(host_error)?.into_metadata() + } + + async fn write(&self, metadata: sync::LegacyMetadata) -> Result<(), AdapterError> { + let (host, metadata) = (Arc::clone(&self.host), LegacyMetadataArg::of(metadata)); + let written = self + .tasks + .spawn_blocking_task(move || host.write(metadata)) + .await + .map_err(host_error)?; + written.map_err(host_error) + } + + async fn mark( + &self, + dirty: Vec, + tombstones: Vec, + ) -> Result<(), AdapterError> { + let host = Arc::clone(&self.host); + let dirty = dirty.into_iter().map(Into::into).collect(); + let tombstones = tombstones.into_iter().map(Into::into).collect(); + let marked = self + .tasks + .spawn_blocking_task(move || host.mark(dirty, tombstones)) + .await + .map_err(host_error)?; + marked.map_err(host_error) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn metadata_crosses_the_boundary_and_back_unchanged() { + let metadata = sync::LegacyMetadata { + token: Some(vec![1, 2]), + dirty: vec![sync::LegacyRecordRef { + record_type: "Connection".to_owned(), + id: "A".to_owned(), + }], + tombstones: vec![sync::LegacyTombstone { + record: sync::LegacyRecordRef { + record_type: "Group".to_owned(), + id: "B".to_owned(), + }, + deleted_at_ms: 1_767_225_600_000, + owner: Some(Uuid::from_u128(7)), + }], + changes_held_for_unreadable: vec!["Connection_C".to_owned()], + deletions_held_for_unreadable: vec!["Group_D".to_owned()], + standing: vec![sync::LegacyStanding { + connection: Uuid::from_u128(9), + standing: Standing::LocalOnly, + }], + ..sync::LegacyMetadata::default() + }; + + let back = LegacyMetadataArg::of(metadata.clone()).into_metadata().unwrap(); + + assert_eq!(back, metadata); + } +} diff --git a/core/crates/ffi/src/sync/mod.rs b/core/crates/ffi/src/sync/mod.rs new file mode 100644 index 0000000000..506be2362d --- /dev/null +++ b/core/crates/ffi/src/sync/mod.rs @@ -0,0 +1,31 @@ +// The sync surface the apps call (core ADRs 0054 and 0056): `SyncService`, its listener, and the callbacks the +// apps implement. Its bodies answer `sync.unimplemented` until the engine and key lanes fill them. + +mod cloudkit; +mod host; +mod keys; +mod legacy; +mod service; + +pub use cloudkit::{ + CloudKitAccount, CloudKitChanges, CloudKitDeletion, CloudKitFailure, CloudKitFetched, CloudKitField, + CloudKitOutcome, CloudKitRecord, CloudKitTransport, CloudKitValue, +}; +pub use host::{ + DeviceItemClassTag, DeviceItemTag, HostDeviceStore, HostSettings, SettingsCategoryArg, device_item_class, +}; +pub use keys::{ + AccountDeviceInfo, ApprovalRequestInfo, ApprovalSessionInfo, FingerprintInfo, GenesisOutcomeTag, HeldRestartInfo, + KeyChangeInfo, KeyNoticeInfo, KeyNoticeKindTag, KeyStateInfo, KeyVersionStateTag, LockCauseTag, MemberKeyStatusTag, + MemberKeysInfo, PendingResetInfo, RecoveryKeyDraftInfo, RemovalReviewInfo, ResetKindTag, ResetStateTag, + ReviewedDeviceInfo, ReviewedMemberInfo, RotationDraftInfo, SessionEndTag, SessionPhaseTag, SessionRoleTag, + SignOutOutcomeTag, StopCauseTag, StoppedDeviceInfo, TeamKeysInfo, TeamRoleTag, +}; +pub use legacy::{ + HostLegacyMirror, LegacyMetadataArg, LegacyRecordArg, LegacyStandingArg, LegacyStandingTag, LegacyTombstoneArg, +}; +pub use service::{ + ConflictChoiceTag, HeldReasonTag, HeldRecordInfo, MoveBackPlanInfo, MovePlanInfo, NewIdentityChoiceTag, + PassReasonTag, PendingApprovalInfo, SyncCategoriesArg, SyncConfig, SyncFailureInfo, SyncListener, SyncPhaseTag, + SyncPlatformTag, SyncRecordRef, SyncService, SyncStatusInfo, TeamConflictInfo, +}; diff --git a/core/crates/ffi/src/sync/service.rs b/core/crates/ffi/src/sync/service.rs new file mode 100644 index 0000000000..eb5a730c96 --- /dev/null +++ b/core/crates/ffi/src/sync/service.rs @@ -0,0 +1,384 @@ +use std::sync::Arc; + +use tablepro_records::Kind; +use tablepro_session::runtime::Tasks; +use tablepro_sync::SyncError; +use tablepro_sync::api::{CloudKitFailure, TransportError}; + +use super::cloudkit::{CloudKitBridge, CloudKitTransport}; +use super::host::{HostDeviceStore, HostDeviceStoreBridge, HostSettings, HostSettingsBridge}; +use super::keys::LockCauseTag; +use super::legacy::{HostLegacyMirror, LegacyMirrorBridge}; +use crate::account::{AccountService, SyncProviderTag}; +use crate::core_handle::Core; +use crate::error::CoreError; + +// The typed fields a sync refusal carries, which the app acts on: RFC 9470's challenge to step up and retry, a +// `Retry-After`, the rejected change's own code (0051, Push), and why the device locked. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum SyncFailureInfo { + StepUp { acr_values: Vec, max_age_secs: u64 }, + RetryAfter { ms: u64 }, + Rejected { code: String }, + Locked { cause: LockCauseTag }, +} + +fn failure_info(error: &SyncError) -> Option { + match error { + SyncError::Transport(TransportError::StepUpRequired(challenge)) => Some(SyncFailureInfo::StepUp { + acr_values: challenge.acr_values.clone(), + max_age_secs: challenge.max_age_secs, + }), + SyncError::Transport( + TransportError::RateLimited { retry_after_ms } + | TransportError::RestoreCheckUnavailable { retry_after_ms } + | TransportError::Server { retry_after_ms, .. }, + ) + | SyncError::CloudKit(CloudKitFailure::Throttled { retry_after_ms }) => { + retry_after_ms.map(|ms| SyncFailureInfo::RetryAfter { ms }) + } + SyncError::Rejected { code } => Some(SyncFailureInfo::Rejected { + code: code.as_str().to_owned(), + }), + SyncError::Locked { cause } => Some(SyncFailureInfo::Locked { cause: (*cause).into() }), + _ => None, + } +} + +impl From for CoreError { + fn from(error: SyncError) -> Self { + if error == SyncError::Cancelled { + return Self::Cancelled; + } + let sync = failure_info(&error); + match Self::failed(error.code(), error.to_string()) { + Self::Failed { mut info } => { + info.sync = sync; + Self::Failed { info } + } + cancelled @ Self::Cancelled => cancelled, + } + } +} + +// A contract whose lane has not filled it yet answers `sync.unimplemented`. +pub(crate) fn unfilled(what: &'static str) -> Result { + Err(SyncError::unimplemented(what).into()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SyncPlatformTag { + Macos, + Ios, + Linux, + Windows, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SyncConfig { + pub platform: SyncPlatformTag, + pub categories: SyncCategoriesArg, +} + +// The kinds turned off on this device, by their wire names, and the password switch. +#[derive(Debug, Clone, PartialEq, Eq, Default, uniffi::Record)] +pub struct SyncCategoriesArg { + pub off_kinds: Vec, + pub passwords: bool, +} + +// Told that something changed, on a runtime thread. It only schedules a read on the app's own thread: no work, and +// nothing that blocks (core ADR 0002). +#[uniffi::export(callback_interface)] +pub trait SyncListener: Send + Sync { + // `status`, the approvals, the conflicts or the held records changed. + fn status_changed(&self); + + // The key state, a session, a reset, a team's keys or the key notices changed. + fn keys_changed(&self); +} + +// One per app, over the account it was opened with. Dropping it stops the scheduler. +#[derive(uniffi::Object)] +#[expect(dead_code, reason = "the engine's lanes run the service over these")] +pub struct SyncService { + pub(crate) tasks: Tasks, + pub(crate) account: Arc, + pub(crate) config: SyncConfig, + pub(crate) cloudkit: Option>, + pub(crate) settings: Option>, + pub(crate) device_store: Option>, + pub(crate) legacy_mirror: Option>, + pub(crate) listener: Arc, +} + +impl std::fmt::Debug for SyncService { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SyncService") + .field("config", &self.config) + .finish_non_exhaustive() + } +} + +#[uniffi::export] +impl Core { + // The Apple apps pass their CloudKit transport and device store, and the Mac its legacy mirror while the previous + // stable runs the Swift engine. Windows passes none: the core reaches Credential Manager itself. + #[expect( + clippy::too_many_arguments, + reason = "a UniFFI record cannot carry callback interfaces, so each host service is its own argument" + )] + pub fn open_sync( + &self, + config: SyncConfig, + account: Arc, + cloudkit: Option>, + settings: Option>, + device_store: Option>, + legacy_mirror: Option>, + listener: Box, + ) -> Result, CoreError> { + let tasks = self.tasks.clone(); + let kind = match config.platform { + SyncPlatformTag::Macos => Kind::MacosSettings, + SyncPlatformTag::Ios => Kind::IosSettings, + SyncPlatformTag::Linux => Kind::LinuxSettings, + SyncPlatformTag::Windows => Kind::WindowsSettings, + }; + let cloudkit = + cloudkit.map(|host| Arc::new(CloudKitBridge(host)) as Arc); + let settings = settings.map(|host| { + Arc::new(HostSettingsBridge { + host: Arc::from(host), + kind, + tasks: tasks.clone(), + }) as Arc + }); + let device_store = device_store.map(|host| { + Arc::new(HostDeviceStoreBridge { + host: Arc::from(host), + tasks: tasks.clone(), + }) as Arc + }); + let legacy_mirror = legacy_mirror.map(|host| { + Arc::new(LegacyMirrorBridge { + host: Arc::from(host), + tasks: tasks.clone(), + }) as Arc + }); + Ok(Arc::new(SyncService { + tasks, + account, + config, + cloudkit, + settings, + device_store, + legacy_mirror, + listener: Arc::from(listener), + })) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SyncPhaseTag { + Off, + Unavailable, + Idle, + Syncing, + Waiting { retry_in_ms: u64 }, + PullOnly, + ZoneRemoved, + NewIdentity, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SyncStatusInfo { + pub provider: Option, + pub phase: SyncPhaseTag, + pub last_pass_ms: Option, + // The last pass's error code. + pub problem: Option, + pub waiting_approvals: u32, + pub conflicts: u32, + pub held: u32, + pub queued_changes: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum PassReasonTag { + // A store the app keeps wrote, after the write landed. + Journal, + // `CKAccountChanged`, after the operations in flight were cancelled. + AccountChanged, + Launch, + Foreground, + NetworkBack, + CloudKitPush, + Person, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum NewIdentityChoiceTag { + MoveMyData, + StartEmpty, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ConflictChoiceTag { + KeepMine, + KeepTheirs, +} + +// A synced record: its scope as the wire names it (`personal`, `history` or `team_...`), its kind and its id. +#[derive(Debug, Clone, PartialEq, Eq, Hash, uniffi::Record)] +pub struct SyncRecordRef { + pub scope: String, + pub kind: String, + pub record_id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct MovePlanInfo { + pub records: u64, + pub staying_behind: u64, + pub secrets_to_seal: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct MoveBackPlanInfo { + pub icloud_deletions: u64, +} + +// Values are JSON text. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct PendingApprovalInfo { + pub record: SyncRecordRef, + pub field: String, + pub pulled: String, + pub current: Option, +} + +// None is a deletion. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TeamConflictInfo { + pub record: SyncRecordRef, + pub fields: Vec, + pub mine: Option, + pub theirs: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum HeldReasonTag { + Unreadable, + UnknownKind, + AwaitingApproval, + // Over 1 MiB, or a value the server's rules refuse, with the server's code. + Refused { code: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct HeldRecordInfo { + pub record: SyncRecordRef, + pub reason: HeldReasonTag, +} + +#[uniffi::export] +impl SyncService { + pub fn status(&self) -> SyncStatusInfo { + SyncStatusInfo { + provider: None, + phase: SyncPhaseTag::Unavailable, + last_pass_ms: None, + problem: Some(SyncError::unimplemented("sync.status").code().to_owned()), + waiting_approvals: 0, + conflicts: 0, + held: 0, + queued_changes: 0, + } + } + + pub async fn sync_now(&self, why: PassReasonTag) -> Result<(), CoreError> { + let _ = why; + unfilled("sync.sync_now") + } + + pub async fn set_categories(&self, categories: SyncCategoriesArg) -> Result<(), CoreError> { + let _ = categories; + unfilled("sync.set_categories") + } + + // A store the app still keeps wrote these records of `kind`, after its write landed (core ADR 0060). + pub async fn record_host_changes( + &self, + kind: String, + written: Vec, + deleted: Vec, + ) -> Result<(), CoreError> { + let _ = (kind, written, deleted); + unfilled("sync.host_changed") + } + + // Among what the managed policy allows (core ADR 0055). + pub async fn choose_provider(&self, provider: SyncProviderTag) -> Result<(), CoreError> { + let _ = provider; + unfilled("sync.choose_provider") + } + + pub async fn plan_move_to_service(&self) -> Result { + unfilled("sync.plan_move_to_service") + } + + pub async fn move_to_service(&self) -> Result<(), CoreError> { + unfilled("sync.move_to_service") + } + + pub async fn plan_move_to_icloud(&self) -> Result { + unfilled("sync.plan_move_to_icloud") + } + + // Refused unless the count is the plan's, which the person confirmed. + pub async fn move_to_icloud(&self, confirmed_deletions: u64) -> Result<(), CoreError> { + let _ = confirmed_deletions; + unfilled("sync.move_to_icloud") + } + + pub async fn choose_for_new_identity(&self, choice: NewIdentityChoiceTag) -> Result<(), CoreError> { + let _ = choice; + unfilled("sync.choose_for_new_identity") + } + + pub async fn upload_again(&self) -> Result<(), CoreError> { + unfilled("sync.upload_again") + } + + pub async fn delete_icloud_zone(&self) -> Result<(), CoreError> { + unfilled("sync.delete_icloud_zone") + } + + pub async fn approvals(&self) -> Result, CoreError> { + unfilled("sync.approvals") + } + + pub async fn decide_approval(&self, record: SyncRecordRef, field: String, approve: bool) -> Result<(), CoreError> { + let _ = (record, field, approve); + unfilled("sync.decide_approval") + } + + pub async fn conflicts(&self) -> Result, CoreError> { + unfilled("sync.conflicts") + } + + pub async fn resolve_conflict(&self, record: SyncRecordRef, keep: ConflictChoiceTag) -> Result<(), CoreError> { + let _ = (record, keep); + unfilled("sync.resolve_conflict") + } + + pub async fn held_records(&self) -> Result, CoreError> { + unfilled("sync.held_records") + } + + // True while older entries remain on the server. + pub async fn load_older_history(&self) -> Result { + unfilled("sync.load_older_history") + } +} diff --git a/core/crates/sync/Cargo.toml b/core/crates/sync/Cargo.toml new file mode 100644 index 0000000000..441c51563c --- /dev/null +++ b/core/crates/sync/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "tablepro-sync" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +tablepro-keys.workspace = true +tablepro-records.workspace = true +async-trait.workspace = true +secrecy.workspace = true +serde_json.workspace = true +thiserror.workspace = true +uuid.workspace = true +zeroize.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt"] } + +[lints] +workspace = true diff --git a/core/crates/sync/src/api/adapter.rs b/core/crates/sync/src/api/adapter.rs new file mode 100644 index 0000000000..a4b9993c45 --- /dev/null +++ b/core/crates/sync/src/api/adapter.rs @@ -0,0 +1,83 @@ +use async_trait::async_trait; +use serde_json::Value; +use tablepro_records::Kind; +use uuid::Uuid; + +use super::error::AdapterError; +use super::ids::ScopeName; +use super::state::Standing; + +// One kind's bridge to its core store (0054, Adapters). Dirty state is the diff of `records` against the bases, so a +// write the journal missed is found on the next pass. +#[async_trait] +pub trait RecordAdapter: Send + Sync { + fn kind(&self) -> Kind; + + // The store whose identity puts this kind into refill when it changes (0054, Store identity). + fn store(&self) -> &str; + + async fn identity(&self) -> Result; + + // Every record the store holds of this kind in `scope` as wire fields, the ids it holds but cannot read, and for a + // create-once kind the tombstones it keeps until they are pushed. A team library kind has one set per team. + async fn records(&self, scope: ScopeName) -> Result; + + // Writes what a pull of `scope` settled, in one store write, and answers the identity after it. + async fn apply(&self, scope: ScopeName, changes: Vec) -> Result; + + // A create-once kind's tombstones the provider took, which the store drops. + async fn tombstones_pushed(&self, scope: ScopeName, record_ids: Vec) -> Result<(), AdapterError>; +} + +// A store's generation id and write sequence. A new generation is a restored, replaced or copied file; a lower +// sequence went back in time. Either puts the store's kinds into refill. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct StoreStamp { + pub generation: Uuid, + pub sequence: u64, +} + +impl StoreStamp { + pub fn needs_refill(self, seen: Self) -> bool { + self.generation != seen.generation || self.sequence < seen.sequence + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct LocalRecords { + pub records: Vec, + pub unreadable: Vec, + pub tombstones: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LocalRecord { + pub record_id: String, + pub fields: Value, + // Local only and sample connections never leave the device. + pub standing: Standing, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LocalChange { + Put { record_id: String, fields: Value }, + Delete { record_id: String }, +} + +// Each app's settings, which it keeps its own way (0054, Adapters): the categories of its platform's registry in +// `tablepro_records::settings`, each as one JSON document. The `_settings` adapter sits over it. +#[async_trait] +pub trait HostSettings: Send + Sync { + fn kind(&self) -> Kind; + + async fn categories(&self) -> Result, AdapterError>; + + // None removes the category's synced document, as a deleted theme. + async fn apply(&self, category: String, document: Option) -> Result<(), AdapterError>; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SettingsDocument { + pub category: String, + pub document: Value, +} diff --git a/core/crates/sync/src/api/cloudkit.rs b/core/crates/sync/src/api/cloudkit.rs new file mode 100644 index 0000000000..95fc4edb59 --- /dev/null +++ b/core/crates/sync/src/api/cloudkit.rs @@ -0,0 +1,199 @@ +use std::fmt; + +use async_trait::async_trait; + +// 0054, The CloudKit transport. Swift implements it over CloudKit's operations; the FFI's foreign trait of the same +// name bridges to this one. The core never calls it under a lock, and dropping a call's future cancels the Swift task. +// Swift decides nothing: it maps each `CKError` to an outcome or a failure and returns. Every call names the iCloud +// user record name the pass's state file is bound to. +#[async_trait] +pub trait CloudKitTransport: Send + Sync { + async fn account_status(&self) -> Result; + + async fn ensure_zone(&self, account: String) -> Result<(), CloudKitFailure>; + + async fn delete_zone(&self, account: String) -> Result<(), CloudKitFailure>; + + async fn fetch_changes(&self, account: String, token: Option>) -> Result; + + async fn fetch_records(&self, account: String, names: Vec) + -> Result, CloudKitFailure>; + + async fn modify( + &self, + account: String, + saves: Vec, + deletes: Vec, + ) -> Result, CloudKitFailure>; +} + +// The signed-in iCloud account: its user record name. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct CloudKitAccount { + pub user_record_name: String, +} + +#[derive(Clone, PartialEq)] +pub struct CloudKitRecord { + pub record_type: String, + pub name: String, + // What `CKRecord.encodeSystemFields(with:)` writes; Swift rebuilds the record from it and saves with + // `.ifServerRecordUnchanged`. A create sends none. + pub system_fields: Option>, + // `CKRecord.creationDate` in milliseconds, on a record CloudKit returned; None on a save. Kept with the base, it + // tells a record made again after a zone was removed from the one the base came from. + pub created_ms: Option, + pub fields: Vec, +} + +impl fmt::Debug for CloudKitRecord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CloudKitRecord") + .field("record_type", &self.record_type) + .field("name", &self.name) + .field("system_fields", &self.system_fields.as_ref().map(Vec::len)) + .field( + "fields", + &self.fields.iter().map(|field| &field.name).collect::>(), + ) + .finish() + } +} + +// A save names each field it sets; `None` clears one. +#[derive(Debug, Clone, PartialEq)] +pub struct CloudKitField { + pub name: String, + pub value: Option, +} + +// CloudKit's own types; `tablepro_records::cloudkit` maps them to wire fields and back. +#[derive(Debug, Clone, PartialEq)] +pub enum CloudKitValue { + Text(String), + Int64(i64), + Double(f64), + // Milliseconds since the Unix epoch, the precision a CloudKit date keeps. + Timestamp(i64), + Bytes(Vec), + TextList(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CloudKitChanges { + pub changed: Vec, + pub deleted: Vec, + // Records the zone reported changed whose fetch failed; the engine fetches them by name or holds them. + pub unfetched: Vec, + pub token: Vec, + pub more: bool, +} + +// `recordWithIDWasDeletedBlock`'s record name and type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct CloudKitDeletion { + pub name: String, + pub record_type: String, +} + +// One name of `fetch_records`, as `perRecordResultBlock` answers it. +#[derive(Debug, Clone, PartialEq)] +pub enum CloudKitFetched { + Found { + record: CloudKitRecord, + }, + // `unknownItem`: the zone holds no record by that name. + Missing { + name: String, + }, + Failed { + name: String, + code: i64, + retry_after_ms: Option, + }, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum CloudKitOutcome { + Saved { + name: String, + system_fields: Vec, + }, + Deleted { + name: String, + }, + // `serverRecordChanged`, with the server's copy when the error carried one. + ServerChanged { + name: String, + server: Option, + }, + UnknownItem { + name: String, + }, + Failed { + name: String, + code: i64, + retry_after_ms: Option, + }, +} + +impl CloudKitOutcome { + pub fn name(&self) -> &str { + match self { + Self::Saved { name, .. } + | Self::Deleted { name } + | Self::ServerChanged { name, .. } + | Self::UnknownItem { name } + | Self::Failed { name, .. } => name, + } + } +} + +// A whole call's failure. `AccountChanged` discards the call's results, ends the pass and drops its state file's +// session (0054, Every call is bound to one account). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CloudKitFailure { + #[error("no iCloud account")] + NoAccount, + #[error("iCloud is restricted")] + Restricted, + #[error("the iCloud account is temporarily unavailable")] + AccountTemporarilyUnavailable, + #[error("the iCloud account changed during the call")] + AccountChanged, + #[error("the change token expired")] + TokenExpired, + #[error("the zone does not exist")] + ZoneNotFound, + #[error("the person deleted the zone")] + ZoneDeletedByUser, + #[error("the batch is over CloudKit's limit")] + LimitExceeded, + #[error("the iCloud quota is exceeded")] + QuotaExceeded, + #[error("the network failed")] + Network, + #[error("CloudKit is throttling")] + Throttled { retry_after_ms: Option }, + #[error("CloudKit failed with code {code}")] + Other { code: i64 }, +} + +impl CloudKitFailure { + pub const fn code(&self) -> &'static str { + match self { + Self::NoAccount => "sync.icloud.no_account", + Self::Restricted => "sync.icloud.restricted", + Self::AccountTemporarilyUnavailable => "sync.icloud.account_temporarily_unavailable", + Self::AccountChanged => "sync.icloud.account_changed", + Self::TokenExpired => "sync.icloud.token_expired", + Self::ZoneNotFound => "sync.icloud.zone_not_found", + Self::ZoneDeletedByUser => "sync.icloud.zone_deleted_by_user", + Self::LimitExceeded => "sync.icloud.limit_exceeded", + Self::QuotaExceeded => "sync.icloud.quota_exceeded", + Self::Network => "sync.icloud.network", + Self::Throttled { .. } => "sync.icloud.throttled", + Self::Other { .. } => "sync.icloud.other", + } + } +} diff --git a/core/crates/sync/src/api/control.rs b/core/crates/sync/src/api/control.rs new file mode 100644 index 0000000000..9b0ce0f371 --- /dev/null +++ b/core/crates/sync/src/api/control.rs @@ -0,0 +1,234 @@ +// What the engine offers an app beyond the key flows (0054, Scheduling; Providers; Moving between providers; Rules for +// both providers), which the FFI's `SyncService` wraps. Every method answers `sync.unimplemented` until the engine's +// lanes override it. + +use async_trait::async_trait; +use serde_json::Value; + +use super::error::SyncError; +use super::ids::{KindName, RecordKey}; +use super::state::{HeldReason, Provider}; + +fn unimplemented(what: &'static str) -> Result { + Err(SyncError::unimplemented(what)) +} + +#[async_trait] +pub trait SyncControl: Send + Sync { + fn status(&self) -> SyncStatus; + + // A journal signal, launch, foreground, the network back, a CloudKit push, the poll interval or iCloud's timer. + async fn sync_now(&self, why: PassReason) -> Result<(), SyncError> { + let _ = why; + unimplemented("sync.sync_now") + } + + // The categories this device syncs and whether passwords do: an off category sends nothing, and a deletion pulled + // for it waits (0054, Rules for both providers). + async fn set_categories(&self, categories: SyncCategories) -> Result<(), SyncError> { + let _ = categories; + unimplemented("sync.set_categories") + } + + // A store the app still keeps wrote these records, after its write landed (0060). The diff decides what goes up. + async fn host_changed(&self, kind: KindName, written: Vec, deleted: Vec) -> Result<(), SyncError> { + let _ = (kind, written, deleted); + unimplemented("sync.host_changed") + } + + // Off, iCloud or TablePro Sync for personal data, among what the managed policy allows (0055). + async fn choose_provider(&self, choice: ProviderChoice) -> Result<(), SyncError> { + let _ = choice; + unimplemented("sync.choose_provider") + } + + // What a move to TablePro Sync would leave behind, for the move sheet. + async fn plan_move_to_service(&self) -> Result { + unimplemented("sync.plan_move_to_service") + } + + async fn move_to_service(&self) -> Result<(), SyncError> { + unimplemented("sync.move_to_service") + } + + // How many iCloud records the move back deletes, which the person confirms first. + async fn plan_move_to_icloud(&self) -> Result { + unimplemented("sync.plan_move_to_icloud") + } + + // Refused unless `confirmed_deletions` equals the plan's count. + async fn move_to_icloud(&self, confirmed_deletions: u64) -> Result<(), SyncError> { + let _ = confirmed_deletions; + unimplemented("sync.move_to_icloud") + } + + // Another account or server: Move my data or Start empty. Nothing goes up without this choice. + async fn choose_for_new_identity(&self, choice: NewIdentityChoice) -> Result<(), SyncError> { + let _ = choice; + unimplemented("sync.choose_for_new_identity") + } + + // After a removed zone, nothing is uploaded until the person asks. + async fn upload_again(&self) -> Result<(), SyncError> { + unimplemented("sync.upload_again") + } + + // The zone stays after a move until the person deletes it. + async fn delete_icloud_zone(&self) -> Result<(), SyncError> { + unimplemented("sync.delete_icloud_zone") + } + + async fn approvals(&self) -> Result, SyncError> { + unimplemented("sync.approvals") + } + + // A rejection keeps the device's own value as a local override. + async fn decide_approval(&self, key: RecordKey, field: String, approve: bool) -> Result<(), SyncError> { + let _ = (key, field, approve); + unimplemented("sync.decide_approval") + } + + async fn conflicts(&self) -> Result, SyncError> { + unimplemented("sync.conflicts") + } + + async fn resolve_conflict(&self, key: RecordKey, keep: ConflictChoice) -> Result<(), SyncError> { + let _ = (key, keep); + unimplemented("sync.resolve_conflict") + } + + // Records that stay on the device with a notice: over the record limit, refused, unreadable or held. + async fn held_records(&self) -> Result, SyncError> { + unimplemented("sync.held_records") + } + + // The history view asks for entries older than the window. + async fn load_older_history(&self) -> Result { + unimplemented("sync.load_older_history") + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PassReason { + Journal, + // A key flow wrote something a pass should carry (`KeyHooks::pass_soon`). + KeyFlow, + // `CKAccountChanged`: the engine reads the account status and opens that account's state file. + AccountChanged, + Launch, + Foreground, + NetworkBack, + CloudKitPush, + Poll, + Person, +} + +// The kinds turned off on this device, and the password switch. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SyncCategories { + pub off: Vec, + pub passwords: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ProviderChoice { + Off, + ICloud, + Service, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum NewIdentityChoice { + MoveMyData, + StartEmpty, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SyncStatus { + pub provider: Option, + pub phase: SyncPhase, + pub last_pass_ms: Option, + // The last pass's error code, as `SyncError::code` gives it. + pub problem: Option<&'static str>, + pub waiting_approvals: u32, + pub conflicts: u32, + pub held: u32, + pub queued_changes: u32, +} + +impl SyncStatus { + pub const UNAVAILABLE: Self = Self { + provider: None, + phase: SyncPhase::Unavailable, + last_pass_ms: None, + problem: Some("sync.unimplemented"), + waiting_approvals: 0, + conflicts: 0, + held: 0, + queued_changes: 0, + }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SyncPhase { + Off, + Unavailable, + Idle, + Syncing, + // Backing off with jitter, honoring `Retry-After`. + Waiting { retry_in_ms: u64 }, + // Pull-only past grace or after a lapse. + PullOnly, + // A removed zone waits for Upload Again. + ZoneRemoved, + // Another account or server waits for Move my data or Start empty. + NewIdentity, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MovePlan { + pub records: u64, + // Local only and sample connections, and categories this device has turned off. + pub staying_behind: u64, + pub secrets_to_seal: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MoveBackPlan { + pub icloud_deletions: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PendingApproval { + pub key: RecordKey, + pub field: String, + pub pulled: Value, + pub current: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TeamConflict { + pub key: RecordKey, + pub fields: Vec, + pub mine: Option, + pub theirs: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ConflictChoice { + KeepMine, + KeepTheirs, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeldRecord { + pub key: RecordKey, + pub reason: HeldRecordReason, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HeldRecordReason { + Held(HeldReason), + // Over 1 MiB, or a value the server's rules refuse, kept on the device. + Refused { code: String }, +} diff --git a/core/crates/sync/src/api/device_store.rs b/core/crates/sync/src/api/device_store.rs new file mode 100644 index 0000000000..b2cbb86789 --- /dev/null +++ b/core/crates/sync/src/api/device_store.rs @@ -0,0 +1,100 @@ +use async_trait::async_trait; +use tablepro_keys::encoding::{AccountId, Origin, ResetId, Version}; +use zeroize::Zeroizing; + +use super::ids::{DeviceRowId, StateName}; + +// The device's own secret store (0056, Device stores; 0054, Integrity and freshness): Keychain items that do not sync, +// Credential Manager with local machine persistence, a Secret Service item. Never synced or exported. Each call may +// block, so the core makes it off the runtime's workers. A device without one holds no keys and syncs team plaintext +// records only. +#[async_trait] +pub trait HostDeviceStore: Send + Sync { + async fn load(&self, item: DeviceItem) -> Result>>, DeviceStoreError>; + + async fn store(&self, item: DeviceItem, value: Zeroizing>) -> Result<(), DeviceStoreError>; + + // Deleting an item that is not there succeeds. + async fn delete(&self, item: DeviceItem) -> Result<(), DeviceStoreError>; +} + +// One item. The value's format is the flow's that writes it; the store keeps bytes. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum DeviceItem { + // The device keys of one (origin, account, device row): DSK, DEK and the key device id, and while an approval is + // in flight the new ones beside the old (0056, Keys). They outlive sessions and resume on the same row. + DeviceKeys { + origin: Origin, + account: AccountId, + device_row: DeviceRowId, + }, + // ASK and AEK at one `av`, kept while a scope key is still wrapped to that AEK. + AccountKeys { + origin: Origin, + account: AccountId, + av: Version, + }, + // A reset this device proposed: its new account and device keys, until it activates or ends (0054, `key_pending`). + ResetKeys { + origin: Origin, + account: AccountId, + reset: ResetId, + }, + // 32 random bytes per state file, in the anchor's class. + StateMacKey { + state: StateName, + }, + // The anchor's root: the file id, the current entry and at most one pending entry. Named by the state file's + // name, not its file id, so an anchor with no file is still found (0054, On open). + AnchorRoot { + state: StateName, + }, + // One numbered part of a checkpoint the root names by its digest; Windows splits one over items of 2,560 bytes. + AnchorCheckpoint { + state: StateName, + checkpoint: [u8; 32], + part: u32, + }, +} + +impl DeviceItem { + pub const fn class(&self) -> DeviceItemClass { + match self { + Self::DeviceKeys { .. } | Self::AccountKeys { .. } | Self::ResetKeys { .. } => DeviceItemClass::Keys, + Self::StateMacKey { .. } | Self::AnchorRoot { .. } | Self::AnchorCheckpoint { .. } => { + DeviceItemClass::Anchor + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DeviceItemClass { + // This device only, never in a backup that restores elsewhere: Apple's `ThisDeviceOnly` classes. + Keys, + // Not restored by a backup even to the same device: Apple's `kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly`, + // which reads only while the device is unlocked and goes when the passcode is turned off. + Anchor, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DeviceStoreError { + // No store, as a Linux session without Secret Service. + #[error("the device store is unavailable: {detail}")] + Unavailable { detail: String }, + // The device is locked, so an anchor item cannot be read; a pass that starts locked waits. + #[error("the device store is locked")] + Locked, + #[error("the device store failed: {detail}")] + Failed { detail: String }, +} + +impl DeviceStoreError { + pub const fn code(&self) -> &'static str { + match self { + Self::Unavailable { .. } => "sync.device_store.unavailable", + Self::Locked => "sync.device_store.locked", + Self::Failed { .. } => "sync.device_store.failed", + } + } +} diff --git a/core/crates/sync/src/api/error.rs b/core/crates/sync/src/api/error.rs new file mode 100644 index 0000000000..747bae6f9f --- /dev/null +++ b/core/crates/sync/src/api/error.rs @@ -0,0 +1,125 @@ +use tablepro_keys::KeysError; + +use super::cloudkit::CloudKitFailure; +use super::device_store::DeviceStoreError; +use super::key_flows::LockCause; +use super::transport::{RejectedCode, TransportError}; + +// Every sync error with a stable `code()` (core/AGENTS.md, Principles). The keys' codes pass through as 0056 gives +// them; the server's refusals carry 0051's code under `sync.`. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum SyncError { + // A contract whose lane has not filled it yet. Nothing ships while one answers this. + #[error("{what} is not built yet")] + Unimplemented { what: &'static str }, + #[error("malformed {what}")] + Malformed { what: &'static str }, + #[error(transparent)] + Keys(#[from] KeysError), + #[error(transparent)] + Transport(#[from] TransportError), + #[error(transparent)] + CloudKit(#[from] CloudKitFailure), + #[error(transparent)] + DeviceStore(#[from] DeviceStoreError), + #[error(transparent)] + State(#[from] StateError), + #[error(transparent)] + Adapter(#[from] AdapterError), + // A flow's change set or write was refused, with the change's code (0051, Push). + #[error("the server refused the change: {}", code.as_str())] + Rejected { code: RejectedCode }, + // The device keeps its keys and syncs nothing personal until it is approved again (0056, A locked device). + #[error("this device is locked: {cause:?}")] + Locked { cause: LockCause }, + // The two groups of the recovery key typed back do not match what was shown (0056, The recovery key). + #[error("the recovery key was typed back wrong")] + TypedBackWrong, + // A draft, review or session this service does not hold, or no longer holds. + #[error("no such {what}")] + Unknown { what: &'static str }, + // The call needs an approved device, a device store or keys this device does not hold. + #[error("this device cannot {what} now")] + NotAllowed { what: &'static str }, + #[error("the call was cancelled")] + Cancelled, +} + +impl SyncError { + pub const fn unimplemented(what: &'static str) -> Self { + Self::Unimplemented { what } + } + + pub fn code(&self) -> &'static str { + match self { + Self::Unimplemented { .. } => "sync.unimplemented", + Self::Malformed { .. } => "sync.malformed", + Self::Keys(error) => error.code(), + Self::Transport(error) => error.code(), + Self::CloudKit(failure) => failure.code(), + Self::DeviceStore(error) => error.code(), + Self::State(error) => error.code(), + Self::Adapter(error) => error.code(), + Self::Rejected { .. } => "sync.rejected", + Self::Locked { .. } => "sync.locked", + Self::TypedBackWrong => "sync.typed_back_wrong", + Self::Unknown { .. } => "sync.unknown", + Self::NotAllowed { .. } => "sync.not_allowed", + Self::Cancelled => "sync.cancelled", + } + } +} + +// The state file's own failures (0054, The state file; Integrity and freshness). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum StateError { + // The file was made for another provider, server, account or device. + #[error("the state file belongs to another identity")] + WrongIdentity, + // The state MAC does not verify: the file is refused. + #[error("the state file's MAC does not verify")] + Integrity, + // A pending anchor entry could not be settled, so no commit may start (0054, A commit writes its anchor). + #[error("the anchor has a pending entry that cannot be settled")] + AnchorUnsettled, + // Another process holds the state file's lock (0054, Scheduling). + #[error("another process holds the state file")] + Busy, + #[error("the state file failed: {detail}")] + Io { detail: String }, +} + +impl StateError { + pub const fn code(&self) -> &'static str { + match self { + Self::WrongIdentity => "sync.state.wrong_identity", + Self::Integrity => "sync.state.integrity", + Self::AnchorUnsettled => "sync.state.anchor_unsettled", + Self::Busy => "sync.state.busy", + Self::Io { .. } => "sync.state.io", + } + } +} + +// A record adapter's failures, over the store it reads and writes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum AdapterError { + #[error("the {store} store failed: {detail}")] + Store { store: String, detail: String }, + // A record whose fields this build cannot read; the engine holds it by id (0054, Rules for both providers). + #[error("the record cannot be read: {detail}")] + Unreadable { detail: String }, + // The host's settings call failed. + #[error("the host's settings failed: {detail}")] + Host { detail: String }, +} + +impl AdapterError { + pub const fn code(&self) -> &'static str { + match self { + Self::Store { .. } => "sync.adapter.store", + Self::Unreadable { .. } => "sync.adapter.unreadable", + Self::Host { .. } => "sync.adapter.host", + } + } +} diff --git a/core/crates/sync/src/api/ids.rs b/core/crates/sync/src/api/ids.rs new file mode 100644 index 0000000000..1baa261636 --- /dev/null +++ b/core/crates/sync/src/api/ids.rs @@ -0,0 +1,258 @@ +use std::fmt; + +use tablepro_keys::encoding::{AccountId, TeamId}; +use tablepro_records::Kind; +use uuid::Uuid; + +use super::error::SyncError; + +// A scope as 0051 names it on the wire: `personal`, `history`, or the team's TypeID, `team_` and the team's UUID in +// lower-case Crockford base32. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ScopeName { + Personal, + History, + Team(TeamId), +} + +const TYPEID_ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz"; +const TEAM_PREFIX: &str = "team_"; + +impl ScopeName { + pub fn wire(self) -> String { + match self { + Self::Personal => "personal".to_owned(), + Self::History => "history".to_owned(), + Self::Team(team) => format!("{TEAM_PREFIX}{}", typeid_suffix(team.0)), + } + } + + pub fn parse(text: &str) -> Result { + match text { + "personal" => Ok(Self::Personal), + "history" => Ok(Self::History), + _ => text + .strip_prefix(TEAM_PREFIX) + .and_then(parse_typeid_suffix) + .map(|uuid| Self::Team(TeamId(uuid))) + .ok_or(SyncError::Malformed { what: "scope name" }), + } + } + + // 0051's scope type, which `tablepro_records` checks kinds against. + pub fn records_scope(self) -> tablepro_records::Scope { + match self { + Self::Personal => tablepro_records::Scope::Personal, + Self::History => tablepro_records::Scope::History, + Self::Team(_) => tablepro_records::Scope::Team, + } + } + + // The key scope a record of this sync scope is sealed or signed in (0056, Encoding). + pub fn key_scope(self, account: AccountId) -> tablepro_keys::encoding::Scope { + match self { + Self::Personal => tablepro_keys::encoding::Scope::Personal(account), + Self::History => tablepro_keys::encoding::Scope::History(account), + Self::Team(team) => tablepro_keys::encoding::Scope::Team(team), + } + } +} + +impl fmt::Display for ScopeName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.wire()) + } +} + +fn typeid_suffix(uuid: Uuid) -> String { + let value = uuid.as_u128(); + (0..26) + .rev() + .map(|index| { + let symbol = (value >> (index * 5)) & 0x1f; + char::from(TYPEID_ALPHABET[usize::from(u8::try_from(symbol).unwrap_or(0))]) + }) + .collect() +} + +// A TypeID suffix is 26 symbols whose first carries the two zero bits above 128. +fn parse_typeid_suffix(text: &str) -> Option { + if text.len() != 26 || !text.starts_with(|c: char| ('0'..='7').contains(&c)) { + return None; + } + let mut value: u128 = 0; + for byte in text.bytes() { + let symbol = TYPEID_ALPHABET.iter().position(|candidate| *candidate == byte)?; + value = (value << 5) | u128::try_from(symbol).ok()?; + } + Some(Uuid::from_u128(value)) +} + +// An epoch's id: a random UUID, never a counter (0051, Epochs). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct EpochId(pub Uuid); + +// Where a pull resumes. The service's cursor is opaque text; CloudKit's is the zone's change token. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Cursor { + Service(String), + CloudKit(Vec), +} + +// A write's precondition. The service's tag is opaque base64url text (0051, Change tags) and CloudKit's is the +// record's archived system fields (0054); a client never parses either. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ChangeTag { + Service(String), + CloudKit(Vec), +} + +impl fmt::Debug for ChangeTag { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Service(tag) => f.debug_tuple("Service").field(tag).finish(), + Self::CloudKit(bytes) => f.debug_tuple("CloudKit").field(&bytes.len()).finish(), + } + } +} + +// A kind as the wire carries it. A well-formed kind this build does not know is kept and sent back unchanged (0054). +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct KindName(String); + +impl KindName { + pub fn parse(name: &str) -> Result { + if tablepro_records::kind::well_formed(name) { + Ok(Self(name.to_owned())) + } else { + Err(SyncError::Malformed { what: "kind" }) + } + } + + pub fn of(kind: Kind) -> Self { + Self(kind.as_str().to_owned()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn known(&self) -> Option { + Kind::parse(&self.0).ok().flatten() + } + + pub fn is_key(&self) -> bool { + self.0.starts_with("key.") + } +} + +impl From for KindName { + fn from(kind: Kind) -> Self { + Self::of(kind) + } +} + +impl fmt::Display for KindName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +// One record in one scope: the store's key, and the key of every per-record state row. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct RecordKey { + pub scope: ScopeName, + pub kind: KindName, + pub record_id: String, +} + +impl RecordKey { + pub fn new(scope: ScopeName, kind: impl Into, record_id: impl Into) -> Self { + Self { + scope, + kind: kind.into(), + record_id: record_id.into(), + } + } +} + +// 1 to 255 visible ASCII characters; our clients send a UUIDv4 per batch (0051, Idempotency). +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct IdempotencyKey(pub String); + +impl IdempotencyKey { + pub fn parse(text: &str) -> Result { + let visible = !text.is_empty() && text.len() <= 255 && text.bytes().all(|byte| (0x21..=0x7e).contains(&byte)); + if visible { + Ok(Self(text.to_owned())) + } else { + Err(SyncError::Malformed { + what: "idempotency key", + }) + } + } +} + +// A device row's id as the server names it (`dev_...`), which a token and a stop report carry. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct DeviceRowId(pub String); + +// The 16 random bytes a state file is made with (0054, `binding`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FileId(pub [u8; 16]); + +// The hex digest that names one identity's state file (0054, One per provider and account). It stays the same when +// the file is lost or made again, so the device store finds an anchor that outlived its file by it. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct StateName(pub String); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_team_scope_is_its_typeid() { + let team = TeamId(Uuid::parse_str("01890a5d-ac96-774b-bcce-b302099a8057").unwrap()); + + let wire = ScopeName::Team(team).wire(); + + assert_eq!(wire, "team_01h455vb4pex5vsknk084sn02q"); + assert_eq!(ScopeName::parse(&wire).unwrap(), ScopeName::Team(team)); + assert_eq!( + ScopeName::Team(TeamId(Uuid::nil())).wire(), + "team_00000000000000000000000000" + ); + } + + #[test] + fn a_scope_name_that_is_not_one_is_refused() { + for text in [ + "", + "Personal", + "team_", + "team_81h455vb4pex5vsknk084sn02q", + "team_01h455vb4pex5vsknk084sn02u", + ] { + assert!(ScopeName::parse(text).is_err(), "{text}"); + } + assert_eq!(ScopeName::parse("history").unwrap(), ScopeName::History); + } + + #[test] + fn a_kind_keeps_what_this_build_does_not_know() { + let unknown = KindName::parse("future_kind").unwrap(); + + assert_eq!(unknown.known(), None); + assert_eq!(KindName::parse("connection").unwrap().known(), Some(Kind::Connection)); + assert!(KindName::parse("Not.A.Kind").is_err()); + assert!(KindName::parse("key.account").unwrap().is_key()); + } + + #[test] + fn an_idempotency_key_is_visible_ascii() { + assert!(IdempotencyKey::parse("4a6f").is_ok()); + assert!(IdempotencyKey::parse("").is_err()); + assert!(IdempotencyKey::parse("a b").is_err()); + assert!(IdempotencyKey::parse(&"a".repeat(256)).is_err()); + } +} diff --git a/core/crates/sync/src/api/key_flows.rs b/core/crates/sync/src/api/key_flows.rs new file mode 100644 index 0000000000..32a6868d41 --- /dev/null +++ b/core/crates/sync/src/api/key_flows.rs @@ -0,0 +1,886 @@ +// The end-to-end flows of 0056, one trait per lane that fills them, so each lane writes its own `impl` in its own +// files. Every method answers `sync.unimplemented` until its lane overrides it; the fake in `tablepro-sync-testing` +// overrides them all. Flows a person starts come through the FFI; the `apply_*`, `seal_*`, `open_*` and `resume_*` +// calls are the engine's, made during a pass in revision order. `KeyHooks` is how a flow stops or locks the engine +// and reports to the app. + +use async_trait::async_trait; +use secrecy::SecretString; +use serde_json::Value; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{AccountId, HistoryId, KeyDeviceId, RequestId, ResetId, TeamId, Version}; +use tablepro_keys::envelope::EnvelopeId; +use tablepro_keys::keys::Ed25519Public; +use uuid::Uuid; + +use super::error::SyncError; +use super::ids::{DeviceRowId, EpochId, ScopeName}; +use super::scopes::{Role, ScopeInfo, StopReport, TeamMember}; +use super::state::{KeyVersionState, PendingFlow, StoppedCause}; +use super::transport::{Change, ChangeOutcome, DpopKey, PulledPage, PulledRecord}; + +pub trait KeyFlows: + AccountFlows + ApprovalFlows + DeviceFlows + ResetFlows + TeamFlows + RestoreFlows + StopFlows +{ +} + +impl KeyFlows for T where + T: AccountFlows + ApprovalFlows + DeviceFlows + ResetFlows + TeamFlows + RestoreFlows + StopFlows +{ +} + +fn unimplemented(what: &'static str) -> Result { + Err(SyncError::unimplemented(what)) +} + +// K7-1: Keys, The recovery key, Pins, Genesis, Sign Out, Replace, Envelopes and history, Rollback. +#[async_trait] +pub trait AccountFlows: Send + Sync { + async fn key_state(&self) -> Result { + unimplemented("keys.key_state") + } + + // Genesis step 1: R is made and shown, with the two groups the person types back before anything is pushed. + async fn begin_genesis(&self) -> Result { + unimplemented("keys.begin_genesis") + } + + // Genesis step 2: the change set at `av` 1. When another device's genesis won, this device asks for approval. + async fn finish_genesis(&self, draft: DraftId, typed: TypedBack) -> Result { + let _ = (draft, typed); + unimplemented("keys.finish_genesis") + } + + // The revoke when online, then the device keys and key device id erased; nothing rotates (D7). + async fn sign_out(&self) -> Result { + unimplemented("keys.sign_out") + } + + // Replace Recovery Key: a rotation with R' and IK' endorsed by the old IK, which needs the current R. + // Shows R' and the devices the rotation can keep: this one, and those it compared with. + async fn begin_replace(&self, recovery_key: SecretString) -> Result { + let _ = recovery_key; + unimplemented("keys.begin_replace") + } + + // `keep` is the own-device pins the person ticked; every other device joins again by approval. + async fn finish_replace(&self, draft: DraftId, typed: TypedBack, keep: Vec) -> Result<(), SyncError> { + let _ = (draft, typed, keep); + unimplemented("keys.finish_replace") + } + + async fn own_fingerprint(&self) -> Result { + unimplemented("keys.own_fingerprint") + } + + // Another account's words, from the IK this device pinned for it. + async fn fingerprint(&self, account: AccountId) -> Result { + let _ = account; + unimplemented("keys.fingerprint") + } + + // A scanned `TPF1:` code against the account's pinned IK; a match counts as a comparison. + async fn compare_qr(&self, account: AccountId, text: String) -> Result { + let _ = (account, text); + unimplemented("keys.compare_qr") + } + + // An open key-change alert: the IK pinned and the one offered, each with its words, to compare before accepting. + async fn key_change(&self, account: AccountId) -> Result, SyncError> { + let _ = account; + unimplemented("keys.key_change") + } + + // Re-confirming after a key-change alert, by comparing or by accepting, which is recorded as `first_use`. Bound to + // the offered IK the person saw, so a different one offered since is not accepted with it. + async fn accept_key_change( + &self, + account: AccountId, + offered: Ed25519Public, + how: Acceptance, + ) -> Result<(), SyncError> { + let _ = (account, offered, how); + unimplemented("keys.accept_key_change") + } + + async fn notices(&self) -> Result, SyncError> { + unimplemented("keys.notices") + } + + async fn dismiss_notice(&self, notice: NoticeId) -> Result<(), SyncError> { + let _ = notice; + unimplemented("keys.dismiss_notice") + } + + // The personal scope's account certificates, device certificates, recovery blobs, PK and HK version records, + // their rings and their wraps. + async fn apply_account_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + unimplemented("keys.apply_account_objects") + } + + // A personal envelope under the newest PK version, after a pull of the key objects (0056, Writing). + async fn seal_personal_envelope( + &self, + envelope: EnvelopeId, + secret: SecretString, + dest: Value, + ) -> Result { + let _ = (envelope, secret, dest); + unimplemented("keys.seal_personal_envelope") + } + + // A pulled personal envelope, taken only under the version in force at its place in the order and never below + // the copy held (0056, Rollback, In order). `in_force` is None in a snapshot. + async fn open_personal_envelope( + &self, + envelope: EnvelopeId, + fields: Value, + in_force: Option, + ) -> Result { + let _ = (envelope, fields, in_force); + unimplemented("keys.open_personal_envelope") + } + + // A history entry encrypted at push time under the newest HK version. + async fn seal_history_entry(&self, entry: HistoryId, plaintext: Value) -> Result { + let _ = (entry, plaintext); + unimplemented("keys.seal_history_entry") + } + + async fn open_history_entry(&self, entry: HistoryId, fields: Value) -> Result { + let _ = (entry, fields); + unimplemented("keys.open_history_entry") + } +} + +// K7-2: Approving a device. +#[async_trait] +pub trait ApprovalFlows: Send + Sync { + // N: fixes its view, draws r_N and writes `key.request`. + async fn request_approval(&self) -> Result { + unimplemented("keys.request_approval") + } + + // A: the open requests of the account, newest first. + async fn approval_requests(&self) -> Result, SyncError> { + unimplemented("keys.approval_requests") + } + + // A: writes the `nonce` step. Another approver's step first is `create_only`, which closes this sheet. + async fn choose_request(&self, request: RequestId) -> Result { + let _ = request; + unimplemented("keys.choose_request") + } + + // Either side, polled every 1 to 2 seconds while the sheet is open. Words show once. + async fn approval_session(&self, request: RequestId) -> Result { + let _ = request; + unimplemented("keys.approval_session") + } + + // The person confirmed the words: A pushes the approval change set; N merges once it arrives. + async fn confirm_session(&self, request: RequestId) -> Result { + let _ = request; + unimplemented("keys.confirm_session") + } + + // The person says the words differ: a `cancel` step with `mismatch`. + async fn words_differ(&self, request: RequestId) -> Result<(), SyncError> { + let _ = request; + unimplemented("keys.words_differ") + } + + // A `cancel` step with `user`. + async fn cancel_session(&self, request: RequestId) -> Result<(), SyncError> { + let _ = request; + unimplemented("keys.cancel_session") + } + + // `key.request` and `key.sas` records as a pull serves them. + async fn apply_session_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + unimplemented("keys.apply_session_objects") + } + + async fn resume_approval(&self, request: RequestId) -> Result<(), SyncError> { + let _ = request; + unimplemented("keys.resume_approval") + } +} + +// K7-2: Rotation, Removing a device, Recovery. +#[async_trait] +pub trait DeviceFlows: Send + Sync { + // The account's key devices, as certificates, own-device pins and the server's device rows show them. + async fn account_devices(&self) -> Result, SyncError> { + unimplemented("keys.account_devices") + } + + // Step 1 of a removal: the row goes first, behind a fresh step-up (`sync.step_up_required` carries the challenge). + async fn remove_device_row(&self, device: DeviceRowId) -> Result<(), SyncError> { + let _ = device; + unimplemented("keys.remove_device_row") + } + + // Step 2: R typed, the sheet of devices to keep and members to review. + async fn begin_removal( + &self, + recovery_key: SecretString, + lost: Vec, + ) -> Result { + let _ = (recovery_key, lost); + unimplemented("keys.begin_removal") + } + + // Step 4: the rotation keeping `keep`, then each team rotated without `remove`; the choices stay in `key_pending`. + async fn finish_removal( + &self, + review: DraftId, + keep: Vec, + remove: Vec, + ) -> Result<(), SyncError> { + let _ = (review, keep, remove); + unimplemented("keys.finish_removal") + } + + // Recovery with R on a device with no approved device at hand: a rotation that keeps only this device. + async fn recover(&self, recovery_key: SecretString) -> Result<(), SyncError> { + let _ = recovery_key; + unimplemented("keys.recover") + } + + async fn resume_rotation(&self, av: Version) -> Result<(), SyncError> { + let _ = av; + unimplemented("keys.resume_rotation") + } +} + +// K7-2: Reset. +#[async_trait] +pub trait ResetFlows: Send + Sync { + async fn pending_reset(&self) -> Result, SyncError> { + unimplemented("keys.pending_reset") + } + + // Kind 2 from an approved device, kind 3 from a sign-in whose device is not, after a step-up. R' is shown. + async fn begin_reset(&self, kind: ResetKind) -> Result { + let _ = kind; + unimplemented("keys.begin_reset") + } + + // The `key.reset` alone; the honest server holds it 7 days. + async fn finish_reset_proposal(&self, draft: DraftId, typed: TypedBack) -> Result { + let _ = (draft, typed); + unimplemented("keys.finish_reset_proposal") + } + + async fn cancel_reset(&self, reset: ResetId, with: CancelWith) -> Result<(), SyncError> { + let _ = (reset, with); + unimplemented("keys.cancel_reset") + } + + // The activation change set, from the proposing device, once `held_until` passed. + async fn activate_reset(&self, reset: ResetId) -> Result<(), SyncError> { + let _ = reset; + unimplemented("keys.activate_reset") + } + + // `key.reset` and `key.cancel` records as a pull serves them. + async fn apply_reset_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + unimplemented("keys.apply_reset_objects") + } + + async fn resume_reset(&self, reset: ResetId) -> Result<(), SyncError> { + let _ = reset; + unimplemented("keys.resume_reset") + } +} + +// K7-3: Teams. +#[async_trait] +pub trait TeamFlows: Send + Sync { + async fn team_keys(&self, team: TeamId) -> Result { + let _ = team; + unimplemented("keys.team_keys") + } + + // A team creation: the owner's `key.member`, TK v1 with `start` 1 and its wrap to the owner's AEK. + async fn create_team_keys(&self, team: TeamId) -> Result<(), SyncError> { + let _ = team; + unimplemented("keys.create_team_keys") + } + + // This account's current certificate as `key.member`: on joining, with every replace, and after every `av` change. + async fn publish_member_certificate(&self, team: TeamId) -> Result<(), SyncError> { + let _ = team; + unimplemented("keys.publish_member_certificate") + } + + // An owner's or admin's Confirm: the current version wrapped to the member's AEK. Pins on first use. + async fn confirm_member(&self, team: TeamId, account: AccountId) -> Result<(), SyncError> { + let _ = (team, account); + unimplemented("keys.confirm_member") + } + + // The next version, its ring and a wrap to each holder on the roster with no open alert, less `remove`. Also how + // an owner or admin who held a stopped device's version confirms it again. + async fn rotate_team(&self, team: TeamId, remove: Vec) -> Result<(), SyncError> { + let _ = (team, remove); + unimplemented("keys.rotate_team") + } + + // An owner's restart with `start` 1 when no member on the roster holds the current version, wrapping to `confirm`. + async fn restart_team(&self, team: TeamId, confirm: Vec) -> Result<(), SyncError> { + let _ = (team, confirm); + unimplemented("keys.restart_team") + } + + // A restart of a team key this device held a version of, which it holds until the person compares the restarting + // owner's words (0064). + async fn held_restart(&self, team: TeamId) -> Result, SyncError> { + let _ = team; + unimplemented("keys.held_restart") + } + + // The person compared the restarting owner's six words and accepts: the restart applies, its signer is the holder + // and its pin `compared`. Bound to the IK the person compared; accepting without comparing is not offered. + async fn accept_restart(&self, team: TeamId, signer_ik: Ed25519Public) -> Result<(), SyncError> { + let _ = (team, signer_ik); + unimplemented("keys.accept_restart") + } + + // "Credentials to rotate": the envelopes a removed party could read (0056, Old data). + async fn credentials_to_rotate(&self, scope: ScopeName) -> Result, SyncError> { + let _ = scope; + unimplemented("keys.credentials_to_rotate") + } + + // The roster, `rotation_due` and the caller's role from a scopes body, decided on only after the team's pull is + // caught up. + async fn roster_read(&self, team: TeamId, roster: Roster) -> Result<(), SyncError> { + let _ = (team, roster); + unimplemented("keys.roster_read") + } + + // A team scope's `key.member`, version records, rings and wraps. + async fn apply_team_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + unimplemented("keys.apply_team_objects") + } + + async fn seal_team_envelope( + &self, + team: TeamId, + envelope: EnvelopeId, + secret: SecretString, + dest: Value, + ) -> Result { + let _ = (team, envelope, secret, dest); + unimplemented("keys.seal_team_envelope") + } + + async fn open_team_envelope( + &self, + team: TeamId, + envelope: EnvelopeId, + fields: Value, + in_force: Option, + ) -> Result { + let _ = (team, envelope, fields, in_force); + unimplemented("keys.open_team_envelope") + } +} + +// K7-4: After a restore; What cannot go back. +#[async_trait] +pub trait RestoreFlows: Send + Sync { + // On a new epoch, before any other record: the key objects this account signed that the snapshot lacks, as + // change sets in 0051's order. The engine pushes them one at a time and answers each. + async fn push_back(&self, epoch: EpochId) -> Result, SyncError> { + let _ = epoch; + unimplemented("keys.push_back") + } + + // Every refusal is final: the scope ends on this device, or the account's devices lock. + async fn push_back_answered( + &self, + set: KeyChangeSet, + outcomes: Vec, + ) -> Result { + let _ = (set, outcomes); + unimplemented("keys.push_back_answered") + } +} + +// K7-4: A stopped device. +#[async_trait] +pub trait StopFlows: Send + Sync { + // The reports and withdrawals to send, withdrawals first per team (0054, `key_pending`). + async fn stop_actions(&self) -> Result, SyncError> { + unimplemented("keys.stop_actions") + } + + async fn stop_action_sent(&self, action: StopAction) -> Result<(), SyncError> { + let _ = action; + unimplemented("keys.stop_action_sent") + } + + async fn resume_withdrawal(&self, team: TeamId) -> Result<(), SyncError> { + let _ = team; + unimplemented("keys.resume_withdrawal") + } +} + +// The engine's side: how a key flow stops or locks it and reports to the app. Each returns at once. +pub trait KeyHooks: Send + Sync { + // Nothing personal syncs; the device keeps its keys and shows why. + fn lock(&self, cause: LockCause); + + // The scope writes no secret under its key and holds its envelopes in the queue. The cause is the one its + // `key_versions` row records (0062); a team due a rotation is the engine's own wait, from the scopes body. + fn stop_scope(&self, scope: ScopeName, cause: StoppedCause); + + fn resume_scope(&self, scope: ScopeName); + + // Nothing clears it: a refused push-back or a fork (`keys.conflict`). + fn end_scope(&self, scope: ScopeName, epoch: Option); + + fn notice(&self, notice: KeyNotice); + + // A flow wrote something a pass should carry. + fn pass_soon(&self); +} + +// A draft, review or other flow step this service holds between two calls. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct DraftId(pub Uuid); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct NoticeId(pub Uuid); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyState { + // No secret store: team plaintext records only. + NoDeviceStore, + // The key kinds have not been read yet. + Unknown, + // The account has no `key.account`: genesis is offered. + NoKeys, + // The account has keys and this device holds none it can use: approval, recovery or reset is offered. + NeedsApproval { request: Option }, + Approved { av: Version, key_device: KeyDeviceId }, + Locked { cause: LockCause }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum LockCause { + // 403 `device_removed`. + DeviceRemoved, + // A verified certificate at a newer `av` and none for this key device in its change set. + LeftOutOfRotation, + // An unendorsed IK on the own account, as after a reset elsewhere. + OwnAccountReset, + // A refused push-back of the account's own objects: sign out, then recover or reset. + AccountEnded, + // A state file with no anchor handles no secret until approved again or recovered. + Unanchored, + // A personal or history catch-up it could not verify (`keys.stale`). + PersonalStopped, +} + +// R as the person sees it once, and the two of its 14 groups they type back. +#[derive(Debug, Clone)] +pub struct RecoveryKeyDraft { + pub draft: DraftId, + pub text: SecretString, + // Group indexes from 0 to 13, chosen at random. + pub check: [u8; 2], +} + +#[derive(Debug, Clone)] +pub struct TypedBack { + pub groups: [SecretString; 2], +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum GenesisOutcome { + Created, + // The keys made here are discarded and the device asks for approval. + AnotherDeviceWon, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SignOutOutcome { + Revoked, + // Offline: erased anyway; the row keeps the old certificate until approved again, left out or removed. + ErasedOffline, +} + +// A held restart: the version, the account that signed it, and the words the person compares before accepting. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeldRestart { + pub team: TeamId, + pub version: Version, + pub signer: AccountId, + pub signer_ik: Ed25519Public, + pub words: Fingerprint, +} + +// R' as a draft, with the devices a rotation can keep, ticked by default when compared. +#[derive(Debug, Clone)] +pub struct RotationDraft { + pub recovery: RecoveryKeyDraft, + pub devices: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyChange { + pub account: AccountId, + pub pinned: Fingerprint, + pub offered: Fingerprint, + pub offered_ik: Ed25519Public, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Fingerprint { + // Words 0 to 5 of the account's fingerprint. + pub words: Vec, + // `TPF1:` and 52 Base32 symbols. + pub qr: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Acceptance { + Compared, + WithoutComparing, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyNotice { + pub id: NoticeId, + pub kind: KeyNoticeKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyNoticeKind { + // "Ana replaced her recovery key." + RecoveryKeyReplaced { account: AccountId }, + // An alert in every team the account is in. + KeysChanged { account: AccountId }, + TeamKeyRestarted { team: TeamId }, + // "The team key was started over by Ana. Compare her words before using it." (0064) + RestartHeld { team: TeamId, signer: AccountId }, + ResetPending { reset: ResetId }, + ResetEnded { reset: ResetId, state: ResetState }, + DeviceRemoved { device: DeviceRowId }, + // A wrap or version addressed to one of this account's superseded `av`s: the member copied its certificate again. + SupersededWrap { team: TeamId }, + // A key object at a held id with other fields, or another record at an anchored version. + Conflict { scope: ScopeName }, + ScopeStopped { scope: ScopeName, cause: StoppedCause }, + ScopeEnded { scope: ScopeName }, + Locked { cause: LockCause }, +} + +// What a pull served for the key layer, in revision order on a delta page; a snapshot's go in as one set once the +// pull is caught up (0056, Rollback). +#[derive(Debug, Clone, PartialEq)] +pub struct KeyArrival { + pub scope: ScopeName, + pub records: Vec, + pub order: ArrivalOrder, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ArrivalOrder { + InOrder, + Snapshot, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct KeyApplied { + // The scope key version in force after the last record, which the engine stores with the cursor. + pub in_force: Option, + // Held until the certificate or version record they name arrives, never refused for that. + pub held: Vec, + pub refused: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RefusedObject { + pub record_id: String, + pub error: KeysError, +} + +#[derive(Debug, Clone)] +pub struct OpenedEnvelope { + pub secret: SecretString, + // The destination it was sealed for, which the record's current fields must match at use. + pub dest: Value, + pub kv: Version, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovalRequest { + pub request: RequestId, + pub device: Option, + pub device_name: Option, + pub platform: Option, + pub requested_at_us: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SessionRole { + NewDevice, + Approver, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SessionPhase { + // N's request is written; no approver holds it yet. + Open, + // An approver wrote its `nonce` step. + Chosen, + // Both sides can show the words. + Compare { words: Vec }, + // This side's person confirmed; waiting for the other side. + Confirmed, + Approved, + // Another approver holds the session: "being approved on Mac mini". + TakenElsewhere, + Cancelled { reason: SessionEnd }, + Expired, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SessionEnd { + User, + Mismatch, + Commitment, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovalSession { + pub request: RequestId, + pub role: SessionRole, + pub phase: SessionPhase, + pub expires_at_us: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AccountDevice { + pub key_device: KeyDeviceId, + pub device: Option, + pub name: Option, + pub platform: Option, + pub added_at_us: Option, + pub this_device: bool, + // This device compared with it, so a rotation can keep it. + pub compared: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RemovalReview { + pub review: DraftId, + pub devices: Vec, + // Members this account confirmed under an `av` a lost device held a certificate for. + pub members: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReviewedDevice { + pub device: AccountDevice, + // Ticked by default: compared, and not one of the lost devices. + pub keep_by_default: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ReviewedMember { + pub team: TeamId, + pub account: AccountId, + pub confirmed_under_av: Version, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResetKind { + // Kind 2: keeps the scope keys this device holds. + KeepScopeKeys, + // Kind 3: starts empty; the server deletes the personal and history records when it activates. + StartEmpty, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResetState { + Pending, + Cancelled, + Superseded, + Active, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PendingReset { + pub reset: ResetId, + pub kind: ResetKind, + pub state: ResetState, + // This device proposed it, so it may activate it. + pub mine: bool, + pub proposed_by: Option, + pub taken_at_us: i64, + pub held_until_us: i64, +} + +#[derive(Debug, Clone)] +pub enum CancelWith { + // A device certified at the current `av`. + ThisDevice, + // R's IK signature, carried by any device of the account. + RecoveryKey(SecretString), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TeamKeys { + pub team: TeamId, + pub version: Option, + pub state: KeyVersionState, + pub stopped_cause: Option, + pub rotation_due: bool, + // This account holds the current version. + pub holder: bool, + pub members: Vec, + // The stop reports owners and admins see (0051, A stopped device). + pub stopped: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoppedDevice { + pub account: AccountId, + pub device: DeviceRowId, + pub version: Version, + // This account held that version, so its rotation confirms the device again; the app offers it only then. + pub can_reconfirm: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemberKeys { + pub account: AccountId, + pub role: Role, + pub status: MemberKeyStatus, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MemberKeyStatus { + // "Waiting for this person to set up their keys." + NoKeys, + // "Waiting for confirmation." + AwaitingConfirmation, + Holder, + // A key-change alert: nothing is wrapped to it until re-confirmed. + Alert, +} + +// A team scope as one scopes body gives it. A device decides on the roster only after its pull of that team is caught +// up, and a roster it could not read is no evidence that a member left (0051, `members`; What cannot go back). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Roster { + pub members: Vec, + pub role: Option, + pub rotation_due: bool, + // The stop reports, which the server serves to owners and admins only (0051, A stopped device). + pub stopped: Vec, + caught_up: bool, +} + +impl Roster { + // `pull` is the catch-up of this team's pull that followed this body. None, or one of another scope, leaves the + // roster undecided, whatever a stored flag says. + pub fn of(scope: &ScopeInfo, pull: Option) -> Self { + Self { + members: scope.members.clone(), + role: scope.role, + rotation_due: scope.rotation_due, + stopped: scope.stopped.clone(), + caught_up: pull.is_some_and(|pull| pull.scope == scope.scope), + } + } + + pub fn caught_up(&self) -> bool { + self.caught_up + } +} + +// A pull page with no records for one scope: the only thing that lets a roster be decided on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CaughtUp { + scope: ScopeName, +} + +impl CaughtUp { + pub fn from_page(scope: ScopeName, page: &PulledPage) -> Option { + (page.caught_up && page.records.is_empty()).then_some(Self { scope }) + } +} + +// One change set as one push: only its own key objects, applied whole or not at all. +#[derive(Debug, Clone, PartialEq)] +pub struct KeyChangeSet { + pub scope: ScopeName, + pub changes: Vec, + pub proof: DpopKey, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PushBackVerdict { + Continue, + // The scope stops until what it waits for is back. + Wait { scope: ScopeName }, + Ended { scope: ScopeName }, + // The account's own objects were refused: its devices lock. + AccountEnded, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StopAction { + Report { team: TeamId, version: Version }, + Withdraw { team: TeamId }, +} + +impl StopAction { + pub const fn pending_flow(self) -> Option { + match self { + Self::Report { .. } => None, + Self::Withdraw { team } => Some(PendingFlow::StopWithdrawal { team }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Unfilled; + + impl AccountFlows for Unfilled {} + impl ApprovalFlows for Unfilled {} + impl DeviceFlows for Unfilled {} + impl ResetFlows for Unfilled {} + impl TeamFlows for Unfilled {} + impl RestoreFlows for Unfilled {} + impl StopFlows for Unfilled {} + + fn takes_flows(flows: &impl KeyFlows) -> &impl KeyFlows { + flows + } + + #[tokio::test] + async fn an_unfilled_flow_answers_unimplemented_with_its_name() { + let flows = takes_flows(&Unfilled); + + let genesis = flows.begin_genesis().await; + let push_back = flows.push_back(EpochId(Uuid::nil())).await; + + assert_eq!(genesis.unwrap_err(), SyncError::unimplemented("keys.begin_genesis")); + assert_eq!(push_back.unwrap_err().code(), "sync.unimplemented"); + } +} diff --git a/core/crates/sync/src/api/legacy.rs b/core/crates/sync/src/api/legacy.rs new file mode 100644 index 0000000000..1858466ddc --- /dev/null +++ b/core/crates/sync/src/api/legacy.rs @@ -0,0 +1,129 @@ +// The Swift engine's iCloud metadata, which the Mac imports once on the core engine's first launch and writes back +// while the previous stable still runs the Swift engine (0054, The Apple apps on the engine; Downgrade mirror). The +// host reads and writes UserDefaults and the `SyncRecordCache` files; the engine decides what they hold. + +use async_trait::async_trait; +use uuid::Uuid; + +use super::cloudkit::CloudKitRecord; +use super::error::AdapterError; +use super::state::Standing; + +#[async_trait] +pub trait LegacyMirror: Send + Sync { + // At launch: what the Swift metadata holds now. One that differs from what the mirror last wrote means an older + // build ran in between, and the engine imports it again. + async fn read(&self) -> Result; + + // After every committed pass. + async fn write(&self, metadata: LegacyMetadata) -> Result<(), AdapterError>; + + // On every journal signal, offline too, after the store write: the records that write changed. + async fn mark(&self, dirty: Vec, tombstones: Vec) -> Result<(), AdapterError>; +} + +impl LegacyMetadata { + // What the import takes for the iCloud account the engine runs for, as Swift's `adoptAccount` does: metadata of + // another account, or of none, keeps only the dirty keys and the standing; the server position, tombstones, held + // sets and cache are that other account's. + #[must_use] + pub fn for_account(self, account: &str) -> Self { + if self.account.as_deref() == Some(account) { + return self; + } + Self { + dirty: self.dirty, + standing: self.standing, + account: Some(account.to_owned()), + ..Self::default() + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct LegacyMetadata { + // The archived `CKServerChangeToken`. + pub token: Option>, + pub dirty: Vec, + pub tombstones: Vec, + pub deferred_deletions: Vec, + // Record names a pull changed while this device's copy could not be read, fetched by id once it reads. + pub changes_held_for_unreadable: Vec, + // Unread copies a pull deleted, removed by the next save of their file. + pub removals_pending_for_unreadable: Vec, + // Deletions pulled while this device could not tell whether its unreadable copy syncs. + pub deletions_held_for_unreadable: Vec, + pub owners_kept_off_sync: Vec, + pub standing: Vec, + pub readable_record_types: Vec, + pub account: Option, + pub zone_state: Option, + // `SyncRecordCache`: each record as last agreed, with its system fields. + pub cache: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn metadata(account: Option<&str>) -> LegacyMetadata { + let record = LegacyRecordRef { + record_type: "Connection".to_owned(), + id: "A".to_owned(), + }; + LegacyMetadata { + token: Some(vec![1]), + dirty: vec![record.clone()], + tombstones: vec![LegacyTombstone { + record, + deleted_at_ms: 1, + owner: None, + }], + deferred_deletions: vec!["Group_B".to_owned()], + changes_held_for_unreadable: vec!["Connection_C".to_owned()], + standing: vec![LegacyStanding { + connection: Uuid::nil(), + standing: Standing::LocalOnly, + }], + account: account.map(str::to_owned), + ..LegacyMetadata::default() + } + } + + #[test] + fn another_account_s_metadata_imports_only_the_dirty_keys_and_the_standing() { + let same = metadata(Some("_a")).for_account("_a"); + let other = metadata(Some("_b")).for_account("_a"); + let none = metadata(None).for_account("_a"); + + assert_eq!(same, metadata(Some("_a"))); + for imported in [other, none] { + assert_eq!(imported.dirty, metadata(None).dirty); + assert_eq!(imported.standing, metadata(None).standing); + assert_eq!(imported.token, None); + assert!(imported.tombstones.is_empty() && imported.deferred_deletions.is_empty()); + assert!(imported.changes_held_for_unreadable.is_empty()); + } + } +} + +// A record by its Swift record type and id. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct LegacyRecordRef { + pub record_type: String, + pub id: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct LegacyTombstone { + pub record: LegacyRecordRef, + // Milliseconds since the Unix epoch, which the Swift engine prunes tombstones by. + pub deleted_at_ms: i64, + pub owner: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct LegacyStanding { + pub connection: Uuid, + pub standing: Standing, +} diff --git a/core/crates/sync/src/api/mod.rs b/core/crates/sync/src/api/mod.rs new file mode 100644 index 0000000000..bdc1d89eed --- /dev/null +++ b/core/crates/sync/src/api/mod.rs @@ -0,0 +1,35 @@ +// The contracts the engine, the transports, the key flows and the FFI build against (0051, 0054, 0056). + +pub mod adapter; +pub mod cloudkit; +pub mod control; +pub mod device_store; +pub mod error; +pub mod ids; +pub mod key_flows; +pub mod legacy; +pub mod scopes; +pub mod state; +pub mod transport; + +pub use adapter::{HostSettings, LocalChange, LocalRecord, LocalRecords, RecordAdapter, SettingsDocument, StoreStamp}; +pub use cloudkit::{ + CloudKitAccount, CloudKitChanges, CloudKitDeletion, CloudKitFailure, CloudKitFetched, CloudKitField, + CloudKitOutcome, CloudKitRecord, CloudKitTransport, CloudKitValue, +}; +pub use control::SyncControl; +pub use device_store::{DeviceItem, DeviceItemClass, DeviceStoreError, HostDeviceStore}; +pub use error::{AdapterError, StateError, SyncError}; +pub use ids::{ + ChangeTag, Cursor, DeviceRowId, EpochId, FileId, IdempotencyKey, KindName, RecordKey, ScopeName, StateName, +}; +pub use key_flows::{ + AccountFlows, ApprovalFlows, DeviceFlows, KeyFlows, KeyHooks, ResetFlows, RestoreFlows, StopFlows, TeamFlows, +}; +pub use legacy::{LegacyMetadata, LegacyMirror}; +pub use scopes::{ScopeInfo, ScopesAnswer, ScopesBody}; +pub use state::{Row, RowKey, RowRange, StateFiles, StateStore, StateTxn, Table}; +pub use transport::{ + Change, ChangeOp, ChangeOutcome, DpopKey, Proof, PullRequest, PulledPage, PulledRecord, PushAnswer, PushBatch, + RejectedCode, ServiceTransport, Transport, TransportError, +}; diff --git a/core/crates/sync/src/api/scopes.rs b/core/crates/sync/src/api/scopes.rs new file mode 100644 index 0000000000..1680e1fcf0 --- /dev/null +++ b/core/crates/sync/src/api/scopes.rs @@ -0,0 +1,130 @@ +use tablepro_keys::encoding::{AccountId, Version}; + +use super::ids::{DeviceRowId, EpochId, ScopeName}; + +// `GET /v2/sync/scopes` (0051): the scopes this sign-in reaches and what the server advertises. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScopesBody { + // The current epoch's id. + pub epoch: EpochId, + pub scopes: Vec, + pub limits: ServerLimits, + pub server_version: String, + pub capabilities: Vec, + pub idempotency_retention_secs: u64, + pub poll_interval_secs: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScopeInfo { + pub scope: ScopeName, + // A team scope's role for the caller; None on the personal and history scopes. + pub role: Option, + // The scope's highest committed revision, 0 before its first write. + pub horizon: u64, + // The lineage, oldest first, each epoch with the scope's kept revision (0 when it has no cut). + pub epochs: Vec, + // False past grace or after a lapse, when only key-object writes are taken. + pub writable: bool, + pub policies: ScopePolicies, + pub quota: Option, + // Team scopes only. + pub rotation_due: bool, + // A team's roster for every seat; a server assertion, never a holder check (0051, `members`). + pub members: Vec, + // Stop reports, served to owners and admins only. + pub stopped: Vec, + // The personal and history scopes, when the request carried a DPoP proof. + pub approved: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct LineageEpoch { + pub id: EpochId, + pub kept_revision: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Role { + Owner, + Admin, + Editor, + Member, +} + +impl Role { + pub const fn as_str(self) -> &'static str { + match self { + Self::Owner => "owner", + Self::Admin => "admin", + Self::Editor => "editor", + Self::Member => "member", + } + } + + pub fn parse(text: &str) -> Option { + [Self::Owner, Self::Admin, Self::Editor, Self::Member] + .into_iter() + .find(|role| role.as_str() == text) + } + + // Owners and admins confirm members and rotate at any time (0051, Roles in a team scope). + pub const fn manages_keys(self) -> bool { + matches!(self, Self::Owner | Self::Admin) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct TeamMember { + pub account: AccountId, + pub role: Role, +} + +// One device row's report that it stopped on a team at a version (0051, A stopped device). +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct StopReport { + pub account: AccountId, + pub device: DeviceRowId, + pub version: Version, +} + +// The switches that apply to a scope, true when on (0051, Policies). A switch the scope does not carry is None. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub struct ScopePolicies { + pub personal_sync: Option, + pub password_sync: Option, + pub history_sync: Option, +} + +// 0051, Limits, as the server advertises them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ServerLimits { + pub record_bytes: u64, + pub body_bytes: u64, + pub changes_per_push: u32, + pub changes_per_change_set: u32, + pub page_records: u32, + pub page_bytes: u64, + pub json_depth: u32, + pub team_key_holders: u32, +} + +impl ServerLimits { + pub const ADR_0051: Self = Self { + record_bytes: 1 << 20, + body_bytes: 4 << 20, + changes_per_push: 500, + changes_per_change_set: 10_000, + page_records: 500, + page_bytes: 4 << 20, + json_depth: 32, + team_key_holders: 5_000, + }; +} + +// The answer to a poll: 304 when `If-None-Match` matched the strong ETag, else the body with its ETag. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScopesAnswer { + NotModified, + Body { body: Box, etag: String }, +} diff --git a/core/crates/sync/src/api/state.rs b/core/crates/sync/src/api/state.rs new file mode 100644 index 0000000000..7c78618e28 --- /dev/null +++ b/core/crates/sync/src/api/state.rs @@ -0,0 +1,970 @@ +use async_trait::async_trait; +use serde_json::Value; +use tablepro_keys::encoding::{AccountId, KeyDeviceId, KeyPurpose, Origin, RequestId, ResetId, TeamId, Version}; +use tablepro_keys::keys::{Ed25519Public, X25519Public}; +use tablepro_keys::sas::{Role as ComparisonRole, SessionState}; +use tablepro_keys::trust::PinHow; +use uuid::Uuid; + +use super::error::StateError; +use super::ids::{ChangeTag, Cursor, EpochId, FileId, IdempotencyKey, KindName, RecordKey, ScopeName}; +use super::scopes::{LineageEpoch, Role, ScopePolicies}; +use super::transport::{DeletedReason, PulledRecord}; + +// One state file per provider and account (0054, The state file): SQLite in WAL mode, its sync and key tables, the +// state MAC over both digests, and the anchor in the device store. A pass reads and writes it through one transaction, +// which commits whole: the tables, then the counter and MAC, with the anchor's two steps around it. +#[async_trait] +pub trait StateStore: Send + Sync { + // What the file is bound to; its `binding` row holds it with the file id, the counter and the MAC. + fn identity(&self) -> &StateIdentity; + + // What opening found; it does not change while the file is open. + fn opened(&self) -> &Opened; + + async fn begin(&self) -> Result, StateError>; +} + +// Rows read and written in one commit. Dropping it uncommitted writes nothing. +#[async_trait] +pub trait StateTxn: Send { + async fn get(&mut self, key: &RowKey) -> Result, StateError>; + + // In the byte order of the encoded primary keys, as the digests read them. + async fn scan(&mut self, range: &RowRange) -> Result, StateError>; + + async fn put(&mut self, row: Row) -> Result<(), StateError>; + + async fn delete(&mut self, key: &RowKey) -> Result<(), StateError>; + + // Erases every key table in this commit: Sign Out, or another account on this row (0054, The device's key state). + async fn clear_key_tables(&mut self) -> Result<(), StateError>; + + async fn commit(self: Box) -> Result; +} + +// Opens the state file of one identity, refusing a file made for another, and deletes one whole. +#[async_trait] +pub trait StateFiles: Send + Sync { + async fn open(&self, identity: StateIdentity) -> Result, StateError>; + + async fn delete(&self, identity: StateIdentity) -> Result<(), StateError>; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Provider { + Service, + ICloud, +} + +// What a state file is bound to. Another identity opens another file, so nothing crosses accounts. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum StateIdentity { + Service { + origin: Origin, + // The sign-in key, which names the server and the account file (tablepro-account). + sign_in: String, + account: AccountId, + device_row: super::ids::DeviceRowId, + }, + ICloud { + user_record_name: String, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Committed { + pub counter: u64, +} + +// What the file and its anchor said at open (0054, On open). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Opened { + pub sync_tables: SyncTrust, + pub key_tables: KeyTrust, +} + +impl Opened { + pub const FRESH: Self = Self { + sync_tables: SyncTrust::Trusted, + key_tables: KeyTrust::Trusted, + }; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SyncTrust { + Trusted, + // A restored, replaced or uncertain file: the pull wins, records the provider never saw go up as creates. + Refill, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyTrust { + Trusted, + // A stale file, or an anchor with no file: rebuild from the server's key objects at or above this checkpoint, + // accepting no wrap or envelope and writing no secret until the server shows every anchored pin and version. + Rebuild { checkpoint: Box }, + // A file with no anchor: it handles no secret until another device approves it again or the person recovers. + Unanchored, +} + +// What only moves forward (0054, The checkpoint). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Checkpoint { + pub pins: Vec, + pub versions: Vec, + pub envelopes: Vec, +} + +// The tables in digest order: the sync tables as 0054 lists them, then the key tables. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Table { + Binding, + Scopes, + Stores, + Bases, + // 0064: the bases a pull will apply, written before the store; at a restart one whose store copy matches becomes + // the base, and one that does not stays a local edit. + PendingBases, + Standing, + Held, + Deferred, + Outbox, + Approvals, + Conflicts, + LegacyMirror, + KeyObjects, + KeyPins, + KeyDevicePins, + KeyVersions, + KeyEnvelopes, + KeyComparisons, + KeyPending, + DeletedHistory, +} + +impl Table { + pub const SYNC: [Self; 12] = [ + Self::Binding, + Self::Scopes, + Self::Stores, + Self::Bases, + Self::PendingBases, + Self::Standing, + Self::Held, + Self::Deferred, + Self::Outbox, + Self::Approvals, + Self::Conflicts, + Self::LegacyMirror, + ]; + + pub const KEY: [Self; 8] = [ + Self::KeyObjects, + Self::KeyPins, + Self::KeyDevicePins, + Self::KeyVersions, + Self::KeyEnvelopes, + Self::KeyComparisons, + Self::KeyPending, + Self::DeletedHistory, + ]; + + pub const fn name(self) -> &'static str { + match self { + Self::Binding => "binding", + Self::Scopes => "scopes", + Self::Stores => "stores", + Self::Bases => "bases", + Self::PendingBases => "pending_bases", + Self::Standing => "standing", + Self::Held => "held", + Self::Deferred => "deferred", + Self::Outbox => "outbox", + Self::Approvals => "approvals", + Self::Conflicts => "conflicts", + Self::LegacyMirror => "legacy_mirror", + Self::KeyObjects => "key_objects", + Self::KeyPins => "key_pins", + Self::KeyDevicePins => "key_device_pins", + Self::KeyVersions => "key_versions", + Self::KeyEnvelopes => "key_envelopes", + Self::KeyComparisons => "key_comparisons", + Self::KeyPending => "key_pending", + Self::DeletedHistory => "deleted_history", + } + } + + pub const fn is_key_table(self) -> bool { + matches!( + self, + Self::KeyObjects + | Self::KeyPins + | Self::KeyDevicePins + | Self::KeyVersions + | Self::KeyEnvelopes + | Self::KeyComparisons + | Self::KeyPending + | Self::DeletedHistory + ) + } +} + +// Each row's fields are its columns in order, the primary key first. + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BindingRow { + pub provider: Provider, + // The server origin; None on iCloud. + pub origin: Option, + // The account id, or the iCloud user record name. + pub account: String, + pub device: String, + pub schema_version: u32, + pub file_id: FileId, + // Raised by one on every commit; the store sets it. + pub counter: u64, + // Left out of the sync digest, since it is computed over it. + pub state_mac: [u8; 32], +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScopeRow { + pub scope: ScopeName, + pub role: Option, + pub epoch: Option, + // The service's cursor, or the zone's change token on iCloud. + pub cursor: Option, + // The scope key version in force at `cursor`, moved only by applying a pull (0054, A pass). + pub key_version: Option, + pub horizon: Option, + pub policies: ScopePolicies, + // The lineage the device last read, against which a new epoch's cut is found (0051, Lost writes). + pub lineage: Vec, + // The history scope's cursor for older entries, kept to page back on demand. + pub older_cursor: Option, + // The kinds the last pull read. A build that reads more fetches what it held for the others again. + pub read_kinds: Vec, + pub refill: bool, + pub rotation_due: bool, + // The last pull reached a page with no records. It schedules pulls; a roster decision takes the `CaughtUp` of a + // pull that followed its scopes body, never this flag. + pub caught_up: bool, +} + +impl ScopeRow { + pub fn new(scope: ScopeName) -> Self { + Self { + scope, + role: None, + epoch: None, + cursor: None, + key_version: None, + horizon: None, + policies: ScopePolicies::default(), + lineage: Vec::new(), + older_cursor: None, + read_kinds: Vec::new(), + refill: false, + rotation_due: false, + caught_up: false, + } + } +} + +// One row per store file the core keeps, such as `connections.json` or `history.db`: every kind that file holds refills +// together (0060, 0064). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoreRow { + // The store file's name. + pub store: String, + pub generation: Uuid, + pub sequence: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BaseRow { + pub key: RecordKey, + pub tag: ChangeTag, + pub version: Option, + pub revision: Option, + // The epoch the copy was written in, which a new epoch's cut judges it against (0051, Lost writes). + pub epoch: Option, + // A policy tombstone's base, which a revival patches on. + pub deleted: Option, + // The fields as last agreed; None for create-once kinds. + pub fields: Option, + // CloudKit's creation date of the record the base came from, in milliseconds; None on the service. + pub created_ms: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Standing { + Syncs, + LocalOnly, + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StandingRow { + pub key: RecordKey, + pub standing: Standing, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum HeldReason { + Unreadable, + UnknownKind, + // A pulled value waits for the person (0044's approval-required fields). + AwaitingApproval, + // This device is not approved yet, so it holds what it may not apply (0056, D8). + AwaitingDeviceApproval, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct HeldRow { + pub key: RecordKey, + pub reason: HeldReason, + // The change or deletion held. + pub record: PulledRecord, +} + +// A deletion pulled for a category that is off, applied once the category is read. +#[derive(Debug, Clone, PartialEq)] +pub struct DeferredRow { + pub key: RecordKey, + pub record: PulledRecord, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutboxRow { + pub scope: ScopeName, + pub idempotency_key: IdempotencyKey, + // SHA-256 of the body sent, so a rebuilt batch reuses the key only when it is the same request. + pub request_digest: [u8; 32], + pub created_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApprovalDecision { + // Waiting for the person, or not yet asked. + Waiting, + Approved, + // Kept as a device-local override. + Rejected { local: Value }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApprovalRow { + pub key: RecordKey, + pub field: String, + pub pulled: Value, + pub decision: ApprovalDecision, +} + +// A team record whose field both sides changed; None is a deletion. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConflictRow { + pub key: RecordKey, + pub base: Option, + pub mine: Option, + pub theirs: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LegacyMirrorRow { + pub item: String, + pub value: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyObjectRow { + pub scope: ScopeName, + pub kind: KindName, + pub record_id: String, + // As the server served them or as this device wrote them. + pub fields: String, + // In force: served by the server, or written and applied by this device. + pub applied: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyPinRow { + pub account: AccountId, + pub ik: Ed25519Public, + pub av: Version, + pub how: PinHow, + pub alert: bool, + // In the order replaced; never gone back to. + pub replaced: Vec, +} + +// Own-device pins: never taken from a certificate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyDevicePinRow { + pub key_device: KeyDeviceId, + pub dek: X25519Public, + pub dsk: Ed25519Public, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum KeyVersionState { + Ok, + // A catch-up or a restore leaves the device waiting. + Stopped, + // Nothing clears it. + Ended, +} + +impl KeyVersionState { + pub const fn as_str(self) -> &'static str { + match self { + Self::Ok => "ok", + Self::Stopped => "stopped", + Self::Ended => "ended", + } + } +} + +// One (account id, accepted IK) pair of a team row's holders, sorted by account then IK. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Holder { + pub account: AccountId, + pub ik: Ed25519Public, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyVersionRow { + pub scope: ScopeName, + pub purpose: KeyPurpose, + pub version: Version, + // SHA-256 of that version record's signed bytes. + pub record: [u8; 32], + // Empty for personal and history rows. + pub holders: Vec, + pub state: KeyVersionState, + // Why a `stopped` row waits, None otherwise (0062). Anchored with the row, so a file restore keeps it. + pub stopped_cause: Option, + // The epoch it ended in; None unless ended. + pub epoch: Option, +} + +impl KeyVersionRow { + // Stops the row for `cause`. A scope that meets two causes keeps the stricter: `catch_up`, then `restart_held`, + // then `restore_wait` (0062, 0064). A personal or history row only ever stops as `catch_up`. A row that ended + // stays ended. + pub fn stop(&mut self, cause: StoppedCause) { + if self.state == KeyVersionState::Ended { + return; + } + let cause = if self.purpose == KeyPurpose::Team { + cause + } else { + StoppedCause::CatchUp + }; + let kept = self.stopped_cause.map_or(cause, |held| held.max(cause)); + self.state = KeyVersionState::Stopped; + self.stopped_cause = Some(kept); + } + + // Clears a stop only by the event its cause and purpose allow (0062; 0056, Approving a device, step 7): a team's + // catch-up stop by re-confirmation, a team's restore stop once the server holds every version it waited for, a + // personal or history stop by an approval with the version signed under the current `av`. Anything else is + // refused and the row stays as it was. + pub fn clear_stop(&mut self, by: StopClear) -> Result<(), StopNotCleared> { + if self.state != KeyVersionState::Stopped { + return Err(StopNotCleared); + } + let allowed = match (self.purpose, self.stopped_cause) { + (KeyPurpose::Team, Some(StoppedCause::CatchUp)) => by == StopClear::Reconfirmed, + (KeyPurpose::Team, Some(StoppedCause::RestoreWait)) => by == StopClear::AwaitedVersionsBack, + (KeyPurpose::Team, Some(StoppedCause::RestartHeld)) => by == StopClear::AcceptedRestart, + (KeyPurpose::Personal | KeyPurpose::History, _) => by == StopClear::Approval, + (KeyPurpose::Team, None) => false, + }; + if !allowed { + return Err(StopNotCleared); + } + self.state = KeyVersionState::Ok; + self.stopped_cause = None; + Ok(()) + } + + // Ends the scope in `epoch`, which nothing clears; an ended row has no stop cause (0062). + pub fn end(&mut self, epoch: Option) { + self.state = KeyVersionState::Ended; + self.stopped_cause = None; + self.epoch = epoch; + } +} + +// What clears a stop (0062). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StopClear { + // An owner or admin the device counted as a holder rotated, and the device took the new version. + Reconfirmed, + // The server holds again every version the device waited for, with the same fields. + AwaitedVersionsBack, + // An approval brought the personal or history version signed under the current `av`. + Approval, + // The person compared the restarting owner's words and accepted the restart (0064). + AcceptedRestart, +} + +// The event does not clear this row's stop. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("this event does not clear the scope's stop")] +pub struct StopNotCleared; + +// Why a row stopped (0062, 0064), weakest first, so the stricter of two causes is the greater: a wait for a version a +// restore lost to come back, a team restart held until the person compares words, a catch-up the device could not +// verify. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum StoppedCause { + RestoreWait, + RestartHeld, + CatchUp, +} + +impl StoppedCause { + pub const fn as_str(self) -> &'static str { + match self { + Self::CatchUp => "catch_up", + Self::RestoreWait => "restore_wait", + Self::RestartHeld => "restart_held", + } + } + + // Only a catch-up stop is reported: no rotation clears the others (0062, 0064). + pub const fn is_reported(self) -> bool { + matches!(self, Self::CatchUp) + } + + pub fn parse(text: &str) -> Option { + [Self::CatchUp, Self::RestoreWait, Self::RestartHeld] + .into_iter() + .find(|cause| cause.as_str() == text) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyEnvelopeRow { + pub scope: ScopeName, + pub record_id: String, + pub kv: Version, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyComparisonRow { + pub session: RequestId, + pub role: ComparisonRole, + // The other side's key device id and keys, as this side's view fixed them; encoded by the approval flow. + pub peer: Vec, + pub view: Vec, + pub state: SessionState, + pub expires_at_us: i64, +} + +// A key flow that spans pushes and must survive a crash. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PendingFlow { + // The team rotations an account rotation to this `av` still has to write, with its review's choices. + AccountRotation { av: Version }, + Approval { request: RequestId }, + ResetProposal { reset: ResetId }, + // A stop report to withdraw, sent again after a restart until the server answers. + StopWithdrawal { team: TeamId }, +} + +impl PendingFlow { + pub fn key_text(self) -> String { + match self { + Self::AccountRotation { av } => format!("rotation/{av}"), + Self::Approval { request } => format!("approval/{}", request.to_wire()), + Self::ResetProposal { reset } => format!("reset/{}", reset.to_wire()), + Self::StopWithdrawal { team } => format!("withdraw/{}", team.to_wire()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct KeyPendingRow { + pub flow: PendingFlow, + // The flow's own encoding. + pub state: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeletedHistoryRow { + pub record_id: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Row { + Binding(BindingRow), + Scope(ScopeRow), + Store(StoreRow), + Base(BaseRow), + // A base a pull wrote before the store, in `pending_bases`; its columns are a base's. + PendingBase(BaseRow), + Standing(StandingRow), + Held(HeldRow), + Deferred(DeferredRow), + Outbox(OutboxRow), + Approval(ApprovalRow), + Conflict(ConflictRow), + LegacyMirror(LegacyMirrorRow), + KeyObject(KeyObjectRow), + KeyPin(KeyPinRow), + KeyDevicePin(KeyDevicePinRow), + KeyVersion(KeyVersionRow), + KeyEnvelope(KeyEnvelopeRow), + KeyComparison(KeyComparisonRow), + KeyPending(KeyPendingRow), + DeletedHistory(DeletedHistoryRow), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum RowKey { + Binding, + Scope(ScopeName), + Store(String), + Base(RecordKey), + PendingBase(RecordKey), + Standing(RecordKey), + Held(RecordKey), + Deferred(RecordKey), + Outbox(ScopeName), + Approval(RecordKey, String), + Conflict(RecordKey), + LegacyMirror(String), + KeyObject(ScopeName, KindName, String), + KeyPin(AccountId), + KeyDevicePin(KeyDeviceId), + KeyVersion(ScopeName, KeyPurpose), + KeyEnvelope(ScopeName, String), + KeyComparison(RequestId), + KeyPending(PendingFlow), + DeletedHistory(String), +} + +impl Row { + pub fn key(&self) -> RowKey { + match self { + Self::Binding(_) => RowKey::Binding, + Self::Scope(row) => RowKey::Scope(row.scope), + Self::Store(row) => RowKey::Store(row.store.clone()), + Self::Base(row) => RowKey::Base(row.key.clone()), + Self::PendingBase(row) => RowKey::PendingBase(row.key.clone()), + Self::Standing(row) => RowKey::Standing(row.key.clone()), + Self::Held(row) => RowKey::Held(row.key.clone()), + Self::Deferred(row) => RowKey::Deferred(row.key.clone()), + Self::Outbox(row) => RowKey::Outbox(row.scope), + Self::Approval(row) => RowKey::Approval(row.key.clone(), row.field.clone()), + Self::Conflict(row) => RowKey::Conflict(row.key.clone()), + Self::LegacyMirror(row) => RowKey::LegacyMirror(row.item.clone()), + Self::KeyObject(row) => RowKey::KeyObject(row.scope, row.kind.clone(), row.record_id.clone()), + Self::KeyPin(row) => RowKey::KeyPin(row.account), + Self::KeyDevicePin(row) => RowKey::KeyDevicePin(row.key_device), + Self::KeyVersion(row) => RowKey::KeyVersion(row.scope, row.purpose), + Self::KeyEnvelope(row) => RowKey::KeyEnvelope(row.scope, row.record_id.clone()), + Self::KeyComparison(row) => RowKey::KeyComparison(row.session), + Self::KeyPending(row) => RowKey::KeyPending(row.flow), + Self::DeletedHistory(row) => RowKey::DeletedHistory(row.record_id.clone()), + } + } +} + +// 0054's value encoding of a present column: one byte 1, then `LP` of its bytes. +fn column(out: &mut Vec, bytes: &[u8]) { + out.push(1); + let length = u32::try_from(bytes.len()).unwrap_or(u32::MAX); + out.extend_from_slice(&length.to_be_bytes()); + out.extend_from_slice(bytes); +} + +fn record_columns(out: &mut Vec, key: &RecordKey) { + column(out, key.scope.wire().as_bytes()); + column(out, key.kind.as_str().as_bytes()); + column(out, key.record_id.as_bytes()); +} + +impl RowKey { + pub fn table(&self) -> Table { + match self { + Self::Binding => Table::Binding, + Self::Scope(_) => Table::Scopes, + Self::Store(_) => Table::Stores, + Self::Base(_) => Table::Bases, + Self::PendingBase(_) => Table::PendingBases, + Self::Standing(_) => Table::Standing, + Self::Held(_) => Table::Held, + Self::Deferred(_) => Table::Deferred, + Self::Outbox(_) => Table::Outbox, + Self::Approval(..) => Table::Approvals, + Self::Conflict(_) => Table::Conflicts, + Self::LegacyMirror(_) => Table::LegacyMirror, + Self::KeyObject(..) => Table::KeyObjects, + Self::KeyPin(_) => Table::KeyPins, + Self::KeyDevicePin(_) => Table::KeyDevicePins, + Self::KeyVersion(..) => Table::KeyVersions, + Self::KeyEnvelope(..) => Table::KeyEnvelopes, + Self::KeyComparison(_) => Table::KeyComparisons, + Self::KeyPending(_) => Table::KeyPending, + Self::DeletedHistory(_) => Table::DeletedHistory, + } + } + + // The primary key's columns in 0054's value encoding, whose byte order orders a table's rows in its digest. + // Scopes are their wire text, ids of accounts, key devices and sessions their 16 bytes. + pub fn encoded(&self) -> Vec { + let mut out = Vec::new(); + match self { + Self::Binding => {} + Self::Scope(scope) | Self::Outbox(scope) => column(&mut out, scope.wire().as_bytes()), + Self::Store(text) | Self::LegacyMirror(text) | Self::DeletedHistory(text) => { + column(&mut out, text.as_bytes()); + } + Self::Base(key) + | Self::PendingBase(key) + | Self::Standing(key) + | Self::Held(key) + | Self::Deferred(key) + | Self::Conflict(key) => { + record_columns(&mut out, key); + } + Self::Approval(key, field) => { + record_columns(&mut out, key); + column(&mut out, field.as_bytes()); + } + Self::KeyObject(scope, kind, record_id) => { + column(&mut out, scope.wire().as_bytes()); + column(&mut out, kind.as_str().as_bytes()); + column(&mut out, record_id.as_bytes()); + } + Self::KeyPin(account) => column(&mut out, account.0.as_bytes()), + Self::KeyDevicePin(key_device) => column(&mut out, key_device.0.as_bytes()), + Self::KeyVersion(scope, purpose) => { + column(&mut out, scope.wire().as_bytes()); + column(&mut out, purpose.name().as_bytes()); + } + Self::KeyEnvelope(scope, record_id) => { + column(&mut out, scope.wire().as_bytes()); + column(&mut out, record_id.as_bytes()); + } + Self::KeyComparison(session) => column(&mut out, session.0.as_bytes()), + Self::KeyPending(flow) => column(&mut out, flow.key_text().as_bytes()), + } + out + } +} + +// The rows a scan reads: a whole table, or those whose leading key columns are one scope, or one scope and kind. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum RowRange { + Table(Table), + Scope(Table, ScopeName), + ScopeKind(Table, ScopeName, KindName), +} + +impl RowRange { + pub const fn table(&self) -> Table { + match self { + Self::Table(table) | Self::Scope(table, _) | Self::ScopeKind(table, ..) => *table, + } + } + + // A byte prefix of `RowKey::encoded` for every row in range. + pub fn encoded_prefix(&self) -> Vec { + let mut out = Vec::new(); + match self { + Self::Table(_) => {} + Self::Scope(_, scope) => column(&mut out, scope.wire().as_bytes()), + Self::ScopeKind(_, scope, kind) => { + column(&mut out, scope.wire().as_bytes()); + column(&mut out, kind.as_str().as_bytes()); + } + } + out + } + + pub fn contains(&self, key: &RowKey) -> bool { + key.table() == self.table() && key.encoded().starts_with(&self.encoded_prefix()) + } +} + +#[cfg(test)] +mod tests { + use tablepro_records::Kind; + + use super::*; + + fn base(scope: ScopeName, kind: Kind, id: &str) -> RowKey { + RowKey::Base(RecordKey::new(scope, kind, id)) + } + + #[test] + fn a_scope_range_holds_its_scope_s_rows_and_no_other() { + let range = RowRange::Scope(Table::Bases, ScopeName::Personal); + + assert!(range.contains(&base(ScopeName::Personal, Kind::Connection, "A"))); + assert!(!range.contains(&base(ScopeName::History, Kind::HistoryEntry, "A"))); + assert!(!range.contains(&RowKey::Held(RecordKey::new( + ScopeName::Personal, + Kind::Connection, + "A" + )))); + } + + #[test] + fn a_kind_range_is_not_fooled_by_a_kind_that_starts_another() { + let range = RowRange::ScopeKind(Table::Bases, ScopeName::Personal, KindName::of(Kind::SavedQuery)); + + assert!(range.contains(&base(ScopeName::Personal, Kind::SavedQuery, "A"))); + assert!(!range.contains(&base(ScopeName::Personal, Kind::SavedQueryFolder, "A"))); + } + + #[test] + fn every_table_is_a_sync_or_a_key_table_in_digest_order() { + let all: Vec = Table::SYNC.into_iter().chain(Table::KEY).collect(); + let mut sorted = all.clone(); + sorted.sort(); + + assert_eq!(all, sorted); + assert!(Table::SYNC.iter().all(|table| !table.is_key_table())); + assert!(Table::KEY.iter().all(|table| table.is_key_table())); + } + + fn team_row(purpose: KeyPurpose) -> KeyVersionRow { + KeyVersionRow { + scope: ScopeName::Personal, + purpose, + version: Version::new(3).unwrap(), + record: [0; 32], + holders: Vec::new(), + state: KeyVersionState::Ok, + stopped_cause: None, + epoch: None, + } + } + + #[test] + fn a_scope_that_meets_both_causes_keeps_catch_up() { + let mut waiting = team_row(KeyPurpose::Team); + waiting.stop(StoppedCause::RestoreWait); + let restore_only = waiting.stopped_cause; + waiting.stop(StoppedCause::CatchUp); + let mut caught = team_row(KeyPurpose::Team); + caught.stop(StoppedCause::CatchUp); + caught.stop(StoppedCause::RestoreWait); + + assert_eq!(restore_only, Some(StoppedCause::RestoreWait)); + assert_eq!(waiting.stopped_cause, Some(StoppedCause::CatchUp)); + assert_eq!(caught.stopped_cause, Some(StoppedCause::CatchUp)); + assert_eq!(caught.state, KeyVersionState::Stopped); + } + + #[test] + fn a_personal_or_history_row_stops_only_as_catch_up_and_an_ended_row_stays_ended() { + let mut history = team_row(KeyPurpose::History); + history.stop(StoppedCause::RestoreWait); + let history_cause = history.stopped_cause; + let mut ended = team_row(KeyPurpose::Team); + ended.end(Some(EpochId(uuid::Uuid::nil()))); + ended.stop(StoppedCause::CatchUp); + + assert_eq!(history_cause, Some(StoppedCause::CatchUp)); + assert_eq!(history.clear_stop(StopClear::Reconfirmed), Err(StopNotCleared)); + assert_eq!(history.clear_stop(StopClear::Approval), Ok(())); + assert_eq!((history.state, history.stopped_cause), (KeyVersionState::Ok, None)); + assert_eq!((ended.state, ended.stopped_cause), (KeyVersionState::Ended, None)); + assert_eq!(StoppedCause::parse("restore_wait"), Some(StoppedCause::RestoreWait)); + assert_eq!(StoppedCause::CatchUp.as_str(), "catch_up"); + } + + #[test] + fn a_team_stop_clears_only_by_the_event_its_cause_allows() { + let mut caught = team_row(KeyPurpose::Team); + caught.stop(StoppedCause::CatchUp); + let mut waiting = team_row(KeyPurpose::Team); + waiting.stop(StoppedCause::RestoreWait); + + let caught_by_versions = caught.clear_stop(StopClear::AwaitedVersionsBack); + let caught_by_approval = caught.clear_stop(StopClear::Approval); + let waiting_by_reconfirm = waiting.clear_stop(StopClear::Reconfirmed); + + assert_eq!(caught_by_versions, Err(StopNotCleared)); + assert_eq!(caught_by_approval, Err(StopNotCleared)); + assert_eq!(caught.stopped_cause, Some(StoppedCause::CatchUp)); + assert_eq!(waiting_by_reconfirm, Err(StopNotCleared)); + assert_eq!(caught.clear_stop(StopClear::Reconfirmed), Ok(())); + assert_eq!(waiting.clear_stop(StopClear::AwaitedVersionsBack), Ok(())); + assert_eq!( + team_row(KeyPurpose::Team).clear_stop(StopClear::Reconfirmed), + Err(StopNotCleared) + ); + } + + #[test] + fn a_held_restart_clears_only_once_the_person_accepts_it_and_a_catch_up_outranks_it() { + let mut held = team_row(KeyPurpose::Team); + held.stop(StoppedCause::RestoreWait); + held.stop(StoppedCause::RestartHeld); + let over_restore = held.stopped_cause; + let mut caught = team_row(KeyPurpose::Team); + caught.stop(StoppedCause::RestartHeld); + caught.stop(StoppedCause::CatchUp); + + assert_eq!(over_restore, Some(StoppedCause::RestartHeld)); + assert_eq!(held.clear_stop(StopClear::Reconfirmed), Err(StopNotCleared)); + assert_eq!(held.clear_stop(StopClear::AwaitedVersionsBack), Err(StopNotCleared)); + assert_eq!(held.clear_stop(StopClear::AcceptedRestart), Ok(())); + assert_eq!(caught.stopped_cause, Some(StoppedCause::CatchUp)); + assert!(!StoppedCause::RestartHeld.is_reported()); + assert_eq!(StoppedCause::parse("restart_held"), Some(StoppedCause::RestartHeld)); + } + + #[test] + fn ending_a_stopped_row_drops_its_cause() { + let mut waiting = team_row(KeyPurpose::Team); + waiting.stop(StoppedCause::RestoreWait); + let epoch = EpochId(uuid::Uuid::from_u128(4)); + + waiting.end(Some(epoch)); + + assert_eq!( + (waiting.state, waiting.stopped_cause, waiting.epoch), + (KeyVersionState::Ended, None, Some(epoch)) + ); + assert_eq!(waiting.clear_stop(StopClear::AwaitedVersionsBack), Err(StopNotCleared)); + } + + #[test] + fn a_personal_row_asked_to_wait_on_a_restore_records_catch_up() { + let mut personal = team_row(KeyPurpose::Personal); + + personal.stop(StoppedCause::RestoreWait); + + assert_eq!(personal.stopped_cause, Some(StoppedCause::CatchUp)); + } + + #[test] + fn the_key_of_a_row_is_its_primary_key_columns() { + let key = RecordKey::new(ScopeName::Personal, Kind::Connection, "A"); + + let encoded = RowKey::Base(key).encoded(); + + assert_eq!( + encoded, + [ + &[1, 0, 0, 0, 8][..], + b"personal", + &[1, 0, 0, 0, 10], + b"connection", + &[1, 0, 0, 0, 1], + b"A" + ] + .concat() + ); + } +} diff --git a/core/crates/sync/src/api/transport.rs b/core/crates/sync/src/api/transport.rs new file mode 100644 index 0000000000..028c072511 --- /dev/null +++ b/core/crates/sync/src/api/transport.rs @@ -0,0 +1,402 @@ +use std::fmt; + +use async_trait::async_trait; +use serde_json::Value; +use tablepro_keys::encoding::{TeamId, Version}; +use tablepro_keys::keys::Ed25519Seed; + +use super::ids::{ChangeTag, Cursor, DeviceRowId, EpochId, IdempotencyKey, KindName, ScopeName}; +use super::scopes::ScopesAnswer; + +// What both providers do under the engine (0054, Transports): pull a page from a cursor and push a batch, with an +// answer per change. The service transport speaks `/v2/sync` over the generated client; the CloudKit one maps these to +// `CloudKitTransport` calls. +#[async_trait] +pub trait Transport: Send + Sync { + async fn pull(&self, request: PullRequest) -> Result; + + async fn push(&self, batch: PushBatch) -> Result; +} + +// The service's calls beyond pull and push (0051, Protocol; Keys on the wire; Teams; Lifecycle and audit). +#[async_trait] +pub trait ServiceTransport: Transport { + // `GET /v2/sync/scopes`, with `If-None-Match` from the last body's ETag. + async fn scopes(&self, if_none_match: Option, proof: Proof) -> Result; + + // Sign Out's `DELETE /v2/sync/key-device`: no body, no idempotency key, a fresh proof on every try. 204 whatever + // the key changed. + async fn revoke_key_device(&self, proof: DpopKey) -> Result<(), TransportError>; + + // `PUT /v2/sync/scopes/{team}/stopped` with the version the device stopped at. + async fn report_stopped(&self, team: TeamId, version: Version, proof: DpopKey) -> Result<(), TransportError>; + + // `DELETE /v2/sync/scopes/{team}/stopped`. + async fn withdraw_stopped(&self, team: TeamId, proof: DpopKey) -> Result<(), TransportError>; + + // The apps' removal of a device row of an account with keys: `DELETE /v2/devices/{id}` with a proof from an + // approved device, which needs a fresh step-up (0051, Removals). + async fn remove_device_row(&self, device: DeviceRowId, proof: DpopKey) -> Result<(), TransportError>; +} + +// The device signing key a DPoP proof is signed with (0051, Whose key the proof carries). Which DSK that is depends on +// the call, so the caller names it. +#[derive(Clone)] +pub struct DpopKey(pub std::sync::Arc); + +impl fmt::Debug for DpopKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("DpopKey(redacted)") + } +} + +impl PartialEq for DpopKey { + fn eq(&self, other: &Self) -> bool { + self.0.expose() == other.0.expose() + } +} + +// A team plaintext read or write carries no proof; every personal or history call and every key-object or envelope +// write does (0051, DPoP). +#[derive(Debug, Clone, PartialEq, Default)] +pub enum Proof { + #[default] + None, + Dpop(DpopKey), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct PullRequest { + pub scope: ScopeName, + // None takes a snapshot. + pub cursor: Option, + // At most 500 on the service; None takes the server's default. + pub limit: Option, + pub proof: Proof, +} + +// A page of a pull. On the service a page with no records is caught up; on CloudKit `more` false is. +#[derive(Debug, Clone, PartialEq)] +pub struct PulledPage { + pub records: Vec, + // Where the next page starts. None on a scope with no records yet (0051, Scopes and records). On the history + // scope's snapshot it pages older entries. + pub cursor: Option, + // The history scope's snapshot only: the changes after its mark (0051, Pull). + pub changes_cursor: Option, + pub caught_up: bool, + // CloudKit names it changed but could not return; the engine fetches or holds them. + pub unread: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct PulledRecord { + pub kind: KindName, + pub record_id: String, + pub tag: ChangeTag, + // None on a tombstone, whose fields `/v2/sync` never sends. + pub fields: Option, + // The fields' JSON text exactly as served. A key object is parsed from it, so a duplicate member is refused + // rather than collapsed (0051, Key object bodies). None on CloudKit and on a tombstone. + pub fields_json: Option, + pub deleted: Option, + // The service's columns; None on CloudKit. + pub service: Option, +} + +// 0051, Pull: each record's server columns. Times are microseconds since the Unix epoch in UTC. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServiceMeta { + pub version: u64, + pub revision: u64, + pub epoch: EpochId, + pub updated_at_us: i64, + pub taken_at_us: i64, + // A pending `key.reset`'s. + pub held_until_us: Option, + // A `key.request`'s. + pub expires_at_us: Option, + pub updated_by: Option, + pub updated_device: Option, + // A team record's writer, under the facade's rule for the caller's role. + pub updated_by_name: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum DeletedReason { + // A client deleted it; a device deletes its copy under the conflict rules. + User, + // A policy job tombstoned it; a device keeps its copy (0051, Tombstones). + Policy, +} + +impl DeletedReason { + pub const fn as_str(self) -> &'static str { + match self { + Self::User => "user", + Self::Policy => "policy", + } + } +} + +// One push: every change judged on its own, except a change set, which applies whole or not at all (0051, Push). +#[derive(Debug, Clone, PartialEq)] +pub struct PushBatch { + pub scope: ScopeName, + // The epoch the device holds; the service refuses another one whole with `epoch_changed`. None on CloudKit. + pub epoch: Option, + // A UUIDv4 per batch on the service, kept in the outbox until answered. None on CloudKit. + pub idempotency_key: Option, + pub changes: Vec, + pub proof: Proof, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Change { + pub kind: KindName, + pub record_id: String, + // None creates the record. + pub base: Option, + pub op: ChangeOp, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ChangeOp { + // `patch` is the RFC 7396 merge patch from the base to `fields`, which the service applies; CloudKit sets the + // top-level fields the patch names from `fields`. A create's patch is its fields. + Write { fields: Value, patch: Value }, + Delete, +} + +// One answer per change, in the order sent. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PushAnswer { + pub outcomes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChangeOutcome { + Applied { + // None when the change wrote nothing and the server holds no such record, as a delete of an absent one. + tag: Option, + // The service's new version and revision. + service: Option, + }, + // The stored record, or None when the server has no such record. The service names its tag and no fields, so the + // device pulls; CloudKit's `serverRecordChanged` carries the copy, or none, when the engine fetches it by name. + Conflict { + stored: Option, + }, + // CloudKit's `unknownItem`: a save rebuilt from system fields met no record. + Gone, + Rejected { + code: RejectedCode, + }, + // A CloudKit per-record failure the engine retries. + Failed { + code: i64, + retry_after_ms: Option, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AppliedStamp { + pub version: u64, + pub revision: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredCopy { + pub tag: ChangeTag, + pub tombstone: bool, + pub service: Option, + // CloudKit's server copy, mapped to wire fields. + pub fields: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StoredStamp { + pub version: u64, + pub revision: u64, + pub epoch: EpochId, +} + +// 0051's rejected codes, one per change. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum RejectedCode { + BadKind, + BadRecordId, + BadValue, + SecretKey, + TooLarge, + KindNotInScope, + Role, + Policy, + CreateOnly, + WriterBound, + RequestPending, + RequestClosed, + ResetHeld, + KeyDependency, + ChangeSet, + TeamFull, + IdCaseCollision, + BadStatement, + KeyVersionStale, + KeyVersionUnknown, + RotationDue, + QuotaExceeded, + // A code a newer server sends that this build does not know. + Other(String), +} + +const REJECTED: [(RejectedCode, &str); 22] = [ + (RejectedCode::BadKind, "bad_kind"), + (RejectedCode::BadRecordId, "bad_record_id"), + (RejectedCode::BadValue, "bad_value"), + (RejectedCode::SecretKey, "secret_key"), + (RejectedCode::TooLarge, "too_large"), + (RejectedCode::KindNotInScope, "kind_not_in_scope"), + (RejectedCode::Role, "role"), + (RejectedCode::Policy, "policy"), + (RejectedCode::CreateOnly, "create_only"), + (RejectedCode::WriterBound, "writer_bound"), + (RejectedCode::RequestPending, "request_pending"), + (RejectedCode::RequestClosed, "request_closed"), + (RejectedCode::ResetHeld, "reset_held"), + (RejectedCode::KeyDependency, "key_dependency"), + (RejectedCode::ChangeSet, "change_set"), + (RejectedCode::TeamFull, "team_full"), + (RejectedCode::IdCaseCollision, "id_case_collision"), + (RejectedCode::BadStatement, "bad_statement"), + (RejectedCode::KeyVersionStale, "key_version_stale"), + (RejectedCode::KeyVersionUnknown, "key_version_unknown"), + (RejectedCode::RotationDue, "rotation_due"), + (RejectedCode::QuotaExceeded, "quota_exceeded"), +]; + +impl RejectedCode { + pub fn as_str(&self) -> &str { + match self { + Self::Other(code) => code, + known => REJECTED + .iter() + .find(|(code, _)| code == known) + .map_or("unknown", |(_, name)| name), + } + } + + pub fn parse(text: &str) -> Self { + REJECTED + .iter() + .find(|(_, name)| *name == text) + .map_or_else(|| Self::Other(text.to_owned()), |(code, _)| code.clone()) + } +} + +// RFC 9470's challenge: `insufficient_user_authentication` with the methods and the age the call needs. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct StepUpChallenge { + pub acr_values: Vec, + pub max_age_secs: u64, +} + +// A whole call refused or not made (0051, Whole-request refusals), and the transport's own failures. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TransportError { + // The server asked for its nonce and the transport's retry with it was refused again. + #[error("the server wants its DPoP nonce")] + UseDpopNonce, + #[error("the account lacks the feature")] + FeatureRequired, + #[error("the account has no seat in the team")] + SeatRequired, + #[error("the license is past grace")] + LicenseExpired, + // The device locks: it stops syncing, keeps its keys and cancels nothing (0056). + #[error("this device's row was removed")] + DeviceRemoved, + #[error("the call needs a fresh step-up")] + StepUpRequired(StepUpChallenge), + #[error("this device is not approved for the call")] + DeviceNotApproved, + #[error("the sign-in came from a license key, not an interactive sign-in")] + InteractiveSignInRequired, + #[error("the scope is not reachable")] + NotFound, + #[error("the same idempotency key is still running")] + IdempotencyInProgress, + #[error("the request was malformed")] + ValidationFailed, + // Take a snapshot, and refill when the epoch changed (0051, Pull). + #[error("the cursor expired")] + CursorExpired, + #[error("the server is in another epoch")] + EpochChanged, + #[error("the idempotency key was used with another body")] + IdempotencyMismatch, + #[error("rate limited")] + RateLimited { retry_after_ms: Option }, + // 503: backed off as a 429 is, honoring `Retry-After`. + #[error("the server cannot run its restore check")] + RestoreCheckUnavailable { retry_after_ms: Option }, + // `GET /v2/sync/scopes` answered 404: the server has no `/v2/sync` (0051, Releases). + #[error("the server is too old for TablePro Sync")] + ServerTooOld, + #[error("not signed in")] + SignedOut, + #[error("the network failed: {detail}")] + Network { detail: String }, + // Another status or problem code, as the server sent it. + #[error("the server answered {status} {code}")] + Server { + status: u16, + code: String, + retry_after_ms: Option, + }, +} + +impl TransportError { + pub const fn code(&self) -> &'static str { + match self { + Self::UseDpopNonce => "sync.use_dpop_nonce", + Self::FeatureRequired => "sync.feature_required", + Self::SeatRequired => "sync.seat_required", + Self::LicenseExpired => "sync.license_expired", + Self::DeviceRemoved => "sync.device_removed", + Self::StepUpRequired(_) => "sync.step_up_required", + Self::DeviceNotApproved => "sync.device_not_approved", + Self::InteractiveSignInRequired => "sync.interactive_sign_in_required", + Self::NotFound => "sync.not_found", + Self::IdempotencyInProgress => "sync.idempotency_in_progress", + Self::ValidationFailed => "sync.validation_failed", + Self::CursorExpired => "sync.cursor_expired", + Self::EpochChanged => "sync.epoch_changed", + Self::IdempotencyMismatch => "sync.idempotency_mismatch", + Self::RateLimited { .. } => "sync.rate_limited", + Self::RestoreCheckUnavailable { .. } => "sync.restore_check_unavailable", + Self::ServerTooOld => "sync.server_too_old", + Self::SignedOut => "sync.signed_out", + Self::Network { .. } => "sync.network", + Self::Server { .. } => "sync.server", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_rejected_code_reads_back_as_itself() { + for (code, name) in REJECTED { + assert_eq!(code.as_str(), name); + assert_eq!(RejectedCode::parse(name), code); + } + assert_eq!( + RejectedCode::parse("new_code"), + RejectedCode::Other("new_code".to_owned()) + ); + assert_eq!(RejectedCode::Other("new_code".to_owned()).as_str(), "new_code"); + } +} diff --git a/core/crates/sync/src/lib.rs b/core/crates/sync/src/lib.rs new file mode 100644 index 0000000000..27ab5cf6c9 --- /dev/null +++ b/core/crates/sync/src/lib.rs @@ -0,0 +1,7 @@ +// One sync engine for TablePro Sync and iCloud (core ADR 0054), with the end-to-end flows of 0056. `api` holds the +// contracts every part builds against: the transports, the state file, the device store, the record adapters, the +// key flows and the control surface the FFI wraps. + +pub mod api; + +pub use api::SyncError; diff --git a/core/crates/sync/testing/Cargo.toml b/core/crates/sync/testing/Cargo.toml new file mode 100644 index 0000000000..a076721854 --- /dev/null +++ b/core/crates/sync/testing/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "tablepro-sync-testing" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +# Dev-only: the fakes every sync lane tests against (core/ARCHITECTURE.md, Dependency graph). +[dependencies] +tablepro-keys.workspace = true +tablepro-records.workspace = true +tablepro-sync.workspace = true +async-trait.workspace = true +base64.workspace = true +secrecy.workspace = true +serde_json.workspace = true +sha2.workspace = true +uuid.workspace = true +zeroize.workspace = true + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt"] } + +[lints] +workspace = true diff --git a/core/crates/sync/testing/src/cloudkit/mod.rs b/core/crates/sync/testing/src/cloudkit/mod.rs new file mode 100644 index 0000000000..df25d8e3e7 --- /dev/null +++ b/core/crates/sync/testing/src/cloudkit/mod.rs @@ -0,0 +1,429 @@ +// A CloudKit private database as 0054 describes it, one zone per iCloud account: saves guarded by system fields as +// `.ifServerRecordUnchanged` does, `serverRecordChanged` with the server's copy, `unknownItem`, deletions without a +// change tag, change tokens that page and expire, `limitExceeded`, a zone the person removed, and an account switch +// that saves nothing to either account. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use async_trait::async_trait; +use tablepro_sync::api::cloudkit::{ + CloudKitAccount, CloudKitChanges, CloudKitDeletion, CloudKitFailure, CloudKitFetched, CloudKitField, + CloudKitOutcome, CloudKitRecord, CloudKitTransport, CloudKitValue, +}; +use uuid::Uuid; + +#[derive(Debug, Clone)] +struct Stored { + record_type: String, + created_ms: i64, + fields: BTreeMap, + system_fields: Vec, + change: u64, +} + +#[derive(Debug, Default)] +struct Zone { + records: BTreeMap, + deletions: Vec<(u64, CloudKitDeletion)>, + next_change: u64, + // Each token names the generation it was issued in; expiring tokens starts a new one. + generation: u64, +} + +#[derive(Debug)] +struct State { + signed_in: Option, + zones: HashMap, + removed_by_user: HashMap, + fail_next: Vec, + // The account the device switches to while the next call runs. + switch_mid_call: Option>, + failing_records: HashMap, + page_size: usize, + max_batch: usize, + max_batch_bytes: usize, +} + +#[derive(Debug)] +pub struct FakeCloudKit { + state: Mutex, +} + +impl FakeCloudKit { + pub fn signed_in(user_record_name: &str) -> Self { + Self { + state: Mutex::new(State { + signed_in: Some(user_record_name.to_owned()), + zones: HashMap::new(), + removed_by_user: HashMap::new(), + fail_next: Vec::new(), + switch_mid_call: None, + failing_records: HashMap::new(), + page_size: 200, + max_batch: 400, + max_batch_bytes: 2 << 20, + }), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + // `CKAccountChanged`: another user, or none. + pub fn switch_account(&self, user_record_name: Option<&str>) { + self.lock().signed_in = user_record_name.map(str::to_owned); + } + + // The account changes after the next call's first check and before CloudKit receives it. + pub fn switch_account_during_next_call(&self, user_record_name: Option<&str>) { + self.lock().switch_mid_call = Some(user_record_name.map(str::to_owned)); + } + + pub fn fail_next(&self, failure: CloudKitFailure) { + self.lock().fail_next.push(failure); + } + + // The next save or deletion of `name` fails with `code`, once. + pub fn fail_record(&self, name: &str, code: i64) { + self.lock().failing_records.insert(name.to_owned(), code); + } + + // Every token the zone gave so far now answers `TokenExpired`. + pub fn expire_tokens(&self, account: &str) { + if let Some(zone) = self.lock().zones.get_mut(account) { + zone.generation += 1; + } + } + + // The person deleted the zone in Settings: calls answer `ZoneDeletedByUser` until it is made again. + pub fn remove_zone_by_user(&self, account: &str) { + let mut state = self.lock(); + state.zones.remove(account); + state.removed_by_user.insert(account.to_owned(), true); + } + + pub fn set_limits(&self, page_size: usize, max_batch: usize, max_batch_bytes: usize) { + let mut state = self.lock(); + state.page_size = page_size.max(1); + state.max_batch = max_batch; + state.max_batch_bytes = max_batch_bytes; + } + + // Another device's save, outside this device's calls. + pub fn save_elsewhere(&self, account: &str, record_type: &str, name: &str, fields: Vec) { + let mut state = self.lock(); + let zone = state.zones.entry(account.to_owned()).or_default(); + let mut stored = zone.records.get(name).cloned().unwrap_or_else(|| Stored { + record_type: record_type.to_owned(), + created_ms: zone_now(zone), + fields: BTreeMap::new(), + system_fields: Vec::new(), + change: 0, + }); + set_fields(&mut stored.fields, fields); + zone.next_change += 1; + stored.change = zone.next_change; + stored.system_fields = new_system_fields(); + zone.records.insert(name.to_owned(), stored); + } + + pub fn delete_elsewhere(&self, account: &str, name: &str) { + let mut state = self.lock(); + if let Some(zone) = state.zones.get_mut(account) { + delete(zone, name); + } + } + + pub fn record(&self, account: &str, name: &str) -> Option { + self.lock() + .zones + .get(account) + .and_then(|zone| zone.records.get(name).map(|stored| record(name, stored))) + } + + pub fn record_names(&self, account: &str) -> Vec { + self.lock() + .zones + .get(account) + .map_or_else(Vec::new, |zone| zone.records.keys().cloned().collect()) + } + + // The checks before an operation; the second element is the check after it. + fn begin(&self, account: &str) -> Result, CloudKitFailure> { + let mut state = self.lock(); + if !state.fail_next.is_empty() { + return Err(state.fail_next.remove(0)); + } + let signed_in = state.signed_in.clone().ok_or(CloudKitFailure::NoAccount)?; + if signed_in != account { + return Err(CloudKitFailure::AccountChanged); + } + if let Some(next) = state.switch_mid_call.take() { + state.signed_in = next; + return Err(CloudKitFailure::AccountChanged); + } + Ok(state) + } +} + +// A creation date that grows with each change of the zone, so a record made again reads as newer. +fn zone_now(zone: &Zone) -> i64 { + 1_767_225_600_000 + i64::try_from(zone.next_change).unwrap_or(i64::MAX - 1_767_225_600_000) +} + +fn new_system_fields() -> Vec { + Uuid::new_v4().as_bytes().to_vec() +} + +fn set_fields(target: &mut BTreeMap, fields: Vec) { + for field in fields { + match field.value { + Some(value) => { + target.insert(field.name, value); + } + None => { + target.remove(&field.name); + } + } + } +} + +fn record(name: &str, stored: &Stored) -> CloudKitRecord { + CloudKitRecord { + record_type: stored.record_type.clone(), + name: name.to_owned(), + system_fields: Some(stored.system_fields.clone()), + created_ms: Some(stored.created_ms), + fields: stored + .fields + .iter() + .map(|(name, value)| CloudKitField { + name: name.clone(), + value: Some(value.clone()), + }) + .collect(), + } +} + +fn delete(zone: &mut Zone, name: &str) { + if let Some(stored) = zone.records.remove(name) { + zone.next_change += 1; + let deletion = CloudKitDeletion { + name: name.to_owned(), + record_type: stored.record_type, + }; + zone.deletions.push((zone.next_change, deletion)); + } +} + +fn value_bytes(value: &CloudKitValue) -> usize { + match value { + CloudKitValue::Text(text) => text.len(), + CloudKitValue::Int64(_) | CloudKitValue::Double(_) | CloudKitValue::Timestamp(_) => 8, + CloudKitValue::Bytes(bytes) => bytes.len(), + CloudKitValue::TextList(list) => list.iter().map(String::len).sum(), + } +} + +fn token(generation: u64, change: u64) -> Vec { + [generation.to_be_bytes(), change.to_be_bytes()].concat() +} + +// The change a token resumes after, when it is of the zone's current generation. +fn read_token(token: &[u8], generation: u64) -> Result { + let bytes: [u8; 16] = token.try_into().map_err(|_| CloudKitFailure::TokenExpired)?; + let (issued, change) = bytes.split_at(8); + let issued = u64::from_be_bytes(issued.try_into().map_err(|_| CloudKitFailure::TokenExpired)?); + if issued != generation { + return Err(CloudKitFailure::TokenExpired); + } + Ok(u64::from_be_bytes( + change.try_into().map_err(|_| CloudKitFailure::TokenExpired)?, + )) +} + +fn zone<'a>(state: &'a mut State, account: &str) -> Result<&'a mut Zone, CloudKitFailure> { + if state.zones.contains_key(account) { + return state.zones.get_mut(account).ok_or(CloudKitFailure::ZoneNotFound); + } + if state.removed_by_user.get(account).copied().unwrap_or(false) { + Err(CloudKitFailure::ZoneDeletedByUser) + } else { + Err(CloudKitFailure::ZoneNotFound) + } +} + +fn save(zone: &mut Zone, save: CloudKitRecord) -> CloudKitOutcome { + let current = zone.records.get(&save.name).cloned(); + match (&save.system_fields, current) { + (None, Some(current)) | (Some(_), Some(current)) + if save.system_fields.as_ref() != Some(¤t.system_fields) => + { + CloudKitOutcome::ServerChanged { + server: Some(record(&save.name, ¤t)), + name: save.name, + } + } + (Some(_), None) => CloudKitOutcome::UnknownItem { name: save.name }, + (_, current) => { + let created_ms = zone_now(zone); + let mut stored = current.unwrap_or_else(|| Stored { + record_type: save.record_type.clone(), + created_ms, + fields: BTreeMap::new(), + system_fields: Vec::new(), + change: 0, + }); + set_fields(&mut stored.fields, save.fields); + zone.next_change += 1; + stored.change = zone.next_change; + stored.system_fields = new_system_fields(); + let system_fields = stored.system_fields.clone(); + zone.records.insert(save.name.clone(), stored); + CloudKitOutcome::Saved { + name: save.name, + system_fields, + } + } + } +} + +#[async_trait] +impl CloudKitTransport for FakeCloudKit { + async fn account_status(&self) -> Result { + let mut state = self.lock(); + if !state.fail_next.is_empty() { + return Err(state.fail_next.remove(0)); + } + let user_record_name = state.signed_in.clone().ok_or(CloudKitFailure::NoAccount)?; + Ok(CloudKitAccount { user_record_name }) + } + + async fn ensure_zone(&self, account: String) -> Result<(), CloudKitFailure> { + let mut state = self.begin(&account)?; + state.removed_by_user.remove(&account); + state.zones.entry(account).or_default(); + Ok(()) + } + + async fn delete_zone(&self, account: String) -> Result<(), CloudKitFailure> { + let mut state = self.begin(&account)?; + state.zones.remove(&account); + Ok(()) + } + + async fn fetch_changes(&self, account: String, token: Option>) -> Result { + let mut state = self.begin(&account)?; + let page_size = state.page_size; + let zone = zone(&mut state, &account)?; + let since = token + .as_deref() + .map(|token| read_token(token, zone.generation)) + .transpose()? + .unwrap_or(0); + // Each change at most once, in the order the zone took them. + let mut events: Vec<(u64, Option<&str>, Option<&CloudKitDeletion>)> = zone + .records + .iter() + .filter(|(_, stored)| stored.change > since) + .map(|(name, stored)| (stored.change, Some(name.as_str()), None)) + .collect(); + if token.is_some() { + events.extend( + zone.deletions + .iter() + .filter(|(change, deletion)| *change > since && !zone.records.contains_key(&deletion.name)) + .map(|(change, deletion)| (*change, None, Some(deletion))), + ); + } + events.sort_by_key(|(change, ..)| *change); + let more = events.len() > page_size; + events.truncate(page_size); + let last = events + .last() + .map_or(zone.next_change.max(since), |(change, ..)| *change); + let changed = events + .iter() + .filter_map(|(_, name, _)| name.and_then(|name| zone.records.get(name).map(|stored| record(name, stored)))) + .collect(); + let deleted = events + .iter() + .filter_map(|(.., deletion)| (*deletion).cloned()) + .collect(); + Ok(CloudKitChanges { + changed, + deleted, + unfetched: Vec::new(), + token: self::token(zone.generation, if more { last } else { zone.next_change.max(since) }), + more, + }) + } + + async fn fetch_records( + &self, + account: String, + names: Vec, + ) -> Result, CloudKitFailure> { + let mut state = self.begin(&account)?; + let zone = zone(&mut state, &account)?; + Ok(names + .into_iter() + .map(|name| match zone.records.get(&name) { + Some(stored) => CloudKitFetched::Found { + record: record(&name, stored), + }, + None => CloudKitFetched::Missing { name }, + }) + .collect()) + } + + async fn modify( + &self, + account: String, + saves: Vec, + deletes: Vec, + ) -> Result, CloudKitFailure> { + let mut state = self.begin(&account)?; + let bytes: usize = saves + .iter() + .flat_map(|save| save.fields.iter()) + .map(|field| field.name.len() + field.value.as_ref().map_or(0, value_bytes)) + .sum(); + if saves.len() + deletes.len() > state.max_batch || bytes > state.max_batch_bytes { + return Err(CloudKitFailure::LimitExceeded); + } + let mut failing = std::mem::take(&mut state.failing_records); + let zone = zone(&mut state, &account)?; + let mut outcomes = Vec::with_capacity(saves.len() + deletes.len()); + for record in saves { + outcomes.push(match failing.remove(&record.name) { + Some(code) => CloudKitOutcome::Failed { + name: record.name, + code, + retry_after_ms: None, + }, + None => save(zone, record), + }); + } + for name in deletes { + outcomes.push(match failing.remove(&name) { + Some(code) => CloudKitOutcome::Failed { + name, + code, + retry_after_ms: None, + }, + None => { + delete(zone, &name); + CloudKitOutcome::Deleted { name } + } + }); + } + state.failing_records = failing; + Ok(outcomes) + } +} + +#[cfg(test)] +mod tests; diff --git a/core/crates/sync/testing/src/cloudkit/tests.rs b/core/crates/sync/testing/src/cloudkit/tests.rs new file mode 100644 index 0000000000..3d55efa121 --- /dev/null +++ b/core/crates/sync/testing/src/cloudkit/tests.rs @@ -0,0 +1,262 @@ +use tablepro_sync::api::cloudkit::{ + CloudKitFailure, CloudKitFetched, CloudKitField, CloudKitOutcome, CloudKitRecord, CloudKitTransport, CloudKitValue, +}; + +use super::FakeCloudKit; + +const USER: &str = "_a1b2"; + +fn connection(name: &str, system_fields: Option>, title: &str) -> CloudKitRecord { + CloudKitRecord { + record_type: "Connection".to_owned(), + name: name.to_owned(), + system_fields, + created_ms: None, + fields: vec![CloudKitField { + name: "name".to_owned(), + value: Some(CloudKitValue::Text(title.to_owned())), + }], + } +} + +async fn zone() -> FakeCloudKit { + let cloud = FakeCloudKit::signed_in(USER); + cloud.ensure_zone(USER.to_owned()).await.unwrap(); + cloud +} + +async fn saved(cloud: &FakeCloudKit, record: CloudKitRecord) -> Vec { + match cloud + .modify(USER.to_owned(), vec![record], Vec::new()) + .await + .unwrap() + .remove(0) + { + CloudKitOutcome::Saved { system_fields, .. } => system_fields, + other => panic!("not saved: {other:?}"), + } +} + +#[tokio::test] +async fn a_save_holds_only_on_the_stored_system_fields() { + let cloud = zone().await; + let first = saved(&cloud, connection("Connection_A", None, "a")).await; + + let second = saved(&cloud, connection("Connection_A", Some(first.clone()), "b")).await; + let stale = cloud + .modify( + USER.to_owned(), + vec![connection("Connection_A", Some(first), "c")], + Vec::new(), + ) + .await + .unwrap(); + let create_again = cloud + .modify(USER.to_owned(), vec![connection("Connection_A", None, "d")], Vec::new()) + .await + .unwrap(); + + let server = match &stale[0] { + CloudKitOutcome::ServerChanged { + server: Some(server), .. + } => server.clone(), + other => panic!("not server changed: {other:?}"), + }; + assert_eq!(server.system_fields, Some(second)); + assert_eq!(server.fields, connection("x", None, "b").fields); + assert!(matches!( + &create_again[0], + CloudKitOutcome::ServerChanged { server: Some(_), .. } + )); +} + +#[tokio::test] +async fn a_save_rebuilt_for_a_record_deleted_elsewhere_is_unknown_item() { + let cloud = zone().await; + let tag = saved(&cloud, connection("Connection_A", None, "a")).await; + cloud.delete_elsewhere(USER, "Connection_A"); + + let outcome = cloud + .modify( + USER.to_owned(), + vec![connection("Connection_A", Some(tag), "b")], + Vec::new(), + ) + .await + .unwrap(); + + assert_eq!( + outcome[0], + CloudKitOutcome::UnknownItem { + name: "Connection_A".to_owned() + } + ); + assert!(cloud.record(USER, "Connection_A").is_none()); +} + +#[tokio::test] +async fn changes_page_after_a_token_with_deletions_and_a_full_fetch_lists_only_what_is_there() { + let cloud = zone().await; + cloud.set_limits(1, 400, 1 << 20); + for name in ["Connection_A", "Connection_B"] { + saved(&cloud, connection(name, None, "x")).await; + } + + let first = cloud.fetch_changes(USER.to_owned(), None).await.unwrap(); + let second = cloud + .fetch_changes(USER.to_owned(), Some(first.token.clone())) + .await + .unwrap(); + cloud.delete_elsewhere(USER, "Connection_A"); + let after = cloud + .fetch_changes(USER.to_owned(), Some(second.token.clone())) + .await + .unwrap(); + let full = cloud.fetch_changes(USER.to_owned(), None).await.unwrap(); + + assert!(first.more && !second.more); + assert_eq!(first.changed[0].name, "Connection_A"); + assert_eq!(second.changed[0].name, "Connection_B"); + assert_eq!(after.deleted[0].name, "Connection_A"); + assert_eq!(after.deleted[0].record_type, "Connection"); + assert_eq!( + full.changed + .iter() + .map(|record| record.name.as_str()) + .collect::>(), + ["Connection_B"] + ); + assert!(full.deleted.is_empty()); +} + +#[tokio::test] +async fn an_expired_token_answers_token_expired() { + let cloud = zone().await; + saved(&cloud, connection("Connection_A", None, "a")).await; + let changes = cloud.fetch_changes(USER.to_owned(), None).await.unwrap(); + + cloud.expire_tokens(USER); + + let expired = cloud.fetch_changes(USER.to_owned(), Some(changes.token)).await; + let fresh = cloud.fetch_changes(USER.to_owned(), None).await.unwrap(); + let next = cloud.fetch_changes(USER.to_owned(), Some(fresh.token)).await; + + assert_eq!(expired.unwrap_err(), CloudKitFailure::TokenExpired); + assert_eq!(fresh.changed.len(), 1); + assert!(next.unwrap().changed.is_empty()); +} + +#[tokio::test] +async fn a_batch_over_the_limit_saves_nothing() { + let cloud = zone().await; + cloud.set_limits(200, 1, 1 << 20); + + let batch = vec![ + connection("Connection_A", None, "a"), + connection("Connection_B", None, "b"), + ]; + let refused = cloud.modify(USER.to_owned(), batch, Vec::new()).await; + + assert_eq!(refused.unwrap_err(), CloudKitFailure::LimitExceeded); + assert!(cloud.record_names(USER).is_empty()); +} + +#[tokio::test] +async fn a_zone_the_person_removed_answers_so_until_it_is_made_again() { + let cloud = zone().await; + saved(&cloud, connection("Connection_A", None, "a")).await; + + cloud.remove_zone_by_user(USER); + let fetch = cloud.fetch_changes(USER.to_owned(), None).await; + let save = cloud + .modify(USER.to_owned(), vec![connection("Connection_A", None, "a")], Vec::new()) + .await; + cloud.ensure_zone(USER.to_owned()).await.unwrap(); + + assert_eq!(fetch.unwrap_err(), CloudKitFailure::ZoneDeletedByUser); + assert_eq!(save.unwrap_err(), CloudKitFailure::ZoneDeletedByUser); + assert!(cloud.record_names(USER).is_empty()); +} + +#[tokio::test] +async fn another_account_before_or_during_a_call_saves_nothing_to_either() { + let cloud = zone().await; + cloud.switch_account(Some("_other")); + let before = cloud + .modify(USER.to_owned(), vec![connection("Connection_A", None, "a")], Vec::new()) + .await; + cloud.switch_account(Some(USER)); + cloud.switch_account_during_next_call(Some("_other")); + let during = cloud + .modify(USER.to_owned(), vec![connection("Connection_A", None, "a")], Vec::new()) + .await; + + assert_eq!(before.unwrap_err(), CloudKitFailure::AccountChanged); + assert_eq!(during.unwrap_err(), CloudKitFailure::AccountChanged); + assert!(cloud.record_names(USER).is_empty()); + assert!(cloud.record_names("_other").is_empty()); + assert_eq!(cloud.account_status().await.unwrap().user_record_name, "_other"); +} + +#[tokio::test] +async fn records_are_fetched_by_name_and_a_failing_one_answers_alone() { + let cloud = zone().await; + saved(&cloud, connection("Connection_A", None, "a")).await; + cloud.fail_record("Connection_B", 7); + + let fetched = cloud + .fetch_records( + USER.to_owned(), + vec!["Connection_A".to_owned(), "Connection_Z".to_owned()], + ) + .await + .unwrap(); + let outcomes = cloud + .modify( + USER.to_owned(), + vec![ + connection("Connection_B", None, "b"), + connection("Connection_C", None, "c"), + ], + Vec::new(), + ) + .await + .unwrap(); + + assert!(matches!(&fetched[0], CloudKitFetched::Found { record } if record.name == "Connection_A")); + assert_eq!( + fetched[1], + CloudKitFetched::Missing { + name: "Connection_Z".to_owned() + } + ); + assert!(matches!(&outcomes[0], CloudKitOutcome::Failed { code: 7, .. })); + assert!(matches!(&outcomes[1], CloudKitOutcome::Saved { .. })); +} + +#[tokio::test] +async fn a_signed_out_device_has_no_account() { + let cloud = FakeCloudKit::signed_in(USER); + cloud.switch_account(None); + + assert_eq!(cloud.account_status().await.unwrap_err(), CloudKitFailure::NoAccount); + assert_eq!( + cloud.ensure_zone(USER.to_owned()).await.unwrap_err(), + CloudKitFailure::NoAccount + ); +} + +#[tokio::test] +async fn a_record_made_again_after_its_zone_was_removed_has_a_later_creation_date() { + let cloud = zone().await; + saved(&cloud, connection("Connection_A", None, "a")).await; + let first = cloud.record(USER, "Connection_A").unwrap().created_ms.unwrap(); + cloud.remove_zone_by_user(USER); + cloud.ensure_zone(USER.to_owned()).await.unwrap(); + saved(&cloud, connection("Connection_B", None, "b")).await; + saved(&cloud, connection("Connection_A", None, "a")).await; + + let again = cloud.record(USER, "Connection_A").unwrap().created_ms.unwrap(); + + assert!(again > first); +} diff --git a/core/crates/sync/testing/src/device_store/mod.rs b/core/crates/sync/testing/src/device_store/mod.rs new file mode 100644 index 0000000000..853f402abc --- /dev/null +++ b/core/crates/sync/testing/src/device_store/mod.rs @@ -0,0 +1,221 @@ +// A device store as 0054 and 0056 describe the platforms' (Integrity and freshness; Device stores): items of the +// anchor's class read only while the device is unlocked and go when the passcode is turned off; a backup brings keys +// back only to the same device and never brings the anchor back. + +use std::collections::HashMap; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use async_trait::async_trait; +use tablepro_sync::api::device_store::{DeviceItem, DeviceItemClass, DeviceStoreError, HostDeviceStore}; +use zeroize::Zeroizing; + +#[derive(Debug, Default)] +struct State { + items: HashMap>>, + locked: bool, + unavailable: bool, + fail_next: Vec, +} + +#[derive(Debug, Default)] +pub struct FakeDeviceStore { + state: Mutex, +} + +// What a device backup holds of the store. +#[derive(Debug, Clone)] +pub struct DeviceBackup(HashMap>>); + +impl FakeDeviceStore { + pub fn new() -> Self { + Self::default() + } + + // A Linux session with no Secret Service. + pub fn without_store() -> Self { + let store = Self::default(); + store.lock().unavailable = true; + store + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn set_locked(&self, locked: bool) { + self.lock().locked = locked; + } + + // Turning the passcode off deletes every item of the anchor's class. + pub fn remove_passcode(&self) { + self.lock() + .items + .retain(|item, _| item.class() != DeviceItemClass::Anchor); + } + + pub fn fail_next(&self, error: DeviceStoreError) { + self.lock().fail_next.push(error); + } + + pub fn holds(&self, item: &DeviceItem) -> bool { + self.lock().items.contains_key(item) + } + + pub fn len(&self) -> usize { + self.lock().items.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn backup(&self) -> DeviceBackup { + DeviceBackup( + self.lock() + .items + .iter() + .filter(|(item, _)| item.class() == DeviceItemClass::Keys) + .map(|(item, value)| (item.clone(), value.clone())) + .collect(), + ) + } + + // A restore puts the keys back on the device they were backed up from, and nothing on another device. + pub fn restore(&self, backup: &DeviceBackup, same_device: bool) { + let mut state = self.lock(); + state.items.clear(); + if same_device { + state + .items + .extend(backup.0.iter().map(|(item, value)| (item.clone(), value.clone()))); + } + } + + fn admit(&self, item: &DeviceItem) -> Result, DeviceStoreError> { + let mut state = self.lock(); + if !state.fail_next.is_empty() { + return Err(state.fail_next.remove(0)); + } + if state.unavailable { + return Err(DeviceStoreError::Unavailable { + detail: "no secret service".to_owned(), + }); + } + if state.locked && item.class() == DeviceItemClass::Anchor { + return Err(DeviceStoreError::Locked); + } + Ok(state) + } +} + +#[async_trait] +impl HostDeviceStore for FakeDeviceStore { + async fn load(&self, item: DeviceItem) -> Result>>, DeviceStoreError> { + let state = self.admit(&item)?; + Ok(state.items.get(&item).cloned()) + } + + async fn store(&self, item: DeviceItem, value: Zeroizing>) -> Result<(), DeviceStoreError> { + let mut state = self.admit(&item)?; + state.items.insert(item, value); + Ok(()) + } + + async fn delete(&self, item: DeviceItem) -> Result<(), DeviceStoreError> { + let mut state = self.admit(&item)?; + state.items.remove(&item); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use tablepro_keys::encoding::{AccountId, Origin, Version}; + use tablepro_sync::api::ids::{DeviceRowId, StateName}; + use uuid::Uuid; + + use super::*; + + fn keys() -> DeviceItem { + DeviceItem::AccountKeys { + origin: Origin::parse("https://api.tablepro.app").unwrap(), + account: AccountId(Uuid::nil()), + av: Version::new(1).unwrap(), + } + } + + fn device_keys() -> DeviceItem { + DeviceItem::DeviceKeys { + origin: Origin::parse("https://api.tablepro.app").unwrap(), + account: AccountId(Uuid::nil()), + device_row: DeviceRowId("dev_a".to_owned()), + } + } + + fn anchor() -> DeviceItem { + DeviceItem::AnchorRoot { + state: StateName("ab".repeat(32)), + } + } + + async fn filled() -> FakeDeviceStore { + let store = FakeDeviceStore::new(); + for item in [keys(), device_keys(), anchor()] { + store.store(item, Zeroizing::new(vec![1, 2])).await.unwrap(); + } + store + } + + #[tokio::test] + async fn a_locked_device_reads_its_keys_but_not_its_anchor() { + let store = filled().await; + + store.set_locked(true); + + assert!(store.load(keys()).await.unwrap().is_some()); + assert_eq!(store.load(anchor()).await.unwrap_err(), DeviceStoreError::Locked); + } + + #[tokio::test] + async fn turning_the_passcode_off_deletes_the_anchor_and_keeps_the_keys() { + let store = filled().await; + + store.remove_passcode(); + + assert!(!store.holds(&anchor())); + assert!(store.holds(&keys()) && store.holds(&device_keys())); + } + + #[tokio::test] + async fn a_backup_restores_keys_to_the_same_device_and_never_the_anchor() { + let store = filled().await; + let backup = store.backup(); + + store.restore(&backup, true); + let same = (store.holds(&keys()), store.holds(&anchor())); + store.restore(&backup, false); + + assert_eq!(same, (true, false)); + assert!(store.is_empty()); + } + + #[tokio::test] + async fn a_device_without_a_store_holds_nothing() { + let store = FakeDeviceStore::without_store(); + + let stored = store.store(keys(), Zeroizing::new(vec![1])).await; + + assert!(matches!(stored, Err(DeviceStoreError::Unavailable { .. }))); + } + + #[tokio::test] + async fn deleting_an_item_that_is_not_there_succeeds() { + let store = FakeDeviceStore::new(); + + store.delete(keys()).await.unwrap(); + store.store(keys(), Zeroizing::new(vec![1])).await.unwrap(); + store.delete(keys()).await.unwrap(); + + assert!(store.load(keys()).await.unwrap().is_none()); + } +} diff --git a/core/crates/sync/testing/src/key_flows/account.rs b/core/crates/sync/testing/src/key_flows/account.rs new file mode 100644 index 0000000000..d58a39bd24 --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/account.rs @@ -0,0 +1,383 @@ +use async_trait::async_trait; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use secrecy::{ExposeSecret, SecretString}; +use serde_json::{Value, json}; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{AccountId, HistoryId, KeyDeviceId, Version}; +use tablepro_keys::envelope::EnvelopeId; +use tablepro_keys::fingerprint::{fingerprint, fingerprint_words, parse_qr, qr_text}; +use tablepro_keys::keys::{Ed25519Public, Ed25519Seed}; +use tablepro_keys::sas::SAS_WORDS; +use tablepro_keys::words::words; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::ids::ScopeName; +use tablepro_sync::api::key_flows::{ + Acceptance, AccountFlows, DraftId, Fingerprint, GenesisOutcome, KeyApplied, KeyArrival, KeyChange, KeyNotice, + KeyNoticeKind, KeyState, MemberKeyStatus, NoticeId, OpenedEnvelope, RecoveryKeyDraft, ReviewedDevice, + RotationDraft, SignOutOutcome, TypedBack, +}; +use uuid::Uuid; + +use super::{ + DraftPurpose, FakeKeyFlows, Model, check_typed_back, keep_compared, new_draft, require_approved, rotate, + same_recovery_key, supersede_reset, version, +}; + +pub(crate) fn notice(model: &mut Model, kind: KeyNoticeKind) { + model.notices.push(KeyNotice { + id: NoticeId(Uuid::new_v4()), + kind, + }); +} + +pub(crate) fn sas_words() -> Vec { + let digest: [u8; 32] = *Uuid::new_v4().as_bytes().repeat(2).first_chunk().unwrap_or(&[0; 32]); + words(&digest, SAS_WORDS).into_iter().map(str::to_owned).collect() +} + +// Sealed in the clear: `ct` is the plaintext's base64url, which only this fake writes. +pub(crate) fn fake_seal(kv: Version, plaintext: &Value) -> Value { + json!({"suite": "tp1", "kv": kv.get(), "nonce": "fake", "ct": URL_SAFE_NO_PAD.encode(plaintext.to_string())}) +} + +pub(crate) fn fake_open(fields: &Value) -> Result<(Version, Value), SyncError> { + let malformed = || { + SyncError::Keys(KeysError::Encoding { + what: "not a fake envelope", + }) + }; + let kv = fields.get("kv").and_then(Value::as_i64).ok_or_else(malformed)?; + let ct = fields.get("ct").and_then(Value::as_str).ok_or_else(malformed)?; + let bytes = URL_SAFE_NO_PAD.decode(ct).map_err(|_| malformed())?; + let plaintext = serde_json::from_slice(&bytes).map_err(|_| malformed())?; + Ok((Version::from_i64(kv)?, plaintext)) +} + +// In order, exactly the version in force at its place; in a snapshot, any version up to the newest. Never below the +// copy held (0056, Rollback). +pub(crate) fn take_kv( + model: &mut Model, + scope: ScopeName, + id: &str, + kv: Version, + in_force: Option, + newest: u32, +) -> Result<(), SyncError> { + let held = model.held_kv.get(&(scope, id.to_owned())).copied(); + let ceiling = in_force.map_or(newest, Version::get); + if kv.get() > ceiling { + return Err(SyncError::Keys(KeysError::Step { + held: ceiling, + offered: kv.get(), + })); + } + for floor in [in_force.map(Version::get), held].into_iter().flatten() { + if kv.get() < floor { + return Err(SyncError::Keys(KeysError::Stale { + held: floor, + offered: kv.get(), + })); + } + } + model.held_kv.insert((scope, id.to_owned()), kv.get()); + Ok(()) +} + +impl FakeKeyFlows { + pub(crate) fn identity( + &self, + model: &mut Model, + account: AccountId, + ) -> Result { + if let Some(ik) = model.identities.get(&account) { + return Ok(*ik); + } + let ik = Ed25519Seed::generate()?.public()?; + model.identities.insert(account, ik); + Ok(ik) + } + + fn fingerprint_of(&self, account: AccountId) -> Result { + let ik = self.identity(&mut self.lock(), account)?; + let digest = fingerprint(&self.origin, account, &ik)?; + Ok(Fingerprint { + words: fingerprint_words(&digest).into_iter().map(str::to_owned).collect(), + qr: qr_text(&digest), + }) + } + + // The personal scope's version in force, which every personal apply answers. + pub(crate) fn applied(&self) -> KeyApplied { + KeyApplied { + in_force: Version::new(self.lock().av).ok(), + ..KeyApplied::default() + } + } + + pub(crate) fn approve(&self, model: &mut Model) -> Result<(), SyncError> { + model.av = model.av.max(1); + model.key_state = KeyState::Approved { + av: version(model.av)?, + key_device: model.key_device, + }; + Ok(()) + } +} + +#[async_trait] +impl AccountFlows for FakeKeyFlows { + async fn key_state(&self) -> Result { + Ok(self.lock().key_state.clone()) + } + + async fn begin_genesis(&self) -> Result { + let mut model = self.lock(); + if model.key_state != KeyState::NoKeys { + return Err(SyncError::NotAllowed { + what: "start a genesis", + }); + } + let (draft, made) = new_draft(&mut model, DraftPurpose::Genesis)?; + Ok(RecoveryKeyDraft { + draft, + text: made.text, + check: made.check, + }) + } + + async fn finish_genesis(&self, draft: DraftId, typed: TypedBack) -> Result { + let mut model = self.lock(); + let held = model + .drafts + .get(&draft) + .cloned() + .ok_or(SyncError::Unknown { what: "draft" })?; + check_typed_back(&held, &typed)?; + model.drafts.remove(&draft); + if model.another_device_won { + model.key_state = super::KeyState::NeedsApproval { request: None }; + model.av = 1; + return Ok(GenesisOutcome::AnotherDeviceWon); + } + model.recovery = Some(held.text); + model.history_version = 1; + self.approve(&mut model)?; + Ok(GenesisOutcome::Created) + } + + async fn sign_out(&self) -> Result { + let mut model = self.lock(); + // The keys and the key device id go; signing in again is a new device (0056, Sign Out). + model.key_state = KeyState::NeedsApproval { request: None }; + model.sessions.clear(); + model.key_device = KeyDeviceId(Uuid::new_v4()); + model.held_kv.clear(); + model.reviews.clear(); + for team in model.teams.values_mut() { + team.holder = false; + } + // The revoke ends a reset this row proposed; offline, nothing reaches the server, but this device erases R' and + // the reset's keys with the rest, so it can no longer activate it. + if !model.offline { + supersede_reset(&mut model); + } + model.drafts.clear(); + model.reset_drafts.clear(); + if let Some(reset) = &mut model.reset { + reset.mine = false; + } + Ok(if model.offline { + SignOutOutcome::ErasedOffline + } else { + SignOutOutcome::Revoked + }) + } + + async fn begin_replace(&self, recovery_key: SecretString) -> Result { + let mut model = self.lock(); + require_approved(&model, "replace the recovery key")?; + same_recovery_key(model.recovery.as_ref(), &recovery_key)?; + let (draft, made) = new_draft(&mut model, DraftPurpose::Replace)?; + let devices = model + .devices + .iter() + .map(|device| ReviewedDevice { + keep_by_default: device.compared, + device: device.clone(), + }) + .collect(); + Ok(RotationDraft { + recovery: RecoveryKeyDraft { + draft, + text: made.text, + check: made.check, + }, + devices, + }) + } + + async fn finish_replace(&self, draft: DraftId, typed: TypedBack, keep: Vec) -> Result<(), SyncError> { + let mut model = self.lock(); + let held = model + .drafts + .get(&draft) + .filter(|held| held.purpose == DraftPurpose::Replace) + .cloned() + .ok_or(SyncError::Unknown { what: "draft" })?; + check_typed_back(&held, &typed)?; + keep_compared(&mut model, &keep)?; + model.drafts.remove(&draft); + model.recovery = Some(held.text); + rotate(&mut model); + self.approve(&mut model) + } + + async fn own_fingerprint(&self) -> Result { + self.fingerprint_of(self.account) + } + + async fn fingerprint(&self, account: AccountId) -> Result { + self.fingerprint_of(account) + } + + async fn compare_qr(&self, account: AccountId, text: String) -> Result { + let scanned = parse_qr(&text)?; + let ik = self.identity(&mut self.lock(), account)?; + Ok(scanned == fingerprint(&self.origin, account, &ik)?) + } + + async fn key_change(&self, account: AccountId) -> Result, SyncError> { + let offered = self.lock().offered.get(&account).copied(); + let Some(offered_ik) = offered else { + return Ok(None); + }; + let digest = fingerprint(&self.origin, account, &offered_ik)?; + Ok(Some(KeyChange { + account, + pinned: self.fingerprint_of(account)?, + offered: Fingerprint { + words: fingerprint_words(&digest).into_iter().map(str::to_owned).collect(), + qr: qr_text(&digest), + }, + offered_ik, + })) + } + + async fn accept_key_change( + &self, + account: AccountId, + offered: Ed25519Public, + how: Acceptance, + ) -> Result<(), SyncError> { + let _ = how; + let mut model = self.lock(); + if model.offered.get(&account) != Some(&offered) { + return Err(SyncError::Unknown { what: "key change" }); + } + model.offered.remove(&account); + model.identities.insert(account, offered); + for team in model.teams.values_mut() { + if let Some((_, status)) = team.members.get_mut(&account) + && *status == MemberKeyStatus::Alert + { + // The alert clears; a team key reaches the member only once an owner or admin confirms it again. + *status = MemberKeyStatus::AwaitingConfirmation; + } + } + model + .notices + .retain(|notice| notice.kind != KeyNoticeKind::KeysChanged { account }); + Ok(()) + } + + async fn notices(&self) -> Result, SyncError> { + Ok(self.lock().notices.clone()) + } + + async fn dismiss_notice(&self, notice: NoticeId) -> Result<(), SyncError> { + self.lock().notices.retain(|held| held.id != notice); + Ok(()) + } + + // Parses nothing: the version in force comes back, so an engine test can carry it with the cursor. + async fn apply_account_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + Ok(self.applied()) + } + + async fn seal_personal_envelope( + &self, + envelope: EnvelopeId, + secret: SecretString, + dest: Value, + ) -> Result { + let model = self.lock(); + require_approved(&model, "seal a personal secret")?; + let _ = envelope; + Ok(fake_seal( + version(model.av)?, + &json!({"secret": secret.expose_secret(), "dest": dest}), + )) + } + + async fn open_personal_envelope( + &self, + envelope: EnvelopeId, + fields: Value, + in_force: Option, + ) -> Result { + let mut model = self.lock(); + require_approved(&model, "open a personal secret")?; + let (kv, plaintext) = fake_open(&fields)?; + let newest = model.av; + take_kv( + &mut model, + ScopeName::Personal, + &envelope.to_wire(), + kv, + in_force, + newest, + )?; + Ok(opened(kv, &plaintext)) + } + + async fn seal_history_entry(&self, entry: HistoryId, plaintext: Value) -> Result { + let model = self.lock(); + require_approved(&model, "seal a history entry")?; + let _ = entry; + Ok(fake_seal( + version(model.history_version.max(1))?, + &json!({"entry": plaintext}), + )) + } + + async fn open_history_entry(&self, entry: HistoryId, fields: Value) -> Result { + let model = self.lock(); + require_approved(&model, "open a history entry")?; + let _ = entry; + let (kv, plaintext) = fake_open(&fields)?; + // History has no order against its key's versions: any version up to the newest (0056, Rollback, History). + if kv.get() > model.history_version.max(1) { + return Err(SyncError::Keys(KeysError::Step { + held: model.history_version, + offered: kv.get(), + })); + } + Ok(plaintext.get("entry").cloned().unwrap_or(Value::Null)) + } +} + +pub(crate) fn opened(kv: Version, plaintext: &Value) -> OpenedEnvelope { + OpenedEnvelope { + secret: SecretString::from( + plaintext + .get("secret") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(), + ), + dest: plaintext.get("dest").cloned().unwrap_or(Value::Null), + kv, + } +} diff --git a/core/crates/sync/testing/src/key_flows/approval.rs b/core/crates/sync/testing/src/key_flows/approval.rs new file mode 100644 index 0000000000..d2ceb9752a --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/approval.rs @@ -0,0 +1,161 @@ +use async_trait::async_trait; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{RequestId, random_uuid}; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::key_flows::{ + ApprovalFlows, ApprovalRequest, ApprovalSession, KeyApplied, KeyArrival, KeyState, SessionEnd, SessionPhase, + SessionRole, +}; +use tablepro_sync::api::transport::RejectedCode; + +use super::{FakeKeyFlows, Model, SESSION_US, Session, account::sas_words, require_approved}; + +// A session that ended takes no step (0056, The session). +fn ended(phase: &SessionPhase) -> bool { + matches!( + phase, + SessionPhase::Approved | SessionPhase::Cancelled { .. } | SessionPhase::Expired | SessionPhase::TakenElsewhere + ) +} + +fn live(model: &mut Model, request: RequestId) -> Result<&mut Session, SyncError> { + let now = model.clock_us; + let session = model + .sessions + .get_mut(&request) + .ok_or(SyncError::Unknown { what: "session" })?; + if now >= session.expires_at_us && !ended(&session.phase) { + session.phase = SessionPhase::Expired; + } + if ended(&session.phase) { + return Err(SyncError::Keys(KeysError::Session)); + } + Ok(session) +} + +fn view(request: RequestId, session: &Session) -> ApprovalSession { + ApprovalSession { + request, + role: session.role, + phase: session.phase.clone(), + expires_at_us: session.expires_at_us, + } +} + +#[async_trait] +impl ApprovalFlows for FakeKeyFlows { + async fn request_approval(&self) -> Result { + let mut model = self.lock(); + if !matches!(model.key_state, KeyState::NeedsApproval { .. }) { + return Err(SyncError::NotAllowed { + what: "ask for approval", + }); + } + if model + .sessions + .values() + .any(|session| session.role == SessionRole::NewDevice && !ended(&session.phase)) + { + return Err(SyncError::Rejected { + code: RejectedCode::RequestPending, + }); + } + let request = RequestId(random_uuid()?); + let expires_at_us = model.clock_us + SESSION_US; + model.sessions.insert( + request, + Session { + role: SessionRole::NewDevice, + phase: SessionPhase::Open, + expires_at_us, + }, + ); + model.key_state = KeyState::NeedsApproval { request: Some(request) }; + Ok(request) + } + + async fn approval_requests(&self) -> Result, SyncError> { + let model = self.lock(); + require_approved(&model, "approve a device")?; + let open = |request: &&ApprovalRequest| { + model + .sessions + .get(&request.request) + .is_some_and(|session| session.phase == SessionPhase::Open && model.clock_us < session.expires_at_us) + }; + let mut requests: Vec = model.incoming.iter().filter(open).cloned().collect(); + requests.sort_by_key(|request| std::cmp::Reverse(request.requested_at_us)); + Ok(requests) + } + + async fn choose_request(&self, request: RequestId) -> Result { + let mut model = self.lock(); + require_approved(&model, "approve a device")?; + let taken = model.taken_elsewhere.contains(&request); + let session = live(&mut model, request)?; + if session.phase != SessionPhase::Open { + return Err(SyncError::Keys(KeysError::Session)); + } + // N's reveal follows the `nonce` step at once here. + session.phase = if taken { + SessionPhase::TakenElsewhere + } else { + SessionPhase::Compare { words: sas_words() } + }; + Ok(view(request, session)) + } + + async fn approval_session(&self, request: RequestId) -> Result { + let mut model = self.lock(); + let _ = live(&mut model, request); + let session = model + .sessions + .get(&request) + .ok_or(SyncError::Unknown { what: "session" })?; + Ok(view(request, session)) + } + + async fn confirm_session(&self, request: RequestId) -> Result { + let mut model = self.lock(); + let session = live(&mut model, request)?; + if !matches!(session.phase, SessionPhase::Compare { .. }) { + return Err(SyncError::Keys(KeysError::Session)); + } + // The other side confirms at once here: A's change set applies and N merges it. + session.phase = SessionPhase::Approved; + let role = session.role; + let answer = view(request, session); + if role == SessionRole::NewDevice { + self.approve(&mut model)?; + } + Ok(answer) + } + + async fn words_differ(&self, request: RequestId) -> Result<(), SyncError> { + let mut model = self.lock(); + let session = live(&mut model, request)?; + session.phase = SessionPhase::Cancelled { + reason: SessionEnd::Mismatch, + }; + Ok(()) + } + + async fn cancel_session(&self, request: RequestId) -> Result<(), SyncError> { + let mut model = self.lock(); + let session = live(&mut model, request)?; + session.phase = SessionPhase::Cancelled { + reason: SessionEnd::User, + }; + Ok(()) + } + + async fn apply_session_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + Ok(self.applied()) + } + + async fn resume_approval(&self, request: RequestId) -> Result<(), SyncError> { + let _ = request; + Ok(()) + } +} diff --git a/core/crates/sync/testing/src/key_flows/device.rs b/core/crates/sync/testing/src/key_flows/device.rs new file mode 100644 index 0000000000..9d1705b6b2 --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/device.rs @@ -0,0 +1,103 @@ +use async_trait::async_trait; +use secrecy::SecretString; +use tablepro_keys::encoding::{KeyDeviceId, Version}; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::ids::DeviceRowId; +use tablepro_sync::api::key_flows::{ + AccountDevice, DeviceFlows, DraftId, KeyNoticeKind, MemberKeyStatus, RemovalReview, ReviewedDevice, ReviewedMember, +}; +use tablepro_sync::api::transport::{StepUpChallenge, TransportError}; +use uuid::Uuid; + +use super::{FakeKeyFlows, account::notice, keep_compared, require_approved, rotate, same_recovery_key}; + +#[async_trait] +impl DeviceFlows for FakeKeyFlows { + async fn account_devices(&self) -> Result, SyncError> { + Ok(self.lock().devices.clone()) + } + + async fn remove_device_row(&self, device: DeviceRowId) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "remove a device")?; + if !model.step_up_fresh { + return Err(SyncError::Transport(TransportError::StepUpRequired(StepUpChallenge { + acr_values: vec!["urn:tablepro:acr:passkey".to_owned()], + max_age_secs: 300, + }))); + } + for held in &mut model.devices { + if held.device.as_ref() == Some(&device) { + held.device = None; + } + } + notice(&mut model, KeyNoticeKind::DeviceRemoved { device }); + Ok(()) + } + + async fn begin_removal( + &self, + recovery_key: SecretString, + lost: Vec, + ) -> Result { + let mut model = self.lock(); + require_approved(&model, "remove a device")?; + same_recovery_key(model.recovery.as_ref(), &recovery_key)?; + let devices = model + .devices + .iter() + .map(|device| ReviewedDevice { + keep_by_default: device.compared && !lost.contains(&device.key_device), + device: device.clone(), + }) + .collect(); + let review = DraftId(Uuid::new_v4()); + model.reviews.insert(review, lost); + Ok(RemovalReview { + review, + devices, + members: model.confirmed_under.clone(), + }) + } + + async fn finish_removal( + &self, + review: DraftId, + keep: Vec, + remove: Vec, + ) -> Result<(), SyncError> { + let mut model = self.lock(); + model + .reviews + .remove(&review) + .ok_or(SyncError::Unknown { what: "review" })?; + keep_compared(&mut model, &keep)?; + rotate(&mut model); + for member in remove { + if let Some(team) = model.teams.get_mut(&member.team) + && let Some((_, status)) = team.members.get_mut(&member.account) + { + *status = MemberKeyStatus::AwaitingConfirmation; + } + } + for team in model.teams.values_mut().filter(|team| team.holder) { + team.version = Version::new(team.version.map_or(1, |version| version.get() + 1)).ok(); + team.rotation_due = false; + } + model.confirmed_under.clear(); + self.approve(&mut model) + } + + async fn recover(&self, recovery_key: SecretString) -> Result<(), SyncError> { + let mut model = self.lock(); + same_recovery_key(model.recovery.as_ref(), &recovery_key)?; + rotate(&mut model); + model.devices.retain(|device| device.this_device); + self.approve(&mut model) + } + + async fn resume_rotation(&self, av: Version) -> Result<(), SyncError> { + let _ = av; + Ok(()) + } +} diff --git a/core/crates/sync/testing/src/key_flows/mod.rs b/core/crates/sync/testing/src/key_flows/mod.rs new file mode 100644 index 0000000000..9e270c3ada --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/mod.rs @@ -0,0 +1,518 @@ +// The key flows as the person and the engine see them, with 0056's states and refusals but none of its cryptography +// beyond the recovery key's text, the SAS words and the fingerprints, which are real. Envelopes and history entries are +// sealed in the clear in a form that says so; their key version rules hold. The `apply_*` calls parse no key object: +// they answer the version in force and nothing held. For the UI lanes and the engine's tests, never for a check of the +// keys themselves. + +mod account; +mod approval; +mod device; +mod reset; +mod team; +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use secrecy::{ExposeSecret, SecretString}; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{AccountId, KeyDeviceId, Origin, RequestId, TeamId, Version}; +use tablepro_keys::envelope::EnvelopeId; +use tablepro_keys::keys::Ed25519Public; +use tablepro_keys::recovery::RecoveryKey; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::ids::ScopeName; +use tablepro_sync::api::key_flows::MemberKeyStatus; +use tablepro_sync::api::key_flows::{ + AccountDevice, ApprovalRequest, DraftId, KeyChangeSet, KeyHooks, KeyNotice, KeyState, LockCause, PendingReset, + ReviewedMember, SessionPhase, SessionRole, StopAction, TypedBack, +}; +use tablepro_sync::api::scopes::Role; +use uuid::Uuid; + +pub(crate) const SESSION_US: i64 = 600 * 1_000_000; +pub(crate) const RESET_HOLD_US: i64 = 7 * 24 * 3600 * 1_000_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DraftPurpose { + Genesis, + Replace, + Reset(tablepro_sync::api::key_flows::ResetKind), +} + +#[derive(Debug, Clone)] +pub(crate) struct Draft { + pub(crate) purpose: DraftPurpose, + pub(crate) text: SecretString, + pub(crate) check: [u8; 2], +} + +#[derive(Debug, Clone)] +pub(crate) struct Session { + pub(crate) role: SessionRole, + pub(crate) phase: SessionPhase, + pub(crate) expires_at_us: i64, +} + +#[derive(Debug, Clone)] +pub(crate) struct FakeTeam { + pub(crate) role: Role, + pub(crate) version: Option, + pub(crate) holder: bool, + pub(crate) rotation_due: bool, + pub(crate) members: BTreeMap, + pub(crate) ended: bool, + // Why the team stopped on this device, as its `key_versions` row records it (0062). + pub(crate) stopped_cause: Option, + // Every version this account held, which a stop report's re-confirmation needs. + pub(crate) held_versions: std::collections::BTreeSet, + pub(crate) stopped: Vec, + // A restart this device holds: its version and the account that signed it (0064). + pub(crate) held_restart: Option<(Version, AccountId)>, +} + +#[derive(Debug)] +pub(crate) struct Model { + pub(crate) key_state: KeyState, + pub(crate) av: u32, + pub(crate) recovery: Option, + pub(crate) drafts: HashMap, + pub(crate) another_device_won: bool, + pub(crate) sessions: HashMap, + pub(crate) incoming: Vec, + pub(crate) taken_elsewhere: Vec, + pub(crate) devices: Vec, + pub(crate) reviews: HashMap>, + pub(crate) confirmed_under: Vec, + pub(crate) step_up_fresh: bool, + pub(crate) offline: bool, + pub(crate) reset: Option, + pub(crate) teams: BTreeMap, + pub(crate) notices: Vec, + pub(crate) stop_actions: Vec, + pub(crate) push_back: Vec, + pub(crate) identities: HashMap, + pub(crate) history_version: u32, + pub(crate) held_kv: HashMap<(ScopeName, String), u32>, + pub(crate) credentials: Vec, + pub(crate) clock_us: i64, + pub(crate) key_device: KeyDeviceId, + // An IK offered for an account whose pin is under an alert. + pub(crate) offered: HashMap, + // The draft holding R' for each reset this device proposed. + pub(crate) reset_drafts: HashMap, +} + +#[derive(Debug)] +pub struct FakeKeyFlows { + pub(crate) origin: Origin, + pub(crate) account: AccountId, + pub(crate) model: Mutex, +} + +impl FakeKeyFlows { + // An account that has no keys yet: genesis is offered. + pub fn new(origin: Origin, account: AccountId) -> Self { + Self { + origin, + account, + model: Mutex::new(Model { + key_state: KeyState::NoKeys, + av: 0, + recovery: None, + drafts: HashMap::new(), + another_device_won: false, + sessions: HashMap::new(), + incoming: Vec::new(), + taken_elsewhere: Vec::new(), + devices: Vec::new(), + reviews: HashMap::new(), + confirmed_under: Vec::new(), + step_up_fresh: false, + offline: false, + reset: None, + teams: BTreeMap::new(), + notices: Vec::new(), + stop_actions: Vec::new(), + push_back: Vec::new(), + identities: HashMap::new(), + history_version: 0, + held_kv: HashMap::new(), + credentials: Vec::new(), + clock_us: 1_767_225_600_000_000, + key_device: KeyDeviceId(Uuid::new_v4()), + offered: HashMap::new(), + reset_drafts: HashMap::new(), + }), + } + } + + pub(crate) fn lock(&self) -> MutexGuard<'_, Model> { + self.model.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn key_device(&self) -> KeyDeviceId { + self.lock().key_device + } + + pub fn recovery_key(&self) -> Option { + self.lock().recovery.clone() + } + + // The account's R, as another device's genesis made it. + pub fn set_recovery_key(&self, text: SecretString) { + self.lock().recovery = Some(text); + } + + // The account already has keys from another device: this one needs approval. + pub fn account_has_keys(&self) { + let mut model = self.lock(); + model.key_state = KeyState::NeedsApproval { request: None }; + model.av = model.av.max(1); + } + + // Another device's genesis lands first. + pub fn another_device_wins_genesis(&self) { + self.lock().another_device_won = true; + } + + pub fn set_step_up(&self, fresh: bool) { + self.lock().step_up_fresh = fresh; + } + + pub fn set_offline(&self, offline: bool) { + self.lock().offline = offline; + } + + pub fn advance_clock(&self, micros: i64) { + self.lock().clock_us += micros; + } + + pub fn add_device(&self, device: AccountDevice) { + self.lock().devices.push(device); + } + + pub fn incoming_request(&self, request: ApprovalRequest) { + let mut model = self.lock(); + let expires_at_us = request.requested_at_us + SESSION_US; + model.sessions.insert( + request.request, + Session { + role: SessionRole::Approver, + phase: SessionPhase::Open, + expires_at_us, + }, + ); + model.incoming.push(request); + } + + // Another approver wrote its `nonce` step first. + pub fn taken_by_another_approver(&self, request: RequestId) { + self.lock().taken_elsewhere.push(request); + } + + // The approver chose this device's request, and its reveal went up: both sides can show the words. + pub fn approver_chose(&self, request: RequestId) { + let words = account::sas_words(); + if let Some(session) = self.lock().sessions.get_mut(&request) { + session.phase = SessionPhase::Compare { words }; + } + } + + pub fn add_team(&self, team: TeamId, role: Role, members: &[(AccountId, Role, MemberKeyStatus)]) { + self.lock().teams.insert( + team, + FakeTeam { + role, + version: None, + holder: false, + rotation_due: false, + ended: false, + stopped_cause: None, + held_versions: std::collections::BTreeSet::new(), + stopped: Vec::new(), + held_restart: None, + members: members + .iter() + .map(|(account, role, status)| (*account, (*role, *status))) + .collect(), + }, + ); + } + + pub fn confirmed_while_lost_device_held_keys(&self, member: ReviewedMember) { + self.lock().confirmed_under.push(member); + } + + // A key change with no endorsement: an alert in every team the account is in. + pub fn raise_alert(&self, account: AccountId) { + let offered = Ed25519Public(*Uuid::new_v4().as_bytes().repeat(2).first_chunk().unwrap_or(&[0; 32])); + let mut model = self.lock(); + model.offered.insert(account, offered); + for team in model.teams.values_mut() { + if let Some((_, status)) = team.members.get_mut(&account) { + *status = MemberKeyStatus::Alert; + } + } + account::notice( + &mut model, + tablepro_sync::api::key_flows::KeyNoticeKind::KeysChanged { account }, + ); + } + + // A catch-up this device could not verify, or a wait on a version a restore lost. Meeting both keeps `CatchUp`, and + // only a catch-up stop is reported (0062). + pub fn stop_team(&self, team: TeamId, cause: tablepro_sync::api::state::StoppedCause) { + use tablepro_sync::api::state::StoppedCause; + let mut model = self.lock(); + let Some(held) = model.teams.get_mut(&team) else { + return; + }; + if held.ended { + return; + } + let kept = held.stopped_cause.map_or(cause, |stopped| stopped.max(cause)); + held.stopped_cause = Some(kept); + let version = held.version; + if kept.is_reported() + && cause == StoppedCause::CatchUp + && let Some(version) = version + { + model.stop_actions.push(StopAction::Report { team, version }); + } + account::notice( + &mut model, + tablepro_sync::api::key_flows::KeyNoticeKind::ScopeStopped { + scope: ScopeName::Team(team), + cause: kept, + }, + ); + } + + // The event that clears a stop of its cause: a re-confirmation, or every awaited version back. + pub fn clear_team_stop(&self, team: TeamId, by: tablepro_sync::api::state::StopClear) -> Result<(), SyncError> { + use tablepro_sync::api::state::{StopClear, StoppedCause}; + let mut model = self.lock(); + let held = model.teams.get_mut(&team).ok_or(SyncError::Unknown { what: "team" })?; + let allowed = matches!( + (held.stopped_cause, by), + (Some(StoppedCause::CatchUp), StopClear::Reconfirmed) + | (Some(StoppedCause::RestoreWait), StopClear::AwaitedVersionsBack) + | (Some(StoppedCause::RestartHeld), StopClear::AcceptedRestart) + ); + if !allowed { + return Err(SyncError::NotAllowed { + what: "clear this stop", + }); + } + held.stopped_cause = None; + if by == StopClear::Reconfirmed { + model + .stop_actions + .retain(|action| !matches!(action, StopAction::Report { team: reported, .. } if *reported == team)); + model.stop_actions.push(StopAction::Withdraw { team }); + } + Ok(()) + } + + // A restart of the team key signed by `signer`, an account other than this one, met while this device held an + // earlier version: held until the person compares words (0064). + pub fn hold_restart(&self, team: TeamId, version: Version, signer: AccountId) { + if let Some(held) = self.lock().teams.get_mut(&team) { + held.held_restart = Some((version, signer)); + } + self.stop_team(team, tablepro_sync::api::state::StoppedCause::RestartHeld); + account::notice( + &mut self.lock(), + tablepro_sync::api::key_flows::KeyNoticeKind::RestartHeld { team, signer }, + ); + } + + pub fn queue_stop_action(&self, action: StopAction) { + self.lock().stop_actions.push(action); + } + + pub fn queue_push_back(&self, set: KeyChangeSet) { + self.lock().push_back.push(set); + } + + pub fn set_credentials_to_rotate(&self, envelopes: Vec) { + self.lock().credentials = envelopes; + } + + pub fn now_us(&self) -> i64 { + self.lock().clock_us + } +} + +pub(crate) fn require_approved(model: &Model, what: &'static str) -> Result<(), SyncError> { + match model.key_state { + KeyState::Approved { .. } => Ok(()), + KeyState::Locked { cause } => Err(SyncError::Locked { cause }), + _ => Err(SyncError::NotAllowed { what }), + } +} + +// A rotation to the next `av`: the personal and history keys move with it, and a pending reset at that `av` ends, +// since whoever rotated holds R (0056, Rotation). +pub(crate) fn rotate(model: &mut Model) { + model.av += 1; + model.history_version = model.av; + supersede_reset(model); +} + +// Only a device this one compared with can be kept (0056, Rotation); the others leave the account's list. +pub(crate) fn keep_compared(model: &mut Model, keep: &[KeyDeviceId]) -> Result<(), SyncError> { + let comparable = |id: &KeyDeviceId| { + model + .devices + .iter() + .any(|device| device.key_device == *id && device.compared) + }; + if !keep.iter().all(comparable) { + return Err(SyncError::Keys(KeysError::NotCompared)); + } + model + .devices + .retain(|device| device.this_device || keep.contains(&device.key_device)); + Ok(()) +} + +pub(crate) fn supersede_reset(model: &mut Model) { + let ended = match &mut model.reset { + Some(reset) if reset.state == tablepro_sync::api::key_flows::ResetState::Pending => { + reset.state = tablepro_sync::api::key_flows::ResetState::Superseded; + Some(reset.reset) + } + _ => None, + }; + if let Some(reset) = ended { + if let Some(draft) = model.reset_drafts.remove(&reset) { + model.drafts.remove(&draft); + } + account::notice( + model, + tablepro_sync::api::key_flows::KeyNoticeKind::ResetEnded { + reset, + state: tablepro_sync::api::key_flows::ResetState::Superseded, + }, + ); + } +} + +pub(crate) fn version(number: u32) -> Result { + Version::new(number).map_err(SyncError::from) +} + +// R's 14 groups, as the text shows them. +pub(crate) fn groups(text: &SecretString) -> Vec { + text.expose_secret().split('-').map(str::to_owned).collect() +} + +// A group as reading the recovery key reads it (0056, The recovery key, Text). +fn normalized(group: &str) -> String { + group + .chars() + .filter(|character| !matches!(character, '-' | ' ')) + .map(|character| match character.to_ascii_uppercase() { + 'O' => '0', + 'I' | 'L' => '1', + other => other, + }) + .collect() +} + +pub(crate) fn check_typed_back(draft: &Draft, typed: &TypedBack) -> Result<(), SyncError> { + let groups = groups(&draft.text); + let matches = draft.check.iter().zip(&typed.groups).all(|(index, typed)| { + groups + .get(usize::from(*index)) + .is_some_and(|group| normalized(typed.expose_secret()) == *group) + }); + if matches { + Ok(()) + } else { + Err(SyncError::TypedBackWrong) + } +} + +pub(crate) fn same_recovery_key(held: Option<&SecretString>, typed: &SecretString) -> Result<(), SyncError> { + let typed = RecoveryKey::parse(typed.expose_secret())?; + let held = held.ok_or(SyncError::NotAllowed { + what: "use a recovery key", + })?; + let held = RecoveryKey::parse(held.expose_secret())?; + if typed.expose() == held.expose() { + Ok(()) + } else { + Err(SyncError::Keys(KeysError::Signature)) + } +} + +pub(crate) fn new_draft(model: &mut Model, purpose: DraftPurpose) -> Result<(DraftId, Draft), SyncError> { + let text = RecoveryKey::generate()?.to_text()?; + let random = Uuid::new_v4().into_bytes(); + let first = random[0] % 14; + let second = (first + 1 + random[1] % 13) % 14; + let draft = Draft { + purpose, + text, + check: [first, second], + }; + let id = DraftId(Uuid::new_v4()); + model.drafts.insert(id, draft.clone()); + Ok((id, draft)) +} + +// The engine side of `KeyHooks`, recording each call for a test to read. +#[derive(Debug, Default)] +pub struct RecordingHooks { + calls: Mutex>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HookCall { + Lock(LockCause), + Stop(ScopeName, tablepro_sync::api::state::StoppedCause), + Resume(ScopeName), + End(ScopeName, Option), + Notice(KeyNotice), + PassSoon, +} + +impl RecordingHooks { + pub fn calls(&self) -> Vec { + self.calls.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + fn record(&self, call: HookCall) { + self.calls.lock().unwrap_or_else(PoisonError::into_inner).push(call); + } +} + +impl KeyHooks for RecordingHooks { + fn lock(&self, cause: LockCause) { + self.record(HookCall::Lock(cause)); + } + + fn stop_scope(&self, scope: ScopeName, cause: tablepro_sync::api::state::StoppedCause) { + self.record(HookCall::Stop(scope, cause)); + } + + fn resume_scope(&self, scope: ScopeName) { + self.record(HookCall::Resume(scope)); + } + + fn end_scope(&self, scope: ScopeName, epoch: Option) { + self.record(HookCall::End(scope, epoch)); + } + + fn notice(&self, notice: KeyNotice) { + self.record(HookCall::Notice(notice)); + } + + fn pass_soon(&self) { + self.record(HookCall::PassSoon); + } +} diff --git a/core/crates/sync/testing/src/key_flows/reset.rs b/core/crates/sync/testing/src/key_flows/reset.rs new file mode 100644 index 0000000000..c258bcd109 --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/reset.rs @@ -0,0 +1,193 @@ +use async_trait::async_trait; +use tablepro_keys::encoding::{ResetId, random_uuid}; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::key_flows::{ + CancelWith, DraftId, KeyApplied, KeyArrival, KeyNoticeKind, KeyState, PendingReset, RecoveryKeyDraft, ResetFlows, + ResetKind, ResetState, TypedBack, +}; +use tablepro_sync::api::transport::{RejectedCode, StepUpChallenge, TransportError}; + +use super::{ + DraftPurpose, FakeKeyFlows, Model, RESET_HOLD_US, account::notice, check_typed_back, new_draft, same_recovery_key, +}; + +fn rejected(code: RejectedCode) -> SyncError { + SyncError::Rejected { code } +} + +// Seven days past `held_until` with no activation, the server ends it (0051, Resets). +fn settle(model: &mut Model) { + let now = model.clock_us; + let ended = match &mut model.reset { + Some(reset) if reset.state == ResetState::Pending && now >= reset.held_until_us + RESET_HOLD_US => { + reset.state = ResetState::Superseded; + Some(reset.reset) + } + _ => None, + }; + if let Some(reset) = ended { + if let Some(draft) = model.reset_drafts.remove(&reset) { + model.drafts.remove(&draft); + } + notice( + model, + KeyNoticeKind::ResetEnded { + reset, + state: ResetState::Superseded, + }, + ); + } +} + +// Kind 2 comes from an approved device; kind 3 from a sign-in whose device is not, stepped up; one pending at most. +fn may_propose(model: &Model, kind: ResetKind) -> Result<(), SyncError> { + let approved = matches!(model.key_state, KeyState::Approved { .. }); + match kind { + ResetKind::KeepScopeKeys if !approved => return Err(rejected(RejectedCode::BadStatement)), + ResetKind::StartEmpty if approved => return Err(rejected(RejectedCode::BadStatement)), + ResetKind::StartEmpty if !model.step_up_fresh => { + return Err(SyncError::Transport(TransportError::StepUpRequired(StepUpChallenge { + acr_values: vec!["urn:tablepro:acr:passkey".to_owned()], + max_age_secs: 300, + }))); + } + _ => {} + } + if pending(model).is_some() { + return Err(rejected(RejectedCode::BadStatement)); + } + Ok(()) +} + +fn pending(model: &Model) -> Option<&PendingReset> { + model.reset.as_ref().filter(|reset| reset.state == ResetState::Pending) +} + +#[async_trait] +impl ResetFlows for FakeKeyFlows { + async fn pending_reset(&self) -> Result, SyncError> { + let mut model = self.lock(); + settle(&mut model); + Ok(model.reset.clone()) + } + + async fn begin_reset(&self, kind: ResetKind) -> Result { + let mut model = self.lock(); + settle(&mut model); + may_propose(&model, kind)?; + let (draft, made) = new_draft(&mut model, DraftPurpose::Reset(kind))?; + Ok(RecoveryKeyDraft { + draft, + text: made.text, + check: made.check, + }) + } + + async fn finish_reset_proposal(&self, draft: DraftId, typed: TypedBack) -> Result { + let mut model = self.lock(); + settle(&mut model); + let held = model + .drafts + .get(&draft) + .cloned() + .ok_or(SyncError::Unknown { what: "draft" })?; + let DraftPurpose::Reset(kind) = held.purpose else { + return Err(SyncError::Unknown { what: "reset draft" }); + }; + check_typed_back(&held, &typed)?; + // What held when the draft began must hold now, and a draft proposes once. + may_propose(&model, kind)?; + if model.reset_drafts.values().any(|proposed| *proposed == draft) { + return Err(rejected(RejectedCode::BadStatement)); + } + let reset = PendingReset { + reset: ResetId(random_uuid()?), + kind, + state: ResetState::Pending, + mine: true, + proposed_by: None, + taken_at_us: model.clock_us, + held_until_us: model.clock_us + RESET_HOLD_US, + }; + // R' stays with its draft, as the reset's keys wait in the device store, until the reset activates or ends. + model.reset_drafts.insert(reset.reset, draft); + model.reset = Some(reset.clone()); + notice(&mut model, KeyNoticeKind::ResetPending { reset: reset.reset }); + Ok(reset) + } + + async fn cancel_reset(&self, reset: ResetId, with: CancelWith) -> Result<(), SyncError> { + let mut model = self.lock(); + settle(&mut model); + if pending(&model).is_none_or(|held| held.reset != reset) { + return Err(rejected(RejectedCode::BadStatement)); + } + match &with { + CancelWith::ThisDevice if !matches!(model.key_state, KeyState::Approved { .. }) => { + return Err(SyncError::NotAllowed { what: "cancel a reset" }); + } + CancelWith::RecoveryKey(text) => same_recovery_key(model.recovery.as_ref(), text)?, + CancelWith::ThisDevice => {} + } + if let Some(held) = &mut model.reset { + held.state = ResetState::Cancelled; + } + if let Some(draft) = model.reset_drafts.remove(&reset) { + model.drafts.remove(&draft); + } + notice( + &mut model, + KeyNoticeKind::ResetEnded { + reset, + state: ResetState::Cancelled, + }, + ); + Ok(()) + } + + async fn activate_reset(&self, reset: ResetId) -> Result<(), SyncError> { + let mut model = self.lock(); + settle(&mut model); + let held = model.reset.clone().filter(|held| held.reset == reset); + let Some(held) = held else { + return Err(rejected(RejectedCode::BadStatement)); + }; + if held.state != ResetState::Pending { + return Err(rejected(RejectedCode::BadStatement)); + } + if !held.mine { + return Err(rejected(RejectedCode::WriterBound)); + } + if model.clock_us < held.held_until_us { + return Err(rejected(RejectedCode::ResetHeld)); + } + // R' waits with the reset's keys; without them the activation cannot be built. + let proposed = model + .reset_drafts + .remove(&reset) + .and_then(|draft| model.drafts.remove(&draft)) + .ok_or(rejected(RejectedCode::BadStatement))?; + model.recovery = Some(proposed.text); + if let Some(stored) = &mut model.reset { + stored.state = ResetState::Active; + } + model.av += 1; + model.history_version = model.av; + model.devices.retain(|device| device.this_device); + for team in model.teams.values_mut() { + team.holder = false; + team.rotation_due = true; + } + self.approve(&mut model) + } + + async fn apply_reset_objects(&self, arrival: KeyArrival) -> Result { + let _ = arrival; + Ok(self.applied()) + } + + async fn resume_reset(&self, reset: ResetId) -> Result<(), SyncError> { + let _ = reset; + Ok(()) + } +} diff --git a/core/crates/sync/testing/src/key_flows/team.rs b/core/crates/sync/testing/src/key_flows/team.rs new file mode 100644 index 0000000000..4379f35180 --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/team.rs @@ -0,0 +1,422 @@ +use async_trait::async_trait; +use secrecy::{ExposeSecret, SecretString}; +use serde_json::{Value, json}; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{AccountId, TeamId, Version}; +use tablepro_keys::envelope::EnvelopeId; +use tablepro_keys::keys::Ed25519Public; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::ids::{EpochId, ScopeName}; +use tablepro_sync::api::key_flows::{ + AccountFlows, HeldRestart, KeyApplied, KeyArrival, KeyChangeSet, KeyNoticeKind, KeyState, LockCause, + MemberKeyStatus, MemberKeys, OpenedEnvelope, PushBackVerdict, RestoreFlows, Roster, StopAction, StopFlows, + StoppedDevice, TeamFlows, TeamKeys, +}; +use tablepro_sync::api::scopes::Role; +use tablepro_sync::api::state::{KeyVersionState, StopClear, StoppedCause}; +use tablepro_sync::api::transport::{ChangeOutcome, RejectedCode}; + +use super::account::{fake_open, fake_seal, notice, opened, take_kv}; +use super::{FakeKeyFlows, FakeTeam, Model, require_approved}; + +fn role(code: RejectedCode) -> SyncError { + SyncError::Rejected { code } +} + +fn team(model: &mut Model, team: TeamId) -> Result<&mut FakeTeam, SyncError> { + model.teams.get_mut(&team).ok_or(SyncError::Unknown { what: "team" }) +} + +// A team that ended on this device writes no secret and takes no new version (0051, What cannot go back). +fn live_team(model: &mut Model, id: TeamId) -> Result<&mut FakeTeam, SyncError> { + let held = team(model, id)?; + if held.ended { + return Err(SyncError::NotAllowed { + what: "use a team that ended on this device", + }); + } + Ok(held) +} + +fn next(version: Option) -> Option { + Version::new(version.map_or(1, |version| version.get() + 1)).ok() +} + +#[async_trait] +impl TeamFlows for FakeKeyFlows { + async fn team_keys(&self, id: TeamId) -> Result { + let mut model = self.lock(); + let held = team(&mut model, id)?; + Ok(TeamKeys { + team: id, + version: held.version, + state: match (held.ended, held.stopped_cause) { + (true, _) => KeyVersionState::Ended, + (false, Some(_)) => KeyVersionState::Stopped, + (false, None) => KeyVersionState::Ok, + }, + stopped_cause: if held.ended { None } else { held.stopped_cause }, + rotation_due: held.rotation_due, + holder: held.holder, + members: held + .members + .iter() + .map(|(account, (role, status))| MemberKeys { + account: *account, + role: *role, + status: *status, + }) + .collect(), + // This fake holds one version at a time, so a holder held the version any report names. + stopped: held + .stopped + .iter() + .map(|report| StoppedDevice { + account: report.account, + device: report.device.clone(), + version: report.version, + can_reconfirm: held.role.manages_keys() && held.held_versions.contains(&report.version.get()), + }) + .collect(), + }) + } + + async fn create_team_keys(&self, id: TeamId) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "create a team key")?; + let held = live_team(&mut model, id)?; + if held.role != Role::Owner || held.version.is_some() { + return Err(role(RejectedCode::Role)); + } + held.version = next(None); + held.holder = true; + held.held_versions.insert(1); + Ok(()) + } + + async fn publish_member_certificate(&self, id: TeamId) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "publish a member certificate")?; + team(&mut model, id).map(|_| ()) + } + + async fn confirm_member(&self, id: TeamId, account: AccountId) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "confirm a member")?; + let held = live_team(&mut model, id)?; + if !held.role.manages_keys() { + return Err(role(RejectedCode::Role)); + } + if !held.holder { + return Err(SyncError::Keys(KeysError::NotHolder)); + } + let (_, status) = held + .members + .get_mut(&account) + .ok_or(SyncError::Unknown { what: "member" })?; + match status { + MemberKeyStatus::NoKeys => Err(SyncError::NotAllowed { + what: "confirm a member with no keys", + }), + // Nothing is wrapped to an account with an open alert until the person re-confirms it. + MemberKeyStatus::Alert => Err(SyncError::NotAllowed { + what: "confirm a member under an alert", + }), + MemberKeyStatus::AwaitingConfirmation | MemberKeyStatus::Holder => { + *status = MemberKeyStatus::Holder; + Ok(()) + } + } + } + + async fn rotate_team(&self, id: TeamId, remove: Vec) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "rotate a team key")?; + let held = live_team(&mut model, id)?; + if !held.holder { + return Err(SyncError::Keys(KeysError::NotHolder)); + } + if held.stopped_cause.is_some() { + return Err(SyncError::NotAllowed { + what: "rotate a team key that stopped on this device", + }); + } + if !held.role.manages_keys() && !held.rotation_due { + return Err(role(RejectedCode::Role)); + } + for (account, (_, status)) in &mut held.members { + if remove.contains(account) && *status == MemberKeyStatus::Holder { + *status = MemberKeyStatus::AwaitingConfirmation; + } + } + held.version = next(held.version); + held.held_versions.extend(held.version.map(Version::get)); + held.rotation_due = false; + Ok(()) + } + + async fn restart_team(&self, id: TeamId, confirm: Vec) -> Result<(), SyncError> { + let mut model = self.lock(); + require_approved(&model, "restart a team key")?; + let held = live_team(&mut model, id)?; + if held.role != Role::Owner { + return Err(role(RejectedCode::Role)); + } + // A restart only once no member on the roster holds the current version. + if held.holder + || held + .members + .values() + .any(|(_, status)| *status == MemberKeyStatus::Holder) + { + return Err(role(RejectedCode::Role)); + } + // Nothing goes to a member with no keys or under an open alert. + for (account, (_, status)) in &mut held.members { + if confirm.contains(account) && *status == MemberKeyStatus::AwaitingConfirmation { + *status = MemberKeyStatus::Holder; + } + } + held.version = next(held.version); + held.held_versions.extend(held.version.map(Version::get)); + held.holder = true; + held.rotation_due = false; + notice(&mut model, KeyNoticeKind::TeamKeyRestarted { team: id }); + Ok(()) + } + + async fn held_restart(&self, id: TeamId) -> Result, SyncError> { + let held = team(&mut self.lock(), id)?.held_restart; + let Some((version, signer)) = held else { + return Ok(None); + }; + let words = self.fingerprint(signer).await?; + let signer_ik = self.identity(&mut self.lock(), signer)?; + Ok(Some(HeldRestart { + team: id, + version, + signer, + signer_ik, + words, + })) + } + + async fn accept_restart(&self, id: TeamId, signer_ik: Ed25519Public) -> Result<(), SyncError> { + let held = team(&mut self.lock(), id)?.held_restart; + let (version, signer) = held.ok_or(SyncError::Unknown { what: "held restart" })?; + // Bound to the IK whose words the person compared. + if self.identity(&mut self.lock(), signer)? != signer_ik { + return Err(SyncError::Keys(KeysError::Mismatch { + what: "the restart's signer is not the one compared", + })); + } + self.clear_team_stop(id, StopClear::AcceptedRestart)?; + let mut model = self.lock(); + let held = team(&mut model, id)?; + held.held_restart = None; + held.version = Some(version); + held.holder = true; + held.held_versions.insert(version.get()); + Ok(()) + } + + async fn credentials_to_rotate(&self, scope: ScopeName) -> Result, SyncError> { + let _ = scope; + Ok(self.lock().credentials.clone()) + } + + async fn roster_read(&self, id: TeamId, roster: Roster) -> Result<(), SyncError> { + let mut model = self.lock(); + let held = team(&mut model, id)?; + if !roster.caught_up() { + return Ok(()); + } + let removed_holder = held.members.iter().any(|(account, (_, status))| { + *status == MemberKeyStatus::Holder && !roster.members.iter().any(|member| member.account == *account) + }); + held.members + .retain(|account, _| roster.members.iter().any(|member| member.account == *account)); + for member in &roster.members { + let entry = held + .members + .entry(member.account) + .or_insert((member.role, MemberKeyStatus::AwaitingConfirmation)); + entry.0 = member.role; + } + if let Some(own) = roster.role { + held.role = own; + } + held.rotation_due = roster.rotation_due || removed_holder; + held.stopped = roster.stopped; + Ok(()) + } + + // Parses nothing: the team's version in force comes back, so an engine test can carry it with the cursor. + async fn apply_team_objects(&self, arrival: KeyArrival) -> Result { + let ScopeName::Team(id) = arrival.scope else { + return Err(SyncError::NotAllowed { + what: "apply team objects outside a team", + }); + }; + let version = team(&mut self.lock(), id)?.version; + Ok(KeyApplied { + in_force: version, + ..KeyApplied::default() + }) + } + + async fn seal_team_envelope( + &self, + id: TeamId, + envelope: EnvelopeId, + secret: SecretString, + dest: Value, + ) -> Result { + let mut model = self.lock(); + require_approved(&model, "seal a team secret")?; + let held = live_team(&mut model, id)?; + if !held.holder { + return Err(role(RejectedCode::Role)); + } + // A stopped team writes nothing under its key (0056, A stopped device). + if held.stopped_cause.is_some() { + return Err(SyncError::NotAllowed { + what: "seal under a team key that stopped on this device", + }); + } + // Team envelopes wait in the queue while the team is due a rotation (0051, Teams). + if held.rotation_due { + return Err(role(RejectedCode::RotationDue)); + } + let kv = held.version.ok_or(SyncError::NotAllowed { + what: "seal before a team key", + })?; + let _ = envelope; + Ok(fake_seal(kv, &json!({"secret": secret.expose_secret(), "dest": dest}))) + } + + async fn open_team_envelope( + &self, + id: TeamId, + envelope: EnvelopeId, + fields: Value, + in_force: Option, + ) -> Result { + let mut model = self.lock(); + let holder = team(&mut model, id)?.holder; + if !holder { + return Err(SyncError::Keys(KeysError::NotHolder)); + } + let (kv, plaintext) = fake_open(&fields)?; + let newest = team(&mut model, id)?.version.map_or(0, Version::get); + take_kv( + &mut model, + ScopeName::Team(id), + &envelope.to_wire(), + kv, + in_force, + newest, + )?; + Ok(opened(kv, &plaintext)) + } +} + +#[async_trait] +impl RestoreFlows for FakeKeyFlows { + async fn push_back(&self, epoch: EpochId) -> Result, SyncError> { + let _ = epoch; + Ok(std::mem::take(&mut self.lock().push_back)) + } + + async fn push_back_answered( + &self, + set: KeyChangeSet, + outcomes: Vec, + ) -> Result { + if outcomes + .iter() + .all(|outcome| matches!(outcome, ChangeOutcome::Applied { .. })) + { + return Ok(PushBackVerdict::Continue); + } + // Every refusal is final (0051, After a restore). + let mut model = self.lock(); + match set.scope { + ScopeName::Personal | ScopeName::History => { + model.key_state = KeyState::Locked { + cause: LockCause::AccountEnded, + }; + notice( + &mut model, + KeyNoticeKind::Locked { + cause: LockCause::AccountEnded, + }, + ); + Ok(PushBackVerdict::AccountEnded) + } + scope @ ScopeName::Team(id) => { + // A refused confirmation wrap ends nothing: the member is confirmed again at the next version. + let refused: Vec<&ChangeOutcome> = set + .changes + .iter() + .zip(&outcomes) + .filter(|(change, outcome)| { + change.kind.as_str() != "key.wrap" && !matches!(outcome, ChangeOutcome::Applied { .. }) + }) + .map(|(_, outcome)| outcome) + .collect(); + if refused.is_empty() { + return Ok(PushBackVerdict::Continue); + } + // The server lacks what makes this account a holder of the version before: wait for it to go back + // (0051, What cannot go back). + let waits = refused.iter().all(|outcome| { + matches!(outcome, ChangeOutcome::Rejected { code } if *code == RejectedCode::KeyDependency) + }); + if waits { + drop(model); + self.stop_team(id, StoppedCause::RestoreWait); + return Ok(PushBackVerdict::Wait { scope }); + } + let held = team(&mut model, id)?; + held.ended = true; + held.stopped_cause = None; + notice(&mut model, KeyNoticeKind::ScopeEnded { scope }); + Ok(PushBackVerdict::Ended { scope }) + } + } + } +} + +#[async_trait] +impl StopFlows for FakeKeyFlows { + async fn stop_actions(&self) -> Result, SyncError> { + let model = self.lock(); + // A restore stop is not reported: no owner's rotation can fill it (0062). + let waiting = |team: &TeamId| { + model + .teams + .get(team) + .is_some_and(|held| held.stopped_cause == Some(StoppedCause::RestoreWait)) + }; + let mut actions: Vec = model + .stop_actions + .iter() + .copied() + .filter(|action| !matches!(action, StopAction::Report { team, .. } if waiting(team))) + .collect(); + // A withdrawal settles before any new report for that team. + actions.sort_by_key(|action| matches!(action, StopAction::Report { .. })); + Ok(actions) + } + + async fn stop_action_sent(&self, action: StopAction) -> Result<(), SyncError> { + self.lock().stop_actions.retain(|held| *held != action); + Ok(()) + } + + async fn resume_withdrawal(&self, team: TeamId) -> Result<(), SyncError> { + let _ = team; + Ok(()) + } +} diff --git a/core/crates/sync/testing/src/key_flows/tests.rs b/core/crates/sync/testing/src/key_flows/tests.rs new file mode 100644 index 0000000000..459c3a6d1f --- /dev/null +++ b/core/crates/sync/testing/src/key_flows/tests.rs @@ -0,0 +1,830 @@ +use secrecy::{ExposeSecret, SecretString}; +use serde_json::json; +use tablepro_keys::KeysError; +use tablepro_keys::encoding::{AccountId, KeyDeviceId, Origin, RequestId, TeamId, Version}; +use tablepro_keys::envelope::EnvelopeId; +use tablepro_keys::keys::Ed25519Public; +use tablepro_sync::api::error::SyncError; +use tablepro_sync::api::key_flows::Acceptance; +use tablepro_sync::api::key_flows::{ + AccountDevice, AccountFlows, ApprovalFlows, ApprovalRequest, CancelWith, DeviceFlows, GenesisOutcome, KeyState, + MemberKeyStatus, RecoveryKeyDraft, ResetFlows, ResetKind, ResetState, SessionEnd, SessionPhase, StopAction, + StopFlows, TeamFlows, TypedBack, +}; +use tablepro_sync::api::scopes::Role; +use tablepro_sync::api::transport::{RejectedCode, TransportError}; +use uuid::Uuid; + +use super::{FakeKeyFlows, RESET_HOLD_US, SESSION_US, groups}; + +fn flows() -> FakeKeyFlows { + FakeKeyFlows::new( + Origin::parse("https://api.tablepro.app").unwrap(), + AccountId(Uuid::from_u128(1)), + ) +} + +fn typed(draft: &RecoveryKeyDraft) -> TypedBack { + let groups = groups(&draft.text); + TypedBack { + groups: draft + .check + .map(|index| SecretString::from(groups[usize::from(index)].to_lowercase())), + } +} + +async fn with_keys() -> FakeKeyFlows { + let flows = flows(); + let draft = flows.begin_genesis().await.unwrap(); + flows.finish_genesis(draft.draft, typed(&draft)).await.unwrap(); + flows +} + +fn envelope() -> EnvelopeId { + EnvelopeId::parse("connection/6F1C2A9E-0B4D-4C8E-9A51-3D7E2B1F0C44/password").unwrap() +} + +#[tokio::test] +async fn genesis_shows_r_and_pushes_only_once_two_groups_are_typed_back() { + let flows = flows(); + let draft = flows.begin_genesis().await.unwrap(); + let mut wrong = typed(&draft); + wrong.groups[1] = SecretString::from("ZZZZ".to_owned()); + + let refused = flows.finish_genesis(draft.draft, wrong).await; + let created = flows.finish_genesis(draft.draft, typed(&draft)).await.unwrap(); + + assert_eq!(draft.text.expose_secret().split('-').count(), 14); + assert_ne!(draft.check[0], draft.check[1]); + assert_eq!(refused.unwrap_err(), SyncError::TypedBackWrong); + assert_eq!(created, GenesisOutcome::Created); + assert!(matches!(flows.key_state().await.unwrap(), KeyState::Approved { av, .. } if av.get() == 1)); + assert!(flows.begin_genesis().await.is_err()); +} + +#[tokio::test] +async fn a_genesis_that_lost_to_another_device_asks_for_approval() { + let flows = flows(); + flows.another_device_wins_genesis(); + let draft = flows.begin_genesis().await.unwrap(); + + let outcome = flows.finish_genesis(draft.draft, typed(&draft)).await.unwrap(); + + assert_eq!(outcome, GenesisOutcome::AnotherDeviceWon); + assert!(matches!( + flows.key_state().await.unwrap(), + KeyState::NeedsApproval { .. } + )); +} + +#[tokio::test] +async fn a_new_device_s_session_runs_open_compare_approved() { + let flows = flows(); + flows.account_has_keys(); + let request = flows.request_approval().await.unwrap(); + + let open = flows.approval_session(request).await.unwrap(); + let second = flows.request_approval().await; + let early = flows.confirm_session(request).await; + flows.approver_chose(request); + let compare = flows.approval_session(request).await.unwrap(); + let approved = flows.confirm_session(request).await.unwrap(); + + assert_eq!(open.phase, SessionPhase::Open); + assert_eq!( + second.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::RequestPending + } + ); + assert_eq!(early.unwrap_err(), SyncError::Keys(KeysError::Session)); + assert!(matches!(compare.phase, SessionPhase::Compare { ref words } if words.len() == 5)); + assert_eq!(approved.phase, SessionPhase::Approved); + assert!(matches!(flows.key_state().await.unwrap(), KeyState::Approved { .. })); +} + +#[tokio::test] +async fn a_session_that_ended_takes_no_step_and_one_expires_after_ten_minutes() { + let flows = flows(); + flows.account_has_keys(); + let request = flows.request_approval().await.unwrap(); + flows.approver_chose(request); + + flows.words_differ(request).await.unwrap(); + let after = flows.confirm_session(request).await; + let ended = flows.approval_session(request).await.unwrap(); + let next = flows.request_approval().await.unwrap(); + flows.advance_clock(SESSION_US); + + assert_eq!(after.unwrap_err(), SyncError::Keys(KeysError::Session)); + assert_eq!( + ended.phase, + SessionPhase::Cancelled { + reason: SessionEnd::Mismatch + } + ); + assert_eq!(flows.approval_session(next).await.unwrap().phase, SessionPhase::Expired); +} + +#[tokio::test] +async fn an_approver_holds_a_session_unless_another_wrote_its_nonce_first() { + let flows = with_keys().await; + let now = flows.now_us(); + let mine = RequestId(Uuid::new_v4()); + let theirs = RequestId(Uuid::new_v4()); + for request in [mine, theirs] { + flows.incoming_request(ApprovalRequest { + request, + device: None, + device_name: Some("iPhone".to_owned()), + platform: Some("ios".to_owned()), + requested_at_us: now, + }); + } + flows.taken_by_another_approver(theirs); + + let listed = flows.approval_requests().await.unwrap(); + let chosen = flows.choose_request(mine).await.unwrap(); + let taken = flows.choose_request(theirs).await.unwrap(); + let done = flows.confirm_session(mine).await.unwrap(); + + assert_eq!(listed.len(), 2); + assert!(matches!(chosen.phase, SessionPhase::Compare { .. })); + assert_eq!(taken.phase, SessionPhase::TakenElsewhere); + assert_eq!(done.phase, SessionPhase::Approved); + assert!(flows.approval_requests().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn replace_needs_the_current_recovery_key_and_moves_the_account_on() { + let flows = with_keys().await; + let current = flows.recovery_key().unwrap(); + let other = tablepro_keys::recovery::RecoveryKey::generate() + .unwrap() + .to_text() + .unwrap(); + + let refused = flows.begin_replace(other).await; + let draft = flows.begin_replace(current.clone()).await.unwrap().recovery; + flows + .finish_replace(draft.draft, typed(&draft), Vec::new()) + .await + .unwrap(); + + assert!(refused.is_err()); + assert_eq!( + flows.recovery_key().unwrap().expose_secret(), + draft.text.expose_secret() + ); + assert!(matches!(flows.key_state().await.unwrap(), KeyState::Approved { av, .. } if av.get() == 2)); +} + +#[tokio::test] +async fn removing_a_device_needs_a_step_up_then_r_and_keeps_only_compared_devices() { + let flows = with_keys().await; + let lost = KeyDeviceId(Uuid::new_v4()); + let kept = KeyDeviceId(Uuid::new_v4()); + let never_compared = KeyDeviceId(Uuid::new_v4()); + for (key_device, compared) in [(lost, true), (kept, true), (never_compared, false)] { + flows.add_device(AccountDevice { + key_device, + device: None, + name: None, + platform: None, + added_at_us: None, + this_device: false, + compared, + }); + } + let row = tablepro_sync::api::ids::DeviceRowId("dev_lost".to_owned()); + + let without = flows.remove_device_row(row.clone()).await; + flows.set_step_up(true); + flows.remove_device_row(row).await.unwrap(); + let review = flows + .begin_removal(flows.recovery_key().unwrap(), vec![lost]) + .await + .unwrap(); + let by_default: Vec<_> = review + .devices + .iter() + .filter(|device| device.keep_by_default) + .map(|device| device.device.key_device) + .collect(); + let refused = flows + .finish_removal(review.review, vec![never_compared], Vec::new()) + .await; + let review = flows + .begin_removal(flows.recovery_key().unwrap(), vec![lost]) + .await + .unwrap(); + flows + .finish_removal(review.review, vec![kept], Vec::new()) + .await + .unwrap(); + + assert!(matches!( + without, + Err(SyncError::Transport(TransportError::StepUpRequired(_))) + )); + assert_eq!(by_default, [kept]); + assert_eq!(refused.unwrap_err(), SyncError::Keys(KeysError::NotCompared)); + let left: Vec<_> = flows + .account_devices() + .await + .unwrap() + .iter() + .map(|device| device.key_device) + .collect(); + assert_eq!(left, [kept]); +} + +#[tokio::test] +async fn a_reset_waits_seven_days_and_can_be_cancelled_meanwhile() { + let flows = with_keys().await; + let draft = flows.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + let pending = flows.finish_reset_proposal(draft.draft, typed(&draft)).await.unwrap(); + + let second = flows.begin_reset(ResetKind::KeepScopeKeys).await; + let early = flows.activate_reset(pending.reset).await; + flows.cancel_reset(pending.reset, CancelWith::ThisDevice).await.unwrap(); + let cancelled = flows.pending_reset().await.unwrap().unwrap(); + + assert_eq!(pending.held_until_us - pending.taken_at_us, RESET_HOLD_US); + assert_eq!( + second.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::BadStatement + } + ); + assert_eq!( + early.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::ResetHeld + } + ); + assert_eq!(cancelled.state, ResetState::Cancelled); +} + +#[tokio::test] +async fn a_reset_activates_after_its_hold_and_ends_unactivated_seven_days_later() { + let flows = with_keys().await; + let draft = flows.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + let pending = flows.finish_reset_proposal(draft.draft, typed(&draft)).await.unwrap(); + flows.advance_clock(RESET_HOLD_US); + flows.activate_reset(pending.reset).await.unwrap(); + + let later = with_keys().await; + let stale_draft = later.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + let stale = later + .finish_reset_proposal(stale_draft.draft, typed(&stale_draft)) + .await + .unwrap(); + later.advance_clock(2 * RESET_HOLD_US); + + assert_eq!(flows.pending_reset().await.unwrap().unwrap().state, ResetState::Active); + assert_eq!( + flows.recovery_key().unwrap().expose_secret(), + draft.text.expose_secret() + ); + assert!(matches!(flows.key_state().await.unwrap(), KeyState::Approved { av, .. } if av.get() == 2)); + assert_eq!( + later.pending_reset().await.unwrap().unwrap().state, + ResetState::Superseded + ); + assert!(later.activate_reset(stale.reset).await.is_err()); +} + +#[tokio::test] +async fn a_reset_that_starts_empty_comes_from_an_unapproved_sign_in_with_a_step_up() { + let approved = with_keys().await; + let unapproved = flows(); + unapproved.account_has_keys(); + + let from_approved = approved.begin_reset(ResetKind::StartEmpty).await; + let without_step_up = unapproved.begin_reset(ResetKind::StartEmpty).await; + unapproved.set_step_up(true); + let stepped_up = unapproved.begin_reset(ResetKind::StartEmpty).await; + let keep_from_sign_in = unapproved.begin_reset(ResetKind::KeepScopeKeys).await; + + assert_eq!( + from_approved.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::BadStatement + } + ); + assert!(matches!( + without_step_up, + Err(SyncError::Transport(TransportError::StepUpRequired(_))) + )); + assert!(stepped_up.is_ok()); + assert_eq!( + keep_from_sign_in.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::BadStatement + } + ); +} + +#[tokio::test] +async fn only_an_owner_or_admin_confirms_and_nothing_goes_to_a_member_under_an_alert() { + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let ana = AccountId(Uuid::from_u128(2)); + let bo = AccountId(Uuid::from_u128(3)); + flows.add_team( + team, + Role::Owner, + &[ + (ana, Role::Editor, MemberKeyStatus::AwaitingConfirmation), + (bo, Role::Member, MemberKeyStatus::NoKeys), + ], + ); + flows.create_team_keys(team).await.unwrap(); + + flows.confirm_member(team, ana).await.unwrap(); + let no_keys = flows.confirm_member(team, bo).await; + flows.raise_alert(ana); + let under_alert = flows.confirm_member(team, ana).await; + let change = flows.key_change(ana).await.unwrap().unwrap(); + let stale = Ed25519Public([9; 32]); + let wrong = flows.accept_key_change(ana, stale, Acceptance::Compared).await; + flows + .accept_key_change(ana, change.offered_ik, Acceptance::Compared) + .await + .unwrap(); + flows.confirm_member(team, ana).await.unwrap(); + + assert!(no_keys.is_err()); + assert!(under_alert.is_err()); + assert!(wrong.is_err()); + assert_ne!(change.pinned.words, change.offered.words); + assert!(flows.key_change(ana).await.unwrap().is_none()); + let keys = flows.team_keys(team).await.unwrap(); + assert_eq!(keys.version, Some(Version::new(1).unwrap())); + assert!( + keys.members + .iter() + .any(|member| member.account == ana && member.status == MemberKeyStatus::Holder) + ); +} + +#[tokio::test] +async fn a_member_rotates_only_while_due_and_an_owner_restarts_only_with_no_holder() { + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let ana = AccountId(Uuid::from_u128(2)); + flows.add_team( + team, + Role::Owner, + &[(ana, Role::Editor, MemberKeyStatus::AwaitingConfirmation)], + ); + flows.create_team_keys(team).await.unwrap(); + flows.confirm_member(team, ana).await.unwrap(); + + let restart = flows.restart_team(team, vec![ana]).await; + flows.rotate_team(team, vec![ana]).await.unwrap(); + + assert_eq!( + restart.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::Role + } + ); + let keys = flows.team_keys(team).await.unwrap(); + assert_eq!(keys.version, Some(Version::new(2).unwrap())); + assert!( + keys.members + .iter() + .all(|member| member.status == MemberKeyStatus::AwaitingConfirmation) + ); +} + +#[tokio::test] +async fn an_envelope_is_sealed_under_the_newest_version_and_never_taken_below_one_held() { + let flows = with_keys().await; + let old = flows + .seal_personal_envelope(envelope(), SecretString::from("old".to_owned()), json!({"host": "db"})) + .await + .unwrap(); + for _ in 0..2 { + let draft = flows + .begin_replace(flows.recovery_key().unwrap()) + .await + .unwrap() + .recovery; + flows + .finish_replace(draft.draft, typed(&draft), Vec::new()) + .await + .unwrap(); + } + let newest = flows + .seal_personal_envelope( + envelope(), + SecretString::from("hunter2".to_owned()), + json!({"host": "db"}), + ) + .await + .unwrap(); + + let opened = flows + .open_personal_envelope(envelope(), newest.clone(), None) + .await + .unwrap(); + let older = flows.open_personal_envelope(envelope(), old.clone(), None).await; + let in_force = Some(Version::new(2).unwrap()); + let below_in_force = flows.open_personal_envelope(envelope(), old, in_force).await; + let above_in_force = flows.open_personal_envelope(envelope(), newest, in_force).await; + + assert_eq!(opened.kv.get(), 3); + assert_eq!(opened.secret.expose_secret(), "hunter2"); + assert_eq!(opened.dest, json!({"host": "db"})); + assert!(matches!( + older, + Err(SyncError::Keys(KeysError::Stale { held: 3, offered: 1 })) + )); + assert!(matches!(below_in_force, Err(SyncError::Keys(KeysError::Stale { .. })))); + assert!(matches!(above_in_force, Err(SyncError::Keys(KeysError::Step { .. })))); +} + +#[tokio::test] +async fn a_team_envelope_waits_while_the_team_is_due_a_rotation() { + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + flows.add_team(team, Role::Owner, &[]); + flows.create_team_keys(team).await.unwrap(); + let id = EnvelopeId::parse("library_connection/6f1c2a9e-0b4d-4c8e-9a51-3d7e2b1f0c44/password").unwrap(); + flows.roster_read(team, roster(team, true)).await.unwrap(); + + let held = flows + .seal_team_envelope(team, id.clone(), SecretString::from("x".to_owned()), json!({})) + .await; + flows.rotate_team(team, Vec::new()).await.unwrap(); + let sealed = flows + .seal_team_envelope(team, id, SecretString::from("x".to_owned()), json!({})) + .await + .unwrap(); + + assert_eq!( + held.unwrap_err(), + SyncError::Rejected { + code: RejectedCode::RotationDue + } + ); + assert_eq!(sealed["kv"], json!(2)); +} + +#[tokio::test] +async fn a_withdrawal_settles_before_a_new_report_for_its_team() { + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let report = StopAction::Report { + team, + version: Version::new(5).unwrap(), + }; + let withdraw = StopAction::Withdraw { team }; + flows.queue_stop_action(report); + flows.queue_stop_action(withdraw); + + let actions = flows.stop_actions().await.unwrap(); + flows.stop_action_sent(withdraw).await.unwrap(); + + assert_eq!(actions, [withdraw, report]); + assert_eq!(flows.stop_actions().await.unwrap(), [report]); +} + +#[tokio::test] +async fn a_signed_out_device_is_a_new_device_and_offline_still_erases() { + let flows = with_keys().await; + flows.set_offline(true); + + let outcome = flows.sign_out().await.unwrap(); + + assert_eq!(outcome, tablepro_sync::api::key_flows::SignOutOutcome::ErasedOffline); + assert!(matches!( + flows.key_state().await.unwrap(), + KeyState::NeedsApproval { request: None } + )); +} + +#[tokio::test] +async fn fingerprints_are_six_words_and_their_qr_compares() { + let flows = with_keys().await; + let ana = AccountId(Uuid::from_u128(2)); + + let own = flows.own_fingerprint().await.unwrap(); + let theirs = flows.fingerprint(ana).await.unwrap(); + + assert_eq!(own.words.len(), 6); + assert!(theirs.qr.starts_with("TPF1:")); + assert!(flows.compare_qr(ana, theirs.qr.clone()).await.unwrap()); + assert!(!flows.compare_qr(ana, own.qr).await.unwrap()); +} + +#[tokio::test] +async fn a_rotation_ends_a_pending_reset_and_moves_history_to_the_new_version() { + let flows = with_keys().await; + let draft = flows.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + let pending = flows.finish_reset_proposal(draft.draft, typed(&draft)).await.unwrap(); + let again = flows.finish_reset_proposal(draft.draft, typed(&draft)).await; + + let replace = flows + .begin_replace(flows.recovery_key().unwrap()) + .await + .unwrap() + .recovery; + flows + .finish_replace(replace.draft, typed(&replace), Vec::new()) + .await + .unwrap(); + flows.advance_clock(RESET_HOLD_US); + let entry = tablepro_keys::encoding::HistoryId(Uuid::new_v4()); + let sealed = flows + .seal_history_entry(entry, json!({"query": "select 1"})) + .await + .unwrap(); + + assert!(again.is_err()); + assert_eq!( + flows.pending_reset().await.unwrap().unwrap().state, + ResetState::Superseded + ); + assert!(flows.activate_reset(pending.reset).await.is_err()); + assert_eq!(sealed["kv"], json!(2)); +} + +#[tokio::test] +async fn a_refused_push_back_of_a_version_ends_the_team_and_a_refused_confirmation_does_not() { + use tablepro_sync::api::ids::{KindName, ScopeName}; + use tablepro_sync::api::key_flows::{KeyChangeSet, PushBackVerdict, RestoreFlows}; + use tablepro_sync::api::transport::{Change, ChangeOp, ChangeOutcome, DpopKey}; + + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + flows.add_team(team, Role::Owner, &[]); + flows.create_team_keys(team).await.unwrap(); + let set = |kind: &str| KeyChangeSet { + scope: ScopeName::Team(team), + changes: vec![Change { + kind: KindName::parse(kind).unwrap(), + record_id: "x".to_owned(), + base: None, + op: ChangeOp::Delete, + }], + proof: DpopKey(std::sync::Arc::new( + tablepro_keys::keys::Ed25519Seed::generate().unwrap(), + )), + }; + let refused = || { + vec![ChangeOutcome::Rejected { + code: RejectedCode::Role, + }] + }; + + let confirmation = flows.push_back_answered(set("key.wrap"), refused()).await.unwrap(); + let version = flows.push_back_answered(set("key.version"), refused()).await.unwrap(); + + assert_eq!(confirmation, PushBackVerdict::Continue); + assert_eq!( + version, + PushBackVerdict::Ended { + scope: ScopeName::Team(team) + } + ); + assert_eq!( + flows.team_keys(team).await.unwrap().state, + tablepro_sync::api::state::KeyVersionState::Ended + ); + assert!(flows.rotate_team(team, Vec::new()).await.is_err()); +} + +#[tokio::test] +async fn a_restart_wraps_to_no_member_under_an_alert() { + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let ana = AccountId(Uuid::from_u128(2)); + flows.add_team( + team, + Role::Owner, + &[(ana, Role::Editor, MemberKeyStatus::AwaitingConfirmation)], + ); + flows.raise_alert(ana); + + flows.restart_team(team, vec![ana]).await.unwrap(); + + let keys = flows.team_keys(team).await.unwrap(); + assert!(keys.holder); + assert_eq!(keys.members[0].status, MemberKeyStatus::Alert); +} + +#[tokio::test] +async fn a_new_approval_after_sign_out_takes_a_new_key_device() { + let flows = with_keys().await; + let before = flows.key_device(); + + flows.sign_out().await.unwrap(); + + assert_ne!(flows.key_device(), before); +} + +#[tokio::test] +async fn an_offline_sign_out_leaves_the_server_s_pending_reset_alone() { + let flows = with_keys().await; + let draft = flows.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + flows.finish_reset_proposal(draft.draft, typed(&draft)).await.unwrap(); + flows.set_offline(true); + + flows.sign_out().await.unwrap(); + + assert_eq!(flows.pending_reset().await.unwrap().unwrap().state, ResetState::Pending); +} + +// A team's roster from a scopes body, decided on after a caught-up pull. +fn roster(team: TeamId, rotation_due: bool) -> tablepro_sync::api::key_flows::Roster { + use tablepro_sync::api::key_flows::{CaughtUp, Roster}; + use tablepro_sync::api::scopes::{ScopeInfo, ScopePolicies}; + use tablepro_sync::api::transport::PulledPage; + + let scope = tablepro_sync::api::ids::ScopeName::Team(team); + let info = ScopeInfo { + scope, + role: Some(Role::Owner), + horizon: 0, + epochs: Vec::new(), + writable: true, + policies: ScopePolicies::default(), + quota: None, + rotation_due, + members: Vec::new(), + stopped: Vec::new(), + approved: None, + }; + let page = PulledPage { + records: Vec::new(), + cursor: None, + changes_cursor: None, + caught_up: true, + unread: Vec::new(), + }; + Roster::of(&info, CaughtUp::from_page(scope, &page)) +} + +#[tokio::test] +async fn a_device_that_signed_out_offline_cannot_activate_its_reset() { + let flows = with_keys().await; + let draft = flows.begin_reset(ResetKind::KeepScopeKeys).await.unwrap(); + let pending = flows.finish_reset_proposal(draft.draft, typed(&draft)).await.unwrap(); + flows.set_offline(true); + flows.sign_out().await.unwrap(); + flows.advance_clock(RESET_HOLD_US); + + let activated = flows.activate_reset(pending.reset).await; + + assert!(!flows.pending_reset().await.unwrap().unwrap().mine); + assert!(activated.is_err()); +} + +#[tokio::test] +async fn only_a_catch_up_stop_is_reported_and_a_stopped_team_seals_nothing() { + use tablepro_sync::api::state::{KeyVersionState, StopClear, StoppedCause}; + + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let waiting = TeamId(Uuid::new_v4()); + for id in [team, waiting] { + flows.add_team(id, Role::Owner, &[]); + flows.create_team_keys(id).await.unwrap(); + } + let id = EnvelopeId::parse("library_connection/6f1c2a9e-0b4d-4c8e-9a51-3d7e2b1f0c44/password").unwrap(); + + flows.stop_team(team, StoppedCause::CatchUp); + flows.stop_team(waiting, StoppedCause::RestoreWait); + let sealed = flows + .seal_team_envelope(team, id, SecretString::from("x".to_owned()), json!({})) + .await; + let keys = flows.team_keys(team).await.unwrap(); + let actions = flows.stop_actions().await.unwrap(); + let wrong_clear = flows.clear_team_stop(team, StopClear::AwaitedVersionsBack); + + assert!(sealed.is_err()); + assert_eq!( + (keys.state, keys.stopped_cause), + (KeyVersionState::Stopped, Some(StoppedCause::CatchUp)) + ); + assert_eq!( + actions, + [StopAction::Report { + team, + version: Version::new(1).unwrap() + }] + ); + assert!(wrong_clear.is_err()); + flows.clear_team_stop(team, StopClear::Reconfirmed).unwrap(); + assert_eq!(flows.stop_actions().await.unwrap(), [StopAction::Withdraw { team }]); +} + +#[tokio::test] +async fn a_push_back_that_lacks_a_dependency_waits_instead_of_ending() { + use tablepro_sync::api::ids::{KindName, ScopeName}; + use tablepro_sync::api::key_flows::{KeyChangeSet, PushBackVerdict, RestoreFlows}; + use tablepro_sync::api::state::StoppedCause; + use tablepro_sync::api::transport::{Change, ChangeOp, ChangeOutcome, DpopKey}; + + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + flows.add_team(team, Role::Owner, &[]); + flows.create_team_keys(team).await.unwrap(); + let set = KeyChangeSet { + scope: ScopeName::Team(team), + changes: vec![Change { + kind: KindName::parse("key.version").unwrap(), + record_id: "x".to_owned(), + base: None, + op: ChangeOp::Delete, + }], + proof: DpopKey(std::sync::Arc::new( + tablepro_keys::keys::Ed25519Seed::generate().unwrap(), + )), + }; + + let verdict = flows + .push_back_answered( + set, + vec![ChangeOutcome::Rejected { + code: RejectedCode::KeyDependency, + }], + ) + .await + .unwrap(); + + assert_eq!( + verdict, + PushBackVerdict::Wait { + scope: ScopeName::Team(team) + } + ); + assert_eq!( + flows.team_keys(team).await.unwrap().stopped_cause, + Some(StoppedCause::RestoreWait) + ); + assert!(flows.stop_actions().await.unwrap().is_empty()); +} + +#[tokio::test] +async fn a_stop_report_can_be_confirmed_again_only_by_one_who_held_its_version() { + use tablepro_sync::api::scopes::StopReport; + + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + flows.add_team(team, Role::Owner, &[]); + flows.create_team_keys(team).await.unwrap(); + let report = |version: u32| StopReport { + account: AccountId(Uuid::from_u128(5)), + device: tablepro_sync::api::ids::DeviceRowId("dev_x".to_owned()), + version: Version::new(version).unwrap(), + }; + let mut held = roster(team, false); + held.stopped = vec![report(1), report(4)]; + + flows.roster_read(team, held).await.unwrap(); + let keys = flows.team_keys(team).await.unwrap(); + + assert!(keys.stopped[0].can_reconfirm); + assert!(!keys.stopped[1].can_reconfirm); +} + +#[tokio::test] +async fn a_held_restart_applies_only_for_the_identity_the_person_compared() { + use tablepro_sync::api::state::{KeyVersionState, StoppedCause}; + + let flows = with_keys().await; + let team = TeamId(Uuid::new_v4()); + let ana = AccountId(Uuid::from_u128(2)); + flows.add_team(team, Role::Editor, &[]); + flows.hold_restart(team, Version::new(3).unwrap(), ana); + + let held = flows.held_restart(team).await.unwrap().unwrap(); + let sealed = flows + .seal_team_envelope( + team, + EnvelopeId::parse("library_connection/6f1c2a9e-0b4d-4c8e-9a51-3d7e2b1f0c44/password").unwrap(), + SecretString::from("x".to_owned()), + json!({}), + ) + .await; + let wrong = flows.accept_restart(team, Ed25519Public([7; 32])).await; + let stopped = flows.team_keys(team).await.unwrap(); + flows.accept_restart(team, held.signer_ik).await.unwrap(); + let applied = flows.team_keys(team).await.unwrap(); + + assert_eq!(held.words.words.len(), 6); + assert!(sealed.is_err()); + assert!(wrong.is_err()); + assert_eq!(stopped.stopped_cause, Some(StoppedCause::RestartHeld)); + assert!(flows.stop_actions().await.unwrap().is_empty()); + assert_eq!( + (applied.state, applied.version), + (KeyVersionState::Ok, Some(Version::new(3).unwrap())) + ); + assert!(flows.held_restart(team).await.unwrap().is_none()); +} diff --git a/core/crates/sync/testing/src/lib.rs b/core/crates/sync/testing/src/lib.rs new file mode 100644 index 0000000000..29a40199ab --- /dev/null +++ b/core/crates/sync/testing/src/lib.rs @@ -0,0 +1,18 @@ +// Fakes of the parts the sync engine runs against, for every sync lane's tests: an in-memory `/v2/sync` server, a +// CloudKit, a device store, a state file and the key flows. Each behaves as its ADR says, which its tests show. +#![expect( + clippy::disallowed_types, + reason = "record fields compare as JSON values, as Postgres jsonb does, so member order carries nothing" +)] + +pub mod cloudkit; +pub mod device_store; +pub mod key_flows; +pub mod service; +pub mod state; + +pub use cloudkit::FakeCloudKit; +pub use device_store::FakeDeviceStore; +pub use key_flows::{FakeKeyFlows, RecordingHooks}; +pub use service::{FakeClient, FakeServer}; +pub use state::MemoryStateFiles; diff --git a/core/crates/sync/testing/src/service/mod.rs b/core/crates/sync/testing/src/service/mod.rs new file mode 100644 index 0000000000..5c8e751512 --- /dev/null +++ b/core/crates/sync/testing/src/service/mod.rs @@ -0,0 +1,480 @@ +// An in-memory `/v2/sync` server with 0051's record rules: change tags that carry the epoch, conditional writes, create +// only key kinds, change sets applied whole and never split across pages, idempotent replays, snapshots then deltas, +// epochs with their cuts, and the scopes body. It checks no signature or key-object statement: those are the real +// server's (S3K) and the hostile fake's (K7). One `FakeServer` serves many devices, each through its own `FakeClient`. + +mod pull; +mod push; +mod scopes; +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde_json::Value; +use tablepro_keys::encoding::{AccountId, TeamId}; +use tablepro_sync::api::ids::{ChangeTag, DeviceRowId, EpochId, KindName, ScopeName}; +use tablepro_sync::api::scopes::{Role, StopReport}; +use tablepro_sync::api::transport::{DeletedReason, Proof, TransportError}; +use uuid::Uuid; + +pub use pull::PAGE_BYTES; + +// Where a scope's records live: an account's personal and history scopes, or a team's. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ScopeOwner { + Personal(AccountId), + History(AccountId), + Team(TeamId), +} + +impl ScopeOwner { + pub fn of(scope: ScopeName, account: AccountId) -> Self { + match scope { + ScopeName::Personal => Self::Personal(account), + ScopeName::History => Self::History(account), + ScopeName::Team(team) => Self::Team(team), + } + } + + pub fn scope(self) -> ScopeName { + match self { + Self::Personal(_) => ScopeName::Personal, + Self::History(_) => ScopeName::History, + Self::Team(team) => ScopeName::Team(team), + } + } +} + +// A record as the server stores it (0051, `sync_records`). +#[derive(Debug, Clone, PartialEq)] +pub struct StoredRecord { + pub kind: KindName, + pub record_id: String, + pub version: u64, + pub revision: u64, + pub written_epoch: EpochId, + pub write_tag: [u8; 16], + pub fields: Option, + pub deleted: Option, + pub taken_at_us: i64, + pub updated_at_us: i64, + pub updated_device: Option, + pub updated_by: Option, +} + +impl StoredRecord { + // 0051, Change tags: format 0x01, the written epoch, the version big-endian and the write tag, base64url. + pub fn change_tag(&self) -> ChangeTag { + let mut bytes = Vec::with_capacity(41); + bytes.push(1); + bytes.extend_from_slice(self.written_epoch.0.as_bytes()); + bytes.extend_from_slice(&self.version.to_be_bytes()); + bytes.extend_from_slice(&self.write_tag); + ChangeTag::Service(URL_SAFE_NO_PAD.encode(bytes)) + } +} + +#[derive(Debug, Clone, Default)] +pub(crate) struct ScopeData { + pub(crate) records: BTreeMap<(String, String), StoredRecord>, + // Each change set's first and last revision, which a page never splits. + pub(crate) change_sets: Vec<(u64, u64)>, +} + +impl ScopeData { + pub(crate) fn horizon(&self) -> u64 { + self.records.values().map(|record| record.revision).max().unwrap_or(0) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct EpochRow { + pub(crate) id: EpochId, + // Each scope's horizon when the epoch began. + pub(crate) cuts: BTreeMap, +} + +#[derive(Debug, Clone)] +pub(crate) struct Team { + pub(crate) members: BTreeMap, + pub(crate) rotation_due: bool, + pub(crate) password_sync: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Policies { + pub personal_sync: bool, + pub password_sync: bool, + pub history_sync: bool, +} + +impl Default for Policies { + fn default() -> Self { + Self { + personal_sync: true, + password_sync: true, + history_sync: true, + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct StoredAnswer { + pub(crate) digest: [u8; 32], + // The outcome of each change that applied, by its place in the push; the others are judged again on a replay. + pub(crate) applied: Vec>, + pub(crate) created_at_us: i64, +} + +#[derive(Debug, Clone)] +pub(crate) enum CursorPhase { + Snapshot { mark: u64, after: Option<(String, String)> }, + HistoryOlder { mark: u64, before: u64 }, + Delta { after: u64 }, +} + +#[derive(Debug, Clone)] +pub(crate) struct CursorState { + pub(crate) owner: ScopeOwner, + pub(crate) epoch: EpochId, + pub(crate) phase: CursorPhase, + pub(crate) pre_approval: bool, +} + +#[derive(Debug, Clone)] +pub(crate) struct State { + pub(crate) lineage: Vec, + pub(crate) next_revision: u64, + pub(crate) scopes: BTreeMap, + pub(crate) teams: BTreeMap, + pub(crate) idempotency: HashMap<(ScopeOwner, AccountId, String), StoredAnswer>, + // Each device row's approved DSK: the key device it holds, certified at the current `av`. + pub(crate) approved: HashMap, + pub(crate) removed_rows: HashSet, + pub(crate) stopped: BTreeMap<(TeamId, DeviceRowId), StopReport>, + pub(crate) policies: Policies, + pub(crate) lapsed: bool, + // Each device row's sign-in with a fresh step-up, and the account each row belongs to. + pub(crate) stepped_up: HashSet, + pub(crate) rows: HashMap, + pub(crate) fail_next: Vec, + pub(crate) clock_us: i64, +} + +impl State { + pub(crate) fn epoch(&self) -> EpochId { + self.lineage.last().map_or(EpochId(Uuid::nil()), |epoch| epoch.id) + } + + pub(crate) fn take_revision(&mut self) -> u64 { + self.next_revision += 1; + self.next_revision + } + + fn highest_revision(&self) -> u64 { + self.scopes.values().map(ScopeData::horizon).max().unwrap_or(0) + } + + // `sync new-epoch`: a new random id, each scope's horizon as its cut, and the sequence moved 2^40 past the highest + // revision. Stop reports go with the old epoch. + pub(crate) fn open_epoch(&mut self) -> EpochId { + let id = EpochId(Uuid::new_v4()); + let start_revision = self.highest_revision().max(self.next_revision) + (1 << 40); + let cuts = self + .scopes + .iter() + .map(|(owner, data)| (*owner, data.horizon())) + .collect(); + self.lineage.push(EpochRow { id, cuts }); + self.next_revision = start_revision; + self.stopped.clear(); + id + } +} + +// A copy of the database, which `restore` puts back the way a point-in-time restore does. +#[derive(Debug, Clone)] +pub struct Backup(State); + +#[derive(Debug)] +pub struct FakeServer { + state: Mutex, + cursors: Mutex>, +} + +impl FakeServer { + pub fn new() -> Arc { + let mut state = State { + lineage: Vec::new(), + next_revision: 0, + scopes: BTreeMap::new(), + teams: BTreeMap::new(), + idempotency: HashMap::new(), + approved: HashMap::new(), + removed_rows: HashSet::new(), + stopped: BTreeMap::new(), + policies: Policies::default(), + lapsed: false, + stepped_up: HashSet::new(), + rows: HashMap::new(), + fail_next: Vec::new(), + clock_us: 1_767_225_600_000_000, + }; + state.lineage.push(EpochRow { + id: EpochId(Uuid::new_v4()), + cuts: BTreeMap::new(), + }); + Arc::new(Self { + state: Mutex::new(state), + cursors: Mutex::new(HashMap::new()), + }) + } + + pub(crate) fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub(crate) fn cursors(&self) -> MutexGuard<'_, HashMap> { + self.cursors.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn client(self: &Arc, account: AccountId, device_row: DeviceRowId) -> FakeClient { + self.lock().rows.insert(device_row.clone(), account); + FakeClient { + server: Arc::clone(self), + account, + device_row, + } + } + + pub fn epoch(&self) -> EpochId { + self.lock().epoch() + } + + pub fn lineage(&self) -> Vec<(EpochId, BTreeMap)> { + self.lock() + .lineage + .iter() + .map(|epoch| (epoch.id, epoch.cuts.clone())) + .collect() + } + + // A failover, or a restore the server detected: a new epoch over the records as they are. + pub fn new_epoch(&self) -> EpochId { + self.lock().open_epoch() + } + + pub fn backup(&self) -> Backup { + Backup(self.lock().clone()) + } + + // Puts a backup back and opens the epoch its detection opens: writes after the backup are lost, and so are the + // epoch rows the backup did not hold. + pub fn restore(&self, backup: &Backup) -> EpochId { + let mut state = self.lock(); + *state = backup.0.clone(); + state.open_epoch() + } + + pub fn add_team(&self, team: TeamId, members: &[(AccountId, Role)]) { + self.lock().teams.insert( + team, + Team { + members: members.iter().copied().collect(), + rotation_due: false, + password_sync: true, + }, + ); + } + + pub fn set_role(&self, team: TeamId, account: AccountId, role: Option) { + let mut state = self.lock(); + let Some(data) = state.teams.get_mut(&team) else { + return; + }; + match role { + Some(role) => { + data.members.insert(account, role); + } + None => { + // Removing a member marks the team `rotation_due` (0051, Removals). + data.members.remove(&account); + data.rotation_due = true; + } + } + } + + pub fn set_rotation_due(&self, team: TeamId, due: bool) { + if let Some(data) = self.lock().teams.get_mut(&team) { + data.rotation_due = due; + } + } + + // The device row holds a key device whose DSK is `dsk`, certified at the current `av`. + pub fn approve(&self, device_row: &DeviceRowId, dsk: [u8; 32]) { + self.lock().approved.insert(device_row.clone(), dsk); + } + + pub fn unapprove(&self, device_row: &DeviceRowId) { + self.lock().approved.remove(device_row); + } + + pub fn is_approved(&self, device_row: &DeviceRowId) -> bool { + self.lock().approved.contains_key(device_row) + } + + // An install admin removing the row from the portal: the row's device gets `device_removed` from then on. + pub fn remove_row(&self, device_row: &DeviceRowId) { + let mut state = self.lock(); + state.approved.remove(device_row); + state.removed_rows.insert(device_row.clone()); + state.stopped.retain(|(_, row), _| row != device_row); + } + + // Whether this row's sign-in holds a step-up within 300 s (0051, Step-up). + pub fn set_step_up(&self, device_row: &DeviceRowId, fresh: bool) { + let mut state = self.lock(); + if fresh { + state.stepped_up.insert(device_row.clone()); + } else { + state.stepped_up.remove(device_row); + } + } + + pub fn set_lapsed(&self, lapsed: bool) { + self.lock().lapsed = lapsed; + } + + // The next calls fail as given, in order, before anything else is checked. + pub fn fail_next(&self, error: TransportError) { + self.lock().fail_next.push(error); + } + + pub fn advance_clock(&self, micros: i64) { + self.lock().clock_us += micros; + } + + pub fn now_us(&self) -> i64 { + self.lock().clock_us + } + + // A switch turned off: the job tombstones what it covers with `policy` and no writer; on, nothing is revived. + pub fn set_policies(&self, policies: Policies) { + let mut state = self.lock(); + state.policies = policies; + let owners: Vec = state.scopes.keys().copied().collect(); + for owner in owners { + let ids: Vec<(String, String)> = state.scopes[&owner] + .records + .iter() + .filter(|(_, record)| record.deleted.is_none() && push::policy_refuses(&state, owner, &record.kind)) + .map(|(key, _)| key.clone()) + .collect(); + for key in ids { + let revision = state.take_revision(); + let epoch = state.epoch(); + let now = state.clock_us; + if let Some(record) = state.scopes.get_mut(&owner).and_then(|data| data.records.get_mut(&key)) { + record.version += 1; + record.revision = revision; + record.written_epoch = epoch; + record.write_tag = *Uuid::new_v4().as_bytes(); + record.deleted = Some(DeletedReason::Policy); + record.fields = None; + record.updated_at_us = now; + record.updated_device = None; + record.updated_by = None; + } + } + } + } + + pub fn stored(&self, owner: ScopeOwner, kind: &str, record_id: &str) -> Option { + self.lock() + .scopes + .get(&owner) + .and_then(|data| data.records.get(&(kind.to_owned(), record_id.to_owned()))) + .cloned() + } + + pub fn horizon(&self, owner: ScopeOwner) -> u64 { + self.lock().scopes.get(&owner).map_or(0, ScopeData::horizon) + } + + pub fn stop_reports(&self, team: TeamId) -> Vec { + self.lock() + .stopped + .iter() + .filter(|((reported, _), _)| *reported == team) + .map(|(_, report)| report.clone()) + .collect() + } +} + +// One device's sign-in against the server: its account and device row. +#[derive(Debug, Clone)] +pub struct FakeClient { + pub(crate) server: Arc, + pub account: AccountId, + pub device_row: DeviceRowId, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Approval { + NoProof, + Unapproved, + Approved, +} + +impl FakeClient { + pub fn server(&self) -> &Arc { + &self.server + } + + // The checks every call makes first: injected failures, a removed row, a seat in a team. + pub(crate) fn admit(&self, state: &mut State, scope: Option) -> Result<(), TransportError> { + if !state.fail_next.is_empty() { + return Err(state.fail_next.remove(0)); + } + if state.removed_rows.contains(&self.device_row) { + return Err(TransportError::DeviceRemoved); + } + if let Some(ScopeName::Team(team)) = scope { + let data = state.teams.get(&team).ok_or(TransportError::NotFound)?; + if !data.members.contains_key(&self.account) { + return Err(TransportError::SeatRequired); + } + } + Ok(()) + } + + pub(crate) fn approval(&self, state: &State, proof: &Proof) -> Approval { + match proof { + Proof::None => Approval::NoProof, + Proof::Dpop(key) => { + let held = state.approved.get(&self.device_row); + let public = key.0.public().ok().map(|public| public.0); + if held.is_some() && held.copied() == public { + Approval::Approved + } else { + Approval::Unapproved + } + } + } + } + + pub(crate) fn role(&self, state: &State, scope: ScopeName) -> Option { + match scope { + ScopeName::Team(team) => state + .teams + .get(&team) + .and_then(|data| data.members.get(&self.account)) + .copied(), + ScopeName::Personal | ScopeName::History => None, + } + } +} diff --git a/core/crates/sync/testing/src/service/pull.rs b/core/crates/sync/testing/src/service/pull.rs new file mode 100644 index 0000000000..dc012186f4 --- /dev/null +++ b/core/crates/sync/testing/src/service/pull.rs @@ -0,0 +1,255 @@ +// `GET /v2/sync/scopes/{scope}/changes` (0051, Pull): a snapshot up to a mark in pages, then the changes after it in +// revision order. A page with no records is caught up, and no page ends inside a change set. + +use serde_json::Value; +use tablepro_records::limits; +use tablepro_sync::api::ids::{Cursor, ScopeName}; +use tablepro_sync::api::transport::{PullRequest, PulledPage, PulledRecord, ServiceMeta, TransportError}; +use uuid::Uuid; + +use super::push::{expires_at, held_until}; +use super::{Approval, CursorPhase, CursorState, FakeClient, ScopeData, ScopeOwner, State, StoredRecord}; + +pub const PAGE_RECORDS: usize = 500; +pub const PAGE_BYTES: usize = 4 << 20; + +impl FakeClient { + pub(crate) fn pull_page(&self, request: &PullRequest) -> Result { + let mut state = self.server.lock(); + self.admit(&mut state, Some(request.scope))?; + let approval = self.approval(&state, &request.proof); + let pre_approval = match (request.scope, approval) { + (ScopeName::Team(_), _) => false, + (_, Approval::NoProof) | (ScopeName::History, Approval::Unapproved) => { + return Err(TransportError::DeviceNotApproved); + } + (ScopeName::Personal, Approval::Unapproved) => true, + (_, Approval::Approved) => false, + }; + let owner = ScopeOwner::of(request.scope, self.account); + let Some(data) = state.scopes.get(&owner).cloned() else { + return Ok(PulledPage { + records: Vec::new(), + cursor: None, + changes_cursor: None, + caught_up: true, + unread: Vec::new(), + }); + }; + let limit = request + .limit + .map_or(PAGE_RECORDS, |limit| usize::try_from(limit).unwrap_or(PAGE_RECORDS)) + .clamp(1, PAGE_RECORDS); + let phase = match &request.cursor { + None if request.scope == ScopeName::History => CursorPhase::HistoryOlder { + mark: data.horizon(), + before: u64::MAX, + }, + None => CursorPhase::Snapshot { + mark: data.horizon(), + after: None, + }, + Some(cursor) => self.resume(&state, owner, cursor, pre_approval, &data)?, + }; + let page = Page { + owner, + epoch: state.epoch(), + pre_approval, + limit, + }; + Ok(page.read(&self.server, &data, phase)) + } + + fn resume( + &self, + state: &State, + owner: ScopeOwner, + cursor: &Cursor, + pre_approval: bool, + data: &ScopeData, + ) -> Result { + let Cursor::Service(text) = cursor else { + return Err(TransportError::CursorExpired); + }; + let held = self.server.cursors().get(text).cloned(); + let Some(held) = held else { + return Err(TransportError::CursorExpired); + }; + let past_horizon = matches!(held.phase, CursorPhase::Delta { after } if after > data.horizon()); + let approved_since = held.pre_approval && !pre_approval; + if held.owner != owner || held.epoch != state.epoch() || past_horizon || approved_since { + return Err(TransportError::CursorExpired); + } + Ok(held.phase) + } +} + +struct Page { + owner: ScopeOwner, + epoch: tablepro_sync::api::ids::EpochId, + pre_approval: bool, + limit: usize, +} + +impl Page { + fn read(&self, server: &super::FakeServer, data: &ScopeData, phase: CursorPhase) -> PulledPage { + let visible = |record: &&StoredRecord| !self.pre_approval || record.kind.is_key(); + match phase { + CursorPhase::Snapshot { mark, after } => { + let rest: Vec<&StoredRecord> = data + .records + .iter() + .filter(|(key, _)| after.as_ref().is_none_or(|after| *key > after)) + .map(|(_, record)| record) + .filter(|record| record.revision <= mark) + .filter(visible) + .collect(); + if rest.is_empty() { + return self.read(server, data, CursorPhase::Delta { after: mark }); + } + let taken = self.cap(rest); + let last = taken + .last() + .map(|record| (record.kind.as_str().to_owned(), record.record_id.clone())); + let next = CursorPhase::Snapshot { mark, after: last }; + self.page(server, &taken, Some(next), None, false) + } + CursorPhase::HistoryOlder { mark, before } => { + let mut rest: Vec<&StoredRecord> = data + .records + .values() + .filter(|record| record.revision <= mark && record.revision < before) + .collect(); + rest.sort_by_key(|record| std::cmp::Reverse(record.revision)); + let taken = self.cap(rest); + let older = taken.last().map(|record| CursorPhase::HistoryOlder { + mark, + before: record.revision, + }); + let changes = CursorPhase::Delta { after: mark }; + self.page(server, &taken, older, Some(changes), false) + } + CursorPhase::Delta { after } => { + let mut rest: Vec<&StoredRecord> = data + .records + .values() + .filter(|record| record.revision > after) + .filter(visible) + .collect(); + rest.sort_by_key(|record| record.revision); + let taken = self.whole_sets(self.cap(rest.clone()), &rest, data); + let caught_up = taken.is_empty(); + let last = taken.last().map_or(after, |record| record.revision); + self.page( + server, + &taken, + Some(CursorPhase::Delta { after: last }), + None, + caught_up, + ) + } + } + } + + // At most `limit` records or 4 MiB of fields, and always one. + fn cap<'a>(&self, records: Vec<&'a StoredRecord>) -> Vec<&'a StoredRecord> { + let mut bytes = 0; + let mut taken = Vec::new(); + for record in records { + let size = record.fields.as_ref().map_or(0, limits::encoded_len); + if !taken.is_empty() && (taken.len() == self.limit || bytes + size > PAGE_BYTES) { + break; + } + bytes += size; + taken.push(record); + } + taken + } + + // A page that holds a change set's first record holds its last, past the caps if it must. + fn whole_sets<'a>( + &self, + mut taken: Vec<&'a StoredRecord>, + rest: &[&'a StoredRecord], + data: &ScopeData, + ) -> Vec<&'a StoredRecord> { + let Some(last) = taken.last().map(|record| record.revision) else { + return taken; + }; + let end = data + .change_sets + .iter() + .find(|(first, end)| *first <= last && last < *end) + .map(|(_, end)| *end); + if let Some(end) = end { + taken.extend( + rest.iter() + .filter(|record| record.revision > last && record.revision <= end), + ); + } + taken + } + + fn page( + &self, + server: &super::FakeServer, + taken: &[&StoredRecord], + next: Option, + changes: Option, + caught_up: bool, + ) -> PulledPage { + PulledPage { + records: taken.iter().map(|record| pulled(record)).collect(), + cursor: next.map(|phase| self.cursor(server, phase)), + changes_cursor: changes.map(|phase| self.cursor(server, phase)), + caught_up, + unread: Vec::new(), + } + } + + fn cursor(&self, server: &super::FakeServer, phase: CursorPhase) -> Cursor { + let text = Uuid::new_v4().simple().to_string(); + server.cursors().insert( + text.clone(), + CursorState { + owner: self.owner, + epoch: self.epoch, + phase, + pre_approval: self.pre_approval, + }, + ); + Cursor::Service(text) + } +} + +fn pulled(record: &StoredRecord) -> PulledRecord { + PulledRecord { + kind: record.kind.clone(), + record_id: record.record_id.clone(), + tag: record.change_tag(), + // `/v2/sync` sends no tombstone's fields. + fields: if record.deleted.is_some() { + None + } else { + record.fields.clone() + }, + fields_json: if record.deleted.is_some() { + None + } else { + record.fields.as_ref().map(Value::to_string) + }, + deleted: record.deleted, + service: Some(ServiceMeta { + version: record.version, + revision: record.revision, + epoch: record.written_epoch, + updated_at_us: record.updated_at_us, + taken_at_us: record.taken_at_us, + held_until_us: held_until(record), + expires_at_us: expires_at(record), + updated_by: record.updated_by.map(|account| account.to_wire()), + updated_device: record.updated_device.clone(), + updated_by_name: None, + }), + } +} diff --git a/core/crates/sync/testing/src/service/push.rs b/core/crates/sync/testing/src/service/push.rs new file mode 100644 index 0000000000..2bc3ddc484 --- /dev/null +++ b/core/crates/sync/testing/src/service/push.rs @@ -0,0 +1,669 @@ +// `POST /v2/sync/scopes/{scope}/changes` (0051, Push). + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tablepro_keys::record_id::{KeyKind, KeyRecordId}; +use tablepro_records::{kind as kinds, limits, merge_patch, record_id}; +use tablepro_sync::api::ids::{ChangeTag, KindName, ScopeName}; +use tablepro_sync::api::scopes::Role; +use tablepro_sync::api::transport::{ + AppliedStamp, Change, ChangeOp, ChangeOutcome, DeletedReason, Proof, PushAnswer, PushBatch, RejectedCode, + StoredCopy, StoredStamp, TransportError, +}; +use uuid::Uuid; + +use super::{Approval, FakeClient, ScopeOwner, State, StoredAnswer, StoredRecord}; + +const MAX_CHANGES: usize = 500; +const MAX_CHANGE_SET: usize = 10_000; +const MAX_BODY_BYTES: usize = 4 << 20; +const IDEMPOTENCY_RETENTION_US: i64 = 86_400 * 1_000_000; +const REQUEST_LIFETIME_US: i64 = 600 * 1_000_000; +const RESET_HOLD_US: i64 = 7 * 24 * 3600 * 1_000_000; + +// A switch that turns the kind off in the scope (0051, Policies). +pub(crate) fn policy_refuses(state: &State, owner: ScopeOwner, kind: &KindName) -> bool { + let name = kind.as_str(); + let policies = state.policies; + let team_password = match owner { + ScopeOwner::Team(team) => state.teams.get(&team).is_some_and(|data| !data.password_sync), + _ => false, + }; + (name == "secret_envelope" && (!policies.password_sync || team_password)) + || (name == "history_entry" && (!policies.history_sync || !policies.personal_sync)) + || (matches!(owner, ScopeOwner::Personal(_)) && !kind.is_key() && !policies.personal_sync) +} + +// The push body as the service receives it: the epoch, then each change as its JSON. Measured for the 4 MiB limit and +// hashed for idempotency, so neither depends on what stays on the device. +fn body(batch: &PushBatch) -> String { + let changes: Vec = batch + .changes + .iter() + .map(|change| { + let base = change.base.as_ref().map(|tag| match tag { + ChangeTag::Service(text) => Value::String(text.clone()), + ChangeTag::CloudKit(_) => Value::Null, + }); + match &change.op { + ChangeOp::Write { patch, .. } => json!({ + "kind": change.kind.as_str(), "record_id": change.record_id, "op": "patch", + "base_tag": base, "patch": patch, + }), + ChangeOp::Delete => json!({ + "kind": change.kind.as_str(), "record_id": change.record_id, "op": "delete", "base_tag": base, + }), + } + }) + .collect(); + json!({"epoch": batch.epoch.map(|epoch| epoch.0.to_string()), "changes": changes}).to_string() +} + +impl FakeClient { + pub(crate) fn push_batch(&self, batch: &PushBatch) -> Result { + let mut state = self.server.lock(); + self.admit(&mut state, Some(batch.scope))?; + let owner = ScopeOwner::of(batch.scope, self.account); + let key = batch.idempotency_key.as_ref().ok_or(TransportError::ValidationFailed)?; + // A push of key objects alone is judged as one change set, as each of 0051's change sets goes up alone. + let change_set = !batch.changes.is_empty() && batch.changes.iter().all(|change| change.kind.is_key()); + let limit = if change_set { MAX_CHANGE_SET } else { MAX_CHANGES }; + if batch.changes.is_empty() || batch.changes.len() > limit || named_twice(&batch.changes) { + return Err(TransportError::ValidationFailed); + } + let body = body(batch); + if body.len() > MAX_BODY_BYTES { + return Err(TransportError::Server { + status: 413, + code: "payload_too_large".to_owned(), + retry_after_ms: None, + }); + } + self.gate(&state, batch)?; + if batch.epoch != Some(state.epoch()) { + return Err(TransportError::EpochChanged); + } + let now = state.clock_us; + state + .idempotency + .retain(|_, answer| now - answer.created_at_us < IDEMPOTENCY_RETENTION_US); + let slot = (owner, self.account, key.0.clone()); + let digest: [u8; 32] = Sha256::digest(body.as_bytes()).into(); + let stored = state.idempotency.get(&slot).cloned(); + if stored.as_ref().is_some_and(|stored| stored.digest != digest) { + return Err(TransportError::IdempotencyMismatch); + } + let before = state.clone(); + let (outcomes, applied) = self.judge_all( + &mut state, + owner, + batch, + stored.as_ref(), + proof_key(&batch.proof).as_ref(), + ); + if change_set + && outcomes + .iter() + .any(|outcome| !matches!(outcome, ChangeOutcome::Applied { .. })) + { + *state = before; + return Ok(PushAnswer { + outcomes: whole_set_refused(outcomes), + }); + } + if change_set && applied.iter().any(Option::is_some) { + mark_change_set(&mut state, owner, &applied); + } + if applied.iter().any(Option::is_some) { + let mut answer = stored.unwrap_or(StoredAnswer { + digest, + applied: vec![None; applied.len()], + created_at_us: now, + }); + for (held, wrote) in answer.applied.iter_mut().zip(applied) { + if wrote.is_some() { + *held = wrote; + } + } + state.idempotency.insert(slot, answer); + } + Ok(PushAnswer { outcomes }) + } + + // Each change in the order sent. A replay answers what applied from the store, after the caller's role and every + // other check pass again, and judges the rest again. + fn judge_all( + &self, + state: &mut State, + owner: ScopeOwner, + batch: &PushBatch, + stored: Option<&StoredAnswer>, + proof: Option<&[u8; 32]>, + ) -> (Vec, Vec>) { + let mut outcomes = Vec::with_capacity(batch.changes.len()); + let mut applied = Vec::with_capacity(batch.changes.len()); + for (index, change) in batch.changes.iter().enumerate() { + let replayed = stored.and_then(|stored| stored.applied.get(index).cloned().flatten()); + let (outcome, wrote) = match replayed { + Some(outcome) => match self.authorize(state, owner, change, &binding(batch, proof)) { + Ok(()) => (outcome, false), + Err(code) => (ChangeOutcome::Rejected { code }, false), + }, + None => self.judge(state, owner, change, &binding(batch, proof)), + }; + applied.push(wrote.then(|| outcome.clone())); + outcomes.push(outcome); + } + (outcomes, applied) + } + + // Whole-push refusals: approval, a lapse and the scope's own rules before any change is judged. + fn gate(&self, state: &State, batch: &PushBatch) -> Result<(), TransportError> { + let approval = self.approval(state, &batch.proof); + let keyed = |change: &Change| change.kind.is_key() || change.kind.as_str() == "secret_envelope"; + match batch.scope { + ScopeName::Personal | ScopeName::History => { + let allowed = match approval { + Approval::Approved => true, + Approval::Unapproved => batch.scope == ScopeName::Personal && before_approval(&batch.changes), + Approval::NoProof => false, + }; + if !allowed { + return Err(TransportError::DeviceNotApproved); + } + } + ScopeName::Team(_) => { + if batch.changes.iter().any(keyed) && approval != Approval::Approved { + return Err(TransportError::DeviceNotApproved); + } + } + } + if state.lapsed && batch.changes.iter().any(|change| !change.kind.is_key()) { + return Err(TransportError::LicenseExpired); + } + Ok(()) + } + + // One change, in the order sent; the flag says whether it wrote. + fn judge( + &self, + state: &mut State, + owner: ScopeOwner, + change: &Change, + bind: &Binding<'_>, + ) -> (ChangeOutcome, bool) { + if let Err(code) = self.check(state, owner, change, bind) { + return (ChangeOutcome::Rejected { code }, false); + } + let stored = state + .scopes + .get(&owner) + .and_then(|data| { + data.records + .get(&(change.kind.as_str().to_owned(), change.record_id.clone())) + }) + .cloned(); + if change.kind.is_key() { + return self.judge_key(state, owner, change, stored); + } + match (&change.op, stored) { + (ChangeOp::Delete, None) => (applied(None), false), + (ChangeOp::Delete, Some(record)) if record.deleted.is_some() => (applied(Some(&record)), false), + (_, Some(record)) if change.base.as_ref() != Some(&record.change_tag()) => (conflict(Some(&record)), false), + (_, None) if change.base.is_some() => (conflict(None), false), + (ChangeOp::Delete, Some(record)) => self.tombstone(state, owner, record), + (ChangeOp::Write { patch, .. }, stored) => self.write(state, owner, change, patch, stored), + } + } + + fn judge_key( + &self, + state: &mut State, + owner: ScopeOwner, + change: &Change, + stored: Option, + ) -> (ChangeOutcome, bool) { + let ChangeOp::Write { patch, .. } = &change.op else { + return rejected(RejectedCode::CreateOnly); + }; + if change.base.is_some() { + return rejected(RejectedCode::CreateOnly); + } + match stored { + // The same object again, as a retry or a push-back, answers applied and writes nothing. + Some(record) if record.fields.as_ref() == Some(patch) => (applied(Some(&record)), false), + Some(_) => rejected(RejectedCode::CreateOnly), + None => self.write(state, owner, change, patch, None), + } + } + + fn check(&self, state: &State, owner: ScopeOwner, change: &Change, bind: &Binding<'_>) -> Result<(), RejectedCode> { + let kind = change.kind.as_str(); + let reserved = kinds::is_reserved(kind); + let id_fits = match change.kind.known() { + Some(known) if reserved => record_id::check(known, &change.record_id).is_ok(), + _ => record_id::well_formed(&change.record_id), + }; + if !id_fits { + return Err(RejectedCode::BadRecordId); + } + if !kinds::admits(owner.scope().records_scope(), kind) { + return Err(RejectedCode::KindNotInScope); + } + self.authorize(state, owner, change, bind)?; + if let ChangeOp::Write { patch, .. } = &change.op + && let Err(refusal) = limits::check(patch) + { + return Err(RejectedCode::parse(refusal.code())); + } + check_case(state, owner, change) + } + + // What a replay checks again before it answers from the store: the policies, the caller's role and the writer. + fn authorize( + &self, + state: &State, + owner: ScopeOwner, + change: &Change, + bind: &Binding<'_>, + ) -> Result<(), RejectedCode> { + if policy_refuses(state, owner, &change.kind) { + return Err(RejectedCode::Policy); + } + self.check_role(state, owner, &change.kind)?; + self.check_writer(change)?; + self.check_bound(state, owner, change, bind) + } + + // 0051, Roles in a team scope, without the holder checks a key object's statement carries. + fn check_role(&self, state: &State, owner: ScopeOwner, kind: &KindName) -> Result<(), RejectedCode> { + let ScopeOwner::Team(team) = owner else { + return Ok(()); + }; + let role = self.role(state, owner.scope()).ok_or(RejectedCode::Role)?; + let rotation_due = state.teams.get(&team).is_some_and(|data| data.rotation_due); + let allowed = match (role, kind.as_str()) { + (_, "key.member") | (Role::Owner | Role::Admin, _) => true, + (Role::Editor | Role::Member, "key.version" | "key.wrap" | "key.ring") => rotation_due, + (Role::Editor, name) => !name.starts_with("key."), + (Role::Member, _) => false, + }; + if allowed { Ok(()) } else { Err(RejectedCode::Role) } + } + + // A key object whose id names an account is bound to that account (0051, Writer binding). + fn check_writer(&self, change: &Change) -> Result<(), RejectedCode> { + let Ok(kind) = KeyKind::parse(change.kind.as_str()) else { + return Ok(()); + }; + let bound = KeyRecordId::parse(kind, &change.record_id) + .ok() + .and_then(|id| id.bound_account()); + match bound { + Some(account) if account != self.account.0 => Err(RejectedCode::WriterBound), + _ => Ok(()), + } + } + + // The binding 0051's table gives the rest (Writer binding): a request and its steps to their DPoP keys, a team + // version, wrap or ring to its signer. + fn check_bound( + &self, + state: &State, + owner: ScopeOwner, + change: &Change, + bind: &Binding<'_>, + ) -> Result<(), RejectedCode> { + let ChangeOp::Write { patch, .. } = &change.op else { + return Ok(()); + }; + let me = self.account.to_wire(); + let bound = match (change.kind.as_str(), owner) { + ("key.request", _) => bind.proof.is_some() && key_field(patch, "dsk") == bind.proof.copied(), + ("key.sas", _) => self.sas_bound(state, owner, change, patch, bind), + ("key.version", ScopeOwner::Team(_)) => patch.get("signer").and_then(Value::as_str) == Some(me.as_str()), + ("key.wrap", ScopeOwner::Team(_)) => patch.get("wrapper").and_then(Value::as_str) == Some(me.as_str()), + ("key.ring", ScopeOwner::Team(_)) => ring_signer(state, owner, change, bind) == Some(me), + _ => true, + }; + if bound { Ok(()) } else { Err(RejectedCode::WriterBound) } + } + + // A `nonce` step's DSK is the caller's DPoP key; a `reveal` comes from the request's; a `cancel` from either. + fn sas_bound(&self, state: &State, owner: ScopeOwner, change: &Change, patch: &Value, bind: &Binding<'_>) -> bool { + let Some(proof) = bind.proof.copied() else { + return false; + }; + let Some((request, step)) = change.record_id.rsplit_once('/') else { + return false; + }; + let stored_key = |kind: &str, id: &str| { + state + .scopes + .get(&owner) + .and_then(|data| data.records.get(&(kind.to_owned(), id.to_owned()))) + .and_then(|record| record.fields.as_ref()) + .and_then(|fields| key_field(fields, "dsk")) + }; + let requester = stored_key("key.request", request); + let approver = stored_key("key.sas", &format!("{request}/nonce")); + match step { + "nonce" => key_field(patch, "dsk") == Some(proof), + "reveal" => requester == Some(proof), + "cancel" => requester == Some(proof) || approver == Some(proof), + _ => false, + } + } + + fn write( + &self, + state: &mut State, + owner: ScopeOwner, + change: &Change, + patch: &Value, + stored: Option, + ) -> (ChangeOutcome, bool) { + let empty_patch = matches!(patch, Value::Object(members) if members.is_empty()); + if let Some(record) = &stored + && empty_patch + && record.deleted.is_none() + { + return (applied(Some(record)), false); + } + if let Some(record) = &stored + && record.deleted.is_some() + && change.kind.as_str() == "history_entry" + && record.deleted != Some(DeletedReason::Policy) + { + return rejected(RejectedCode::CreateOnly); + } + if let Some(record) = &stored + && record.deleted.is_none() + && change.kind.as_str() == "history_entry" + { + return rejected(RejectedCode::CreateOnly); + } + let base = stored + .as_ref() + .and_then(|record| record.fields.clone()) + .unwrap_or_else(|| Value::Object(Default::default())); + let fields = merge_patch::apply(&base, patch); + if let Err(refusal) = limits::check(&fields) { + return rejected(RejectedCode::parse(refusal.code())); + } + if let Err(code) = check_sealed(state, owner, change.kind.as_str(), &fields) { + return rejected(code); + } + let record = self.stamp(state, change, stored, Some(fields), None); + (self.commit(state, owner, record), true) + } + + fn tombstone(&self, state: &mut State, owner: ScopeOwner, record: StoredRecord) -> (ChangeOutcome, bool) { + // Team library tombstones keep their fields until `/v1` sunsets (0051, Tombstones). + let keep = record.kind.known().is_some_and(tablepro_records::Kind::is_team_library); + let fields = if keep { record.fields.clone() } else { None }; + let change = Change { + kind: record.kind.clone(), + record_id: record.record_id.clone(), + base: None, + op: ChangeOp::Delete, + }; + let tombstone = self.stamp(state, &change, Some(record), fields, Some(DeletedReason::User)); + (self.commit(state, owner, tombstone), true) + } + + fn stamp( + &self, + state: &mut State, + change: &Change, + stored: Option, + fields: Option, + deleted: Option, + ) -> StoredRecord { + let revision = state.take_revision(); + let now = state.clock_us; + StoredRecord { + kind: change.kind.clone(), + record_id: change.record_id.clone(), + version: stored.as_ref().map_or(1, |record| record.version + 1), + revision, + written_epoch: state.epoch(), + write_tag: *Uuid::new_v4().as_bytes(), + fields, + deleted, + taken_at_us: stored.as_ref().map_or(now, |record| record.taken_at_us), + updated_at_us: now, + updated_device: Some(self.device_row.clone()), + updated_by: Some(self.account), + } + } + + fn commit(&self, state: &mut State, owner: ScopeOwner, record: StoredRecord) -> ChangeOutcome { + let outcome = applied(Some(&record)); + state + .scopes + .entry(owner) + .or_default() + .records + .insert((record.kind.as_str().to_owned(), record.record_id.clone()), record); + outcome + } +} + +pub(crate) fn expires_at(record: &StoredRecord) -> Option { + (record.kind.as_str() == "key.request").then_some(record.taken_at_us + REQUEST_LIFETIME_US) +} + +pub(crate) fn held_until(record: &StoredRecord) -> Option { + (record.kind.as_str() == "key.reset" && record.deleted.is_none()).then_some(record.taken_at_us + RESET_HOLD_US) +} + +// What a device writes before approval (0051, Before approval): its request and that request's steps; a genesis, +// rotation or reset activation, each led by its `key.account`; a reset proposal; an IK-signed cancel. +fn before_approval(changes: &[Change]) -> bool { + let all = |kinds: &[&str]| changes.iter().all(|change| kinds.contains(&change.kind.as_str())); + let own_steps = changes.iter().all(|change| match change.kind.as_str() { + "key.request" => true, + "key.sas" => change.record_id.ends_with("/reveal") || change.record_id.ends_with("/cancel"), + _ => false, + }); + // A genesis, rotation or reset activation: one `key.account` and only the objects its change set holds. + let account_set = all(&[ + "key.account", + "key.device", + "key.recovery", + "key.version", + "key.wrap", + "key.ring", + ]) && changes + .iter() + .filter(|change| change.kind.as_str() == "key.account") + .count() + == 1; + // A cancel before approval carries the recovery key's IK signature. + let signed_cancels = all(&["key.cancel"]) + && changes + .iter() + .all(|change| matches!(&change.op, ChangeOp::Write { patch, .. } if patch.get("sig").is_some())); + own_steps || all(&["key.reset"]) || signed_cancels || account_set +} + +// What binds a change: the push's DPoP key and the push's other changes, where a ring's version record comes with it. +pub(crate) struct Binding<'a> { + pub(crate) proof: Option<&'a [u8; 32]>, + pub(crate) changes: &'a [Change], +} + +fn binding<'a>(batch: &'a PushBatch, proof: Option<&'a [u8; 32]>) -> Binding<'a> { + Binding { + proof, + changes: &batch.changes, + } +} + +pub(crate) fn proof_key(proof: &Proof) -> Option<[u8; 32]> { + match proof { + Proof::None => None, + Proof::Dpop(key) => key.0.public().ok().map(|public| public.0), + } +} + +// A 32-byte key a body carries as canonical base64url. +pub(crate) fn key_field(fields: &Value, member: &str) -> Option<[u8; 32]> { + let text = fields.get(member)?.as_str()?; + let bytes = URL_SAFE_NO_PAD.decode(text).ok()?; + bytes.try_into().ok() +} + +// A ring's signer is its version record's, from the same change set or the scope. +fn ring_signer(state: &State, owner: ScopeOwner, change: &Change, bind: &Binding<'_>) -> Option { + let in_push = bind.changes.iter().find_map(|other| match &other.op { + ChangeOp::Write { patch, .. } + if other.kind.as_str() == "key.version" && other.record_id == change.record_id => + { + patch.get("signer").and_then(Value::as_str).map(str::to_owned) + } + _ => None, + }); + in_push.or_else(|| { + state + .scopes + .get(&owner)? + .records + .get(&("key.version".to_owned(), change.record_id.clone()))? + .fields + .as_ref()? + .get("signer")? + .as_str() + .map(str::to_owned) + }) +} + +// The newest version of a scope key, from the version records the scope holds: `//`. +fn current_version(state: &State, owner: ScopeOwner, purpose: &str) -> Option { + state + .scopes + .get(&owner)? + .records + .values() + .filter(|record| record.kind.as_str() == "key.version") + .filter_map(|record| { + let mut parts = record.record_id.rsplitn(3, '/'); + let version = parts.next()?.parse::().ok()?; + (parts.next()? == purpose).then_some(version) + }) + .max() +} + +// An envelope or history entry only under its scope key's current version, and a team envelope not while the team is +// due a rotation (0051, Scopes and records; Teams). +fn check_sealed(state: &State, owner: ScopeOwner, kind: &str, fields: &Value) -> Result<(), RejectedCode> { + let (key_owner, purpose) = match (kind, owner) { + ("secret_envelope", ScopeOwner::Personal(account)) => (ScopeOwner::Personal(account), "personal"), + ("secret_envelope", ScopeOwner::Team(team)) => { + if state.teams.get(&team).is_some_and(|data| data.rotation_due) { + return Err(RejectedCode::RotationDue); + } + (ScopeOwner::Team(team), "team") + } + ("history_entry", ScopeOwner::History(account)) => (ScopeOwner::Personal(account), "history"), + _ => return Ok(()), + }; + let Some(kv) = fields.get("kv").and_then(Value::as_u64) else { + return Err(RejectedCode::KeyVersionUnknown); + }; + match current_version(state, key_owner, purpose).map(u64::from) { + Some(current) if kv < current => Err(RejectedCode::KeyVersionStale), + Some(current) if kv == current => Ok(()), + _ => Err(RejectedCode::KeyVersionUnknown), + } +} + +// No two team library records of one kind whose ids match once lower-cased, tombstones included. +fn check_case(state: &State, owner: ScopeOwner, change: &Change) -> Result<(), RejectedCode> { + let library = change.kind.known().is_some_and(tablepro_records::Kind::is_team_library); + if !library || change.base.is_some() { + return Ok(()); + } + let collides = state.scopes.get(&owner).is_some_and(|data| { + data.records.values().any(|record| { + record.kind == change.kind + && record.record_id != change.record_id + && record_id::library_ids_match(&record.record_id, &change.record_id) + }) + }); + if collides { + Err(RejectedCode::IdCaseCollision) + } else { + Ok(()) + } +} + +fn named_twice(changes: &[Change]) -> bool { + let mut seen = std::collections::HashSet::new(); + !changes + .iter() + .all(|change| seen.insert((change.kind.as_str(), change.record_id.as_str()))) +} + +fn applied(record: Option<&StoredRecord>) -> ChangeOutcome { + ChangeOutcome::Applied { + tag: record.map(StoredRecord::change_tag), + service: record.map(|record| AppliedStamp { + version: record.version, + revision: record.revision, + }), + } +} + +fn conflict(record: Option<&StoredRecord>) -> ChangeOutcome { + ChangeOutcome::Conflict { + stored: record.map(|record| StoredCopy { + tag: record.change_tag(), + tombstone: record.deleted.is_some(), + service: Some(StoredStamp { + version: record.version, + revision: record.revision, + epoch: record.written_epoch, + }), + fields: None, + }), + } +} + +fn rejected(code: RejectedCode) -> (ChangeOutcome, bool) { + (ChangeOutcome::Rejected { code }, false) +} + +// A change set applies whole or not at all: the rejected change keeps its code, every other answers `change_set`. +fn whole_set_refused(outcomes: Vec) -> Vec { + outcomes + .into_iter() + .map(|outcome| match outcome { + ChangeOutcome::Rejected { code } => ChangeOutcome::Rejected { code }, + _ => ChangeOutcome::Rejected { + code: RejectedCode::ChangeSet, + }, + }) + .collect() +} + +// The revisions the set wrote, which are consecutive since nothing else writes under the lock. +fn mark_change_set(state: &mut State, owner: ScopeOwner, wrote: &[Option]) { + let revisions: Vec = wrote + .iter() + .filter_map(|outcome| match outcome { + Some(ChangeOutcome::Applied { + service: Some(stamp), .. + }) => Some(stamp.revision), + _ => None, + }) + .collect(); + if let (Some(first), Some(last)) = (revisions.iter().min(), revisions.iter().max()) + && let Some(data) = state.scopes.get_mut(&owner) + { + data.change_sets.push((*first, *last)); + } +} diff --git a/core/crates/sync/testing/src/service/scopes.rs b/core/crates/sync/testing/src/service/scopes.rs new file mode 100644 index 0000000000..e318a11a7c --- /dev/null +++ b/core/crates/sync/testing/src/service/scopes.rs @@ -0,0 +1,260 @@ +// `GET /v2/sync/scopes`, the calls beyond pull and push, and the transport traits over them. + +use async_trait::async_trait; +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use sha2::{Digest, Sha256}; +use tablepro_keys::encoding::{TeamId, Version}; +use tablepro_sync::api::ids::{DeviceRowId, ScopeName}; +use tablepro_sync::api::scopes::{ + LineageEpoch, ScopeInfo, ScopePolicies, ScopesAnswer, ScopesBody, ServerLimits, StopReport, TeamMember, +}; +use tablepro_sync::api::transport::{ + DpopKey, Proof, PullRequest, PulledPage, PushAnswer, PushBatch, ServiceTransport, StepUpChallenge, Transport, + TransportError, +}; + +use super::{Approval, FakeClient, ScopeOwner, State}; + +pub const STEP_UP_ACR: &str = "urn:tablepro:acr:passkey"; + +impl FakeClient { + fn body(&self, state: &State, proof: &Proof) -> ScopesBody { + let approved = match self.approval(state, proof) { + Approval::NoProof => None, + approval => Some(approval == Approval::Approved), + }; + let mut scopes = vec![ + self.scope_info(state, ScopeName::Personal, approved), + self.scope_info(state, ScopeName::History, approved), + ]; + let teams = state + .teams + .iter() + .filter(|(_, team)| team.members.contains_key(&self.account)) + .map(|(team, _)| *team); + scopes.extend(teams.map(|team| self.scope_info(state, ScopeName::Team(team), None))); + ScopesBody { + epoch: state.epoch(), + scopes, + limits: ServerLimits::ADR_0051, + server_version: "fake".to_owned(), + capabilities: Vec::new(), + idempotency_retention_secs: 86_400, + poll_interval_secs: 60, + } + } + + fn scope_info(&self, state: &State, scope: ScopeName, approved: Option) -> ScopeInfo { + let owner = ScopeOwner::of(scope, self.account); + let policies = state.policies; + let (role, rotation_due, members, stopped, policies) = match scope { + ScopeName::Team(team) => { + let data = state.teams.get(&team); + let role = self.role(state, scope); + let members = data.map_or_else(Vec::new, |data| { + data.members + .iter() + .map(|(account, role)| TeamMember { + account: *account, + role: *role, + }) + .collect() + }); + let stopped = if role.is_some_and(|role| role.manages_keys()) { + team_reports(state, team) + } else { + Vec::new() + }; + let password = policies.password_sync && data.is_some_and(|data| data.password_sync); + let policies = ScopePolicies { + password_sync: Some(password), + ..ScopePolicies::default() + }; + ( + role, + data.is_some_and(|data| data.rotation_due), + members, + stopped, + policies, + ) + } + ScopeName::Personal => { + let policies = ScopePolicies { + personal_sync: Some(policies.personal_sync), + password_sync: Some(policies.password_sync), + history_sync: None, + }; + (None, false, Vec::new(), Vec::new(), policies) + } + ScopeName::History => { + let policies = ScopePolicies { + personal_sync: Some(policies.personal_sync), + password_sync: None, + history_sync: Some(policies.history_sync), + }; + (None, false, Vec::new(), Vec::new(), policies) + } + }; + ScopeInfo { + scope, + role, + horizon: state.scopes.get(&owner).map_or(0, super::ScopeData::horizon), + epochs: state + .lineage + .iter() + .map(|epoch| LineageEpoch { + id: epoch.id, + kept_revision: epoch.cuts.get(&owner).copied().unwrap_or(0), + }) + .collect(), + writable: !state.lapsed, + policies, + quota: None, + rotation_due, + members, + stopped, + approved: if matches!(scope, ScopeName::Team(_)) { + None + } else { + approved + }, + } + } + + fn stop_gate(&self, state: &mut State, team: TeamId, proof: &DpopKey) -> Result<(), TransportError> { + self.admit(state, Some(ScopeName::Team(team)))?; + if self.approval(state, &Proof::Dpop(proof.clone())) != Approval::Approved { + return Err(TransportError::DeviceNotApproved); + } + Ok(()) + } +} + +// Tombstones each pending `key.reset` of the account whose proposed device's DSK is `key`. +fn end_resets_proposed_under(state: &mut State, account: tablepro_keys::encoding::AccountId, key: &[u8; 32]) { + let owner = ScopeOwner::Personal(account); + let ids: Vec<(String, String)> = state.scopes.get(&owner).map_or_else(Vec::new, |data| { + data.records + .iter() + .filter(|(_, record)| record.kind.as_str() == "key.reset" && record.deleted.is_none()) + .filter(|(_, record)| { + record + .fields + .as_ref() + .and_then(|fields| fields.get("device")) + .and_then(|device| super::push::key_field(device, "dsk")) + == Some(*key) + }) + .map(|(id, _)| id.clone()) + .collect() + }); + for id in ids { + let revision = state.take_revision(); + let epoch = state.epoch(); + let now = state.clock_us; + if let Some(record) = state.scopes.get_mut(&owner).and_then(|data| data.records.get_mut(&id)) { + record.version += 1; + record.revision = revision; + record.written_epoch = epoch; + record.write_tag = *uuid::Uuid::new_v4().as_bytes(); + record.deleted = Some(tablepro_sync::api::transport::DeletedReason::User); + record.fields = None; + record.updated_at_us = now; + } + } +} + +fn team_reports(state: &State, team: TeamId) -> Vec { + state + .stopped + .iter() + .filter(|((reported, _), _)| *reported == team) + .map(|(_, report)| report.clone()) + .collect() +} + +#[async_trait] +impl Transport for FakeClient { + async fn pull(&self, request: PullRequest) -> Result { + self.pull_page(&request) + } + + async fn push(&self, batch: PushBatch) -> Result { + self.push_batch(&batch) + } +} + +#[async_trait] +impl ServiceTransport for FakeClient { + async fn scopes(&self, if_none_match: Option, proof: Proof) -> Result { + let mut state = self.server.lock(); + self.admit(&mut state, None)?; + let body = self.body(&state, &proof); + let digest = Sha256::digest(format!("{body:?}").as_bytes()); + let etag = format!("\"{}\"", URL_SAFE_NO_PAD.encode(digest)); + if if_none_match.as_deref() == Some(etag.as_str()) { + return Ok(ScopesAnswer::NotModified); + } + Ok(ScopesAnswer::Body { + body: Box::new(body), + etag, + }) + } + + async fn revoke_key_device(&self, proof: DpopKey) -> Result<(), TransportError> { + let mut state = self.server.lock(); + self.admit(&mut state, None)?; + // Taken from any signed-in device; it clears the row's key device only under that key device's own DSK, and + // ends a pending reset only under the DSK its `key.reset` names (0051, Sign Out). + let key = super::push::proof_key(&Proof::Dpop(proof.clone())); + if self.approval(&state, &Proof::Dpop(proof)) == Approval::Approved { + state.approved.remove(&self.device_row); + } + if let Some(key) = key { + end_resets_proposed_under(&mut state, self.account, &key); + } + Ok(()) + } + + async fn report_stopped(&self, team: TeamId, version: Version, proof: DpopKey) -> Result<(), TransportError> { + let mut state = self.server.lock(); + self.stop_gate(&mut state, team, &proof)?; + let report = StopReport { + account: self.account, + device: self.device_row.clone(), + version, + }; + state.stopped.insert((team, self.device_row.clone()), report); + Ok(()) + } + + async fn withdraw_stopped(&self, team: TeamId, proof: DpopKey) -> Result<(), TransportError> { + let mut state = self.server.lock(); + self.stop_gate(&mut state, team, &proof)?; + state.stopped.remove(&(team, self.device_row.clone())); + Ok(()) + } + + async fn remove_device_row(&self, device: DeviceRowId, proof: DpopKey) -> Result<(), TransportError> { + let mut state = self.server.lock(); + self.admit(&mut state, None)?; + if self.approval(&state, &Proof::Dpop(proof)) != Approval::Approved { + return Err(TransportError::DeviceNotApproved); + } + // Only a row of the caller's own account, and only on a sign-in with a fresh step-up. + if state.rows.get(&device) != Some(&self.account) { + return Err(TransportError::NotFound); + } + if !state.stepped_up.contains(&self.device_row) { + return Err(TransportError::StepUpRequired(StepUpChallenge { + acr_values: vec![STEP_UP_ACR.to_owned()], + max_age_secs: 300, + })); + } + state.approved.remove(&device); + state.removed_rows.insert(device.clone()); + state.stopped.retain(|(_, row), _| *row != device); + Ok(()) + } +} diff --git a/core/crates/sync/testing/src/service/tests.rs b/core/crates/sync/testing/src/service/tests.rs new file mode 100644 index 0000000000..2f2ec8a459 --- /dev/null +++ b/core/crates/sync/testing/src/service/tests.rs @@ -0,0 +1,1407 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use tablepro_keys::encoding::{AccountId, TeamId, Version}; +use tablepro_keys::keys::Ed25519Seed; +use tablepro_sync::api::ids::{ChangeTag, Cursor, DeviceRowId, IdempotencyKey, KindName, ScopeName}; +use tablepro_sync::api::scopes::{Role, ScopesAnswer}; +use tablepro_sync::api::transport::{ + Change, ChangeOp, ChangeOutcome, DeletedReason, DpopKey, Proof, PullRequest, PulledPage, PushBatch, RejectedCode, + ServiceTransport, Transport, TransportError, +}; +use uuid::Uuid; + +use super::{FakeClient, FakeServer, Policies, ScopeOwner}; + +const ACCOUNT: &str = "019A6B2E-8F3C-7D41-B2A5-6C0E9F14D7B8"; +const CONNECTION: &str = "6F1C2A9E-0B4D-4C8E-9A51-3D7E2B1F0C44"; + +struct Device { + client: FakeClient, + key: DpopKey, +} + +impl Device { + fn proof(&self) -> Proof { + Proof::Dpop(self.key.clone()) + } + + async fn push(&self, scope: ScopeName, changes: Vec) -> Result, TransportError> { + let batch = self.batch(scope, changes); + self.client.push(batch).await.map(|answer| answer.outcomes) + } + + fn batch(&self, scope: ScopeName, changes: Vec) -> PushBatch { + PushBatch { + scope, + epoch: Some(self.client.server().epoch()), + idempotency_key: Some(IdempotencyKey(Uuid::new_v4().to_string())), + changes, + proof: self.proof(), + } + } + + async fn pull(&self, scope: ScopeName, cursor: Option) -> Result { + let request = PullRequest { + scope, + cursor, + limit: None, + proof: self.proof(), + }; + self.client.pull(request).await + } + + async fn pull_all(&self, scope: ScopeName) -> (Vec, Cursor) { + let mut ids = Vec::new(); + let mut cursor = None; + loop { + let page = self.pull(scope, cursor.clone()).await.unwrap(); + ids.extend(page.records.iter().map(|record| record.record_id.clone())); + cursor = page.cursor; + if page.caught_up { + return (ids, cursor.unwrap()); + } + } + } +} + +fn account() -> AccountId { + AccountId::from_wire(ACCOUNT).unwrap() +} + +fn device(server: &Arc, row: &str, approved: bool) -> Device { + let seed = Ed25519Seed::generate().unwrap(); + let row = DeviceRowId(row.to_owned()); + if approved { + server.approve(&row, seed.public().unwrap().0); + } + Device { + client: server.client(account(), row), + key: DpopKey(Arc::new(seed)), + } +} + +fn write(kind: &str, id: &str, base: Option, fields: Value) -> Change { + Change { + kind: KindName::parse(kind).unwrap(), + record_id: id.to_owned(), + base, + op: ChangeOp::Write { + patch: fields.clone(), + fields, + }, + } +} + +fn delete(kind: &str, id: &str, base: Option) -> Change { + Change { + kind: KindName::parse(kind).unwrap(), + record_id: id.to_owned(), + base, + op: ChangeOp::Delete, + } +} + +fn tag_of(outcome: &ChangeOutcome) -> ChangeTag { + match outcome { + ChangeOutcome::Applied { tag: Some(tag), .. } => tag.clone(), + other => panic!("not applied: {other:?}"), + } +} + +fn rejected(outcome: &ChangeOutcome) -> RejectedCode { + match outcome { + ChangeOutcome::Rejected { code } => code.clone(), + other => panic!("not rejected: {other:?}"), + } +} + +fn member(av: u32) -> String { + format!("{ACCOUNT}/{av}") +} + +// A device's DSK as a key object body carries it. +fn dsk_of(device: &Device) -> String { + use base64::Engine; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(device.key.0.public().unwrap().0) +} + +// The personal and history key versions up to `upto`, each its own change set. +async fn key_versions(device: &Device, upto: u32) { + for version in 1..=upto { + for purpose in ["personal", "history"] { + let id = format!("{ACCOUNT}/{purpose}/{version}"); + let outcomes = device + .push( + ScopeName::Personal, + vec![write("key.version", &id, None, json!({"suite": "tp1"}))], + ) + .await + .unwrap(); + tag_of(&outcomes[0]); + } + } +} + +#[tokio::test] +async fn a_write_applies_only_on_the_stored_tag_and_a_create_over_a_record_conflicts() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + + let created = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, None, json!({"name": "a"}))], + ) + .await; + let tag = tag_of(&created.unwrap()[0]); + let again = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, None, json!({"name": "b"}))], + ) + .await; + let edited = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, Some(tag.clone()), json!({"name": "c"}))], + ) + .await; + let stale = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, Some(tag), json!({"name": "d"}))], + ) + .await; + + assert!(matches!(&again.unwrap()[0], ChangeOutcome::Conflict { stored: Some(stored) } if !stored.tombstone)); + assert!(matches!(&edited.unwrap()[0], ChangeOutcome::Applied { service: Some(stamp), .. } if stamp.version == 2)); + assert!( + matches!(&stale.unwrap()[0], ChangeOutcome::Conflict { stored: Some(stored) } + if stored.service.is_some_and(|stamp| stamp.version == 2) && stored.fields.is_none()) + ); + let stored = server + .stored(ScopeOwner::Personal(account()), "connection", CONNECTION) + .unwrap(); + assert_eq!(stored.fields, Some(json!({"name": "c"}))); +} + +#[tokio::test] +async fn a_delete_tombstones_and_a_patch_on_the_tombstone_s_tag_revives_it() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let created = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, None, json!({"name": "a"}))], + ) + .await; + + let deleted = mac + .push( + ScopeName::Personal, + vec![delete("connection", CONNECTION, Some(tag_of(&created.unwrap()[0])))], + ) + .await; + let tombstone_tag = tag_of(&deleted.unwrap()[0]); + let deleted_again = mac + .push(ScopeName::Personal, vec![delete("connection", CONNECTION, None)]) + .await; + let absent = mac + .push(ScopeName::Personal, vec![delete("group", CONNECTION, None)]) + .await; + let revived = mac + .push( + ScopeName::Personal, + vec![write( + "connection", + CONNECTION, + Some(tombstone_tag), + json!({"name": "b"}), + )], + ) + .await; + + assert!(matches!( + &deleted_again.unwrap()[0], + ChangeOutcome::Applied { tag: Some(_), .. } + )); + assert!(matches!( + &absent.unwrap()[0], + ChangeOutcome::Applied { + tag: None, + service: None + } + )); + tag_of(&revived.unwrap()[0]); + let stored = server + .stored(ScopeOwner::Personal(account()), "connection", CONNECTION) + .unwrap(); + assert_eq!((stored.deleted, stored.fields), (None, Some(json!({"name": "b"})))); +} + +#[tokio::test] +async fn a_tag_from_before_a_restore_never_matches_even_at_the_same_version() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let backup = server.backup(); + let lost = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, None, json!({"name": "lost"}))], + ) + .await; + let lost_tag = tag_of(&lost.unwrap()[0]); + + server.restore(&backup); + let other = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, None, json!({"name": "new"}))], + ) + .await; + let other_tag = tag_of(&other.unwrap()[0]); + let stale = mac + .push( + ScopeName::Personal, + vec![write("connection", CONNECTION, Some(lost_tag.clone()), json!({"x": 1}))], + ) + .await; + + assert_ne!(lost_tag, other_tag); + assert_eq!( + server + .stored(ScopeOwner::Personal(account()), "connection", CONNECTION) + .unwrap() + .version, + 1 + ); + assert!(matches!(&stale.unwrap()[0], ChangeOutcome::Conflict { .. })); +} + +#[tokio::test] +async fn a_push_in_another_epoch_is_refused_whole_and_an_old_cursor_expires() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + mac.push( + ScopeName::Personal, + vec![write("tag", CONNECTION, None, json!({"name": "a"}))], + ) + .await + .unwrap(); + let (_, cursor) = mac.pull_all(ScopeName::Personal).await; + let old = mac.batch(ScopeName::Personal, vec![write("group", CONNECTION, None, json!({}))]); + + server.new_epoch(); + + assert_eq!(mac.client.push(old).await.unwrap_err(), TransportError::EpochChanged); + assert_eq!( + mac.pull(ScopeName::Personal, Some(cursor)).await.unwrap_err(), + TransportError::CursorExpired + ); + let garbled = Cursor::Service("not-a-cursor".to_owned()); + assert_eq!( + mac.pull(ScopeName::Personal, Some(garbled)).await.unwrap_err(), + TransportError::CursorExpired + ); +} + +#[tokio::test] +async fn a_restore_lists_the_new_epoch_with_each_scope_s_kept_revision() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + mac.push( + ScopeName::Personal, + vec![write("tag", CONNECTION, None, json!({"name": "a"}))], + ) + .await + .unwrap(); + let kept = server.horizon(ScopeOwner::Personal(account())); + let backup = server.backup(); + let first = server.epoch(); + mac.push( + ScopeName::Personal, + vec![write("group", CONNECTION, None, json!({"name": "b"}))], + ) + .await + .unwrap(); + let lost_epoch = server.new_epoch(); + + let restored = server.restore(&backup); + + let lineage = server.lineage(); + let ids: Vec<_> = lineage.iter().map(|(id, _)| *id).collect(); + assert_eq!(ids, [first, restored]); + assert!(!ids.contains(&lost_epoch)); + assert_eq!(lineage[1].1.get(&ScopeOwner::Personal(account())), Some(&kept)); + assert!(server.horizon(ScopeOwner::Personal(account())) < (1 << 40)); + let next = mac + .push(ScopeName::Personal, vec![write("group", CONNECTION, None, json!({}))]) + .await + .unwrap(); + assert!(matches!(&next[0], ChangeOutcome::Applied { service: Some(stamp), .. } if stamp.revision > 1 << 40)); +} + +#[tokio::test] +async fn a_key_kind_is_created_once_and_the_same_object_again_writes_nothing() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let object = json!({"suite": "tp1", "x": "1"}); + let first = mac + .push( + ScopeName::Personal, + vec![write("key.account", &member(1), None, object.clone())], + ) + .await; + let revision = server.horizon(ScopeOwner::Personal(account())); + + let retry = mac + .push( + ScopeName::Personal, + vec![write("key.account", &member(1), None, object)], + ) + .await; + let other = mac + .push( + ScopeName::Personal, + vec![write("key.account", &member(1), None, json!({"suite": "tp1"}))], + ) + .await; + let patch = mac + .push( + ScopeName::Personal, + vec![write( + "key.account", + &member(1), + Some(tag_of(&first.unwrap()[0])), + json!({}), + )], + ) + .await; + let removed = mac + .push(ScopeName::Personal, vec![delete("key.account", &member(1), None)]) + .await; + + tag_of(&retry.unwrap()[0]); + assert_eq!(server.horizon(ScopeOwner::Personal(account())), revision); + assert_eq!(rejected(&other.unwrap()[0]), RejectedCode::CreateOnly); + assert_eq!(rejected(&patch.unwrap()[0]), RejectedCode::CreateOnly); + assert_eq!(rejected(&removed.unwrap()[0]), RejectedCode::CreateOnly); +} + +#[tokio::test] +async fn a_change_set_applies_whole_or_answers_change_set_for_the_rest() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let stranger = "019A6B30-1D27-7E9A-8C44-2F5B7A1E0C63/1"; + let set = vec![ + write("key.account", &member(1), None, json!({"suite": "tp1"})), + write("key.recovery", &member(1), None, json!({"suite": "tp1"})), + write("key.account", stranger, None, json!({"suite": "tp1"})), + ]; + + let outcomes = mac.push(ScopeName::Personal, set).await.unwrap(); + + assert_eq!(rejected(&outcomes[0]), RejectedCode::ChangeSet); + assert_eq!(rejected(&outcomes[1]), RejectedCode::ChangeSet); + assert_eq!(rejected(&outcomes[2]), RejectedCode::WriterBound); + assert_eq!(server.horizon(ScopeOwner::Personal(account())), 0); +} + +#[tokio::test] +async fn a_replay_answers_what_applied_and_another_body_under_the_key_is_refused() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let batch = mac.batch( + ScopeName::Personal, + vec![write("tag", CONNECTION, None, json!({"name": "a"}))], + ); + + let first = mac.client.push(batch.clone()).await.unwrap(); + let replay = mac.client.push(batch.clone()).await.unwrap(); + let mut other = batch; + other.changes = vec![write("group", CONNECTION, None, json!({}))]; + + assert_eq!(first, replay); + assert_eq!( + server + .stored(ScopeOwner::Personal(account()), "tag", CONNECTION) + .unwrap() + .version, + 1 + ); + assert_eq!( + mac.client.push(other).await.unwrap_err(), + TransportError::IdempotencyMismatch + ); +} + +#[tokio::test] +async fn a_push_that_names_a_record_twice_or_holds_too_many_changes_is_malformed() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let twice = vec![ + write("tag", CONNECTION, None, json!({})), + write("tag", CONNECTION, None, json!({})), + ]; + let many: Vec = (0..501) + .map(|_| write("tag", &Uuid::new_v4().to_string().to_uppercase(), None, json!({}))) + .collect(); + + assert_eq!( + mac.push(ScopeName::Personal, twice).await.unwrap_err(), + TransportError::ValidationFailed + ); + assert_eq!( + mac.push(ScopeName::Personal, many).await.unwrap_err(), + TransportError::ValidationFailed + ); + let mut unkeyed = mac.batch(ScopeName::Personal, vec![write("tag", CONNECTION, None, json!({}))]); + unkeyed.idempotency_key = None; + assert_eq!( + mac.client.push(unkeyed).await.unwrap_err(), + TransportError::ValidationFailed + ); +} + +#[tokio::test] +async fn a_snapshot_then_the_changes_after_its_mark_then_an_empty_page_caught_up() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let ids: Vec = (0..3).map(|_| Uuid::new_v4().to_string().to_uppercase()).collect(); + for id in &ids { + mac.push(ScopeName::Personal, vec![write("tag", id, None, json!({}))]) + .await + .unwrap(); + } + + let first = mac.pull(ScopeName::Personal, None).await.unwrap(); + let late = Uuid::new_v4().to_string().to_uppercase(); + mac.push(ScopeName::Personal, vec![write("tag", &late, None, json!({}))]) + .await + .unwrap(); + let (rest, _) = mac.pull_all(ScopeName::Personal).await; + let mut cursor = first.cursor.clone(); + let mut tail = Vec::new(); + loop { + let page = mac.pull(ScopeName::Personal, cursor).await.unwrap(); + tail.extend(page.records.iter().map(|record| record.record_id.clone())); + cursor = page.cursor; + if page.caught_up { + assert!(page.records.is_empty()); + break; + } + } + + assert!(!first.caught_up); + assert_eq!(first.records.len(), 3); + assert_eq!(tail, [late]); + assert_eq!(rest.len(), 4); +} + +#[tokio::test] +async fn a_scope_never_written_answers_an_empty_page_with_no_cursor() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + + let page = mac.pull(ScopeName::Personal, None).await.unwrap(); + + assert!(page.records.is_empty() && page.caught_up && page.cursor.is_none()); +} + +#[tokio::test] +async fn a_page_never_ends_inside_a_change_set() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + mac.push(ScopeName::Personal, vec![write("tag", CONNECTION, None, json!({}))]) + .await + .unwrap(); + let (_, cursor) = mac.pull_all(ScopeName::Personal).await; + let set: Vec = (1..=3) + .map(|av| write("key.recovery", &member(av), None, json!({"suite": "tp1"}))) + .collect(); + mac.push(ScopeName::Personal, set).await.unwrap(); + + let request = PullRequest { + scope: ScopeName::Personal, + cursor: Some(cursor), + limit: Some(1), + proof: mac.proof(), + }; + let page = mac.client.pull(request).await.unwrap(); + + assert_eq!(page.records.len(), 3); +} + +#[tokio::test] +async fn the_history_scope_pages_newest_first_with_a_cursor_for_the_changes() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + key_versions(&mac, 1).await; + let ids: Vec = (0..3).map(|_| Uuid::new_v4().to_string().to_uppercase()).collect(); + for id in &ids { + mac.push( + ScopeName::History, + vec![write("history_entry", id, None, json!({"kv": 1}))], + ) + .await + .unwrap(); + } + let request = |cursor| PullRequest { + scope: ScopeName::History, + cursor, + limit: Some(2), + proof: mac.proof(), + }; + + let newest = mac.client.pull(request(None)).await.unwrap(); + let older = mac.client.pull(request(newest.cursor.clone())).await.unwrap(); + let changes = mac.client.pull(request(newest.changes_cursor.clone())).await.unwrap(); + + let order: Vec<_> = newest + .records + .iter() + .chain(&older.records) + .map(|record| record.record_id.clone()) + .collect(); + assert_eq!(order, [ids[2].clone(), ids[1].clone(), ids[0].clone()]); + assert!(changes.caught_up && changes.records.is_empty()); +} + +#[tokio::test] +async fn a_history_entry_is_created_once() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + key_versions(&mac, 1).await; + let id = Uuid::new_v4().to_string().to_uppercase(); + let created = mac + .push( + ScopeName::History, + vec![write("history_entry", &id, None, json!({"kv": 1}))], + ) + .await; + + let patched = mac + .push( + ScopeName::History, + vec![write( + "history_entry", + &id, + Some(tag_of(&created.unwrap()[0])), + json!({"kv": 1}), + )], + ) + .await; + + assert_eq!(rejected(&patched.unwrap()[0]), RejectedCode::CreateOnly); +} + +#[tokio::test] +async fn before_approval_a_device_reads_and_writes_only_the_key_kinds_of_the_personal_scope() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + mac.push(ScopeName::Personal, vec![write("tag", CONNECTION, None, json!({}))]) + .await + .unwrap(); + mac.push( + ScopeName::Personal, + vec![write("key.account", &member(1), None, json!({"suite": "tp1"}))], + ) + .await + .unwrap(); + let new = device(&server, "dev_new", false); + + let (seen, cursor) = new.pull_all(ScopeName::Personal).await; + let data = new + .push(ScopeName::Personal, vec![write("group", CONNECTION, None, json!({}))]) + .await; + let history = new.pull(ScopeName::History, None).await; + server.approve(&new.client.device_row, new.key.0.public().unwrap().0); + + assert_eq!(seen, [member(1)]); + assert_eq!(data.unwrap_err(), TransportError::DeviceNotApproved); + assert_eq!(history.unwrap_err(), TransportError::DeviceNotApproved); + assert_eq!( + new.pull(ScopeName::Personal, Some(cursor)).await.unwrap_err(), + TransportError::CursorExpired + ); +} + +#[tokio::test] +async fn a_reserved_kind_outside_its_scopes_and_a_value_the_rules_refuse_are_rejected() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + + let outcomes = mac + .push( + ScopeName::Personal, + vec![ + write("library_folder", CONNECTION, None, json!({})), + write("tag", CONNECTION, None, json!({"password": "x"})), + ], + ) + .await + .unwrap(); + let history = mac + .push(ScopeName::History, vec![write("tag", CONNECTION, None, json!({}))]) + .await + .unwrap(); + + assert_eq!(rejected(&outcomes[0]), RejectedCode::KindNotInScope); + assert_eq!(rejected(&outcomes[1]), RejectedCode::SecretKey); + assert_eq!(rejected(&history[0]), RejectedCode::KindNotInScope); +} + +#[tokio::test] +async fn a_switch_turned_off_tombstones_with_policy_and_refuses_the_kind() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + key_versions(&mac, 1).await; + let id = format!("connection/{CONNECTION}/password"); + let sealed = json!({"suite": "tp1", "kv": 1, "nonce": "n", "ct": "c"}); + mac.push( + ScopeName::Personal, + vec![write("secret_envelope", &id, None, sealed.clone())], + ) + .await + .unwrap(); + + server.set_policies(Policies { + password_sync: false, + ..Policies::default() + }); + let refused = mac + .push(ScopeName::Personal, vec![write("secret_envelope", &id, None, sealed)]) + .await + .unwrap(); + let page = mac.pull(ScopeName::Personal, None).await.unwrap(); + let envelope = page.records.iter().find(|record| record.record_id == id).unwrap(); + + assert_eq!(rejected(&refused[0]), RejectedCode::Policy); + assert_eq!(envelope.deleted, Some(DeletedReason::Policy)); + assert_eq!(envelope.fields, None); +} + +#[tokio::test] +async fn a_team_member_writes_only_its_key_member_and_reads_without_a_proof() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Member)]); + let mac = device(&server, "dev_mac", true); + + let library = mac + .push( + ScopeName::Team(team), + vec![write("library_folder", CONNECTION, None, json!({}))], + ) + .await; + let own = mac + .push( + ScopeName::Team(team), + vec![write("key.member", &member(1), None, json!({"suite": "tp1"}))], + ) + .await; + let request = PullRequest { + scope: ScopeName::Team(team), + cursor: None, + limit: None, + proof: Proof::None, + }; + let read = mac.client.pull(request).await.unwrap(); + + assert_eq!(rejected(&library.unwrap()[0]), RejectedCode::Role); + tag_of(&own.unwrap()[0]); + assert_eq!(read.records.len(), 1); +} + +#[tokio::test] +async fn the_scopes_body_answers_not_modified_until_a_role_changes() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Editor)]); + let mac = device(&server, "dev_mac", true); + let ScopesAnswer::Body { body, etag } = mac.client.scopes(None, mac.proof()).await.unwrap() else { + panic!("no body"); + }; + + let idle = mac.client.scopes(Some(etag.clone()), mac.proof()).await.unwrap(); + server.set_role(team, account(), Some(Role::Admin)); + let changed = mac.client.scopes(Some(etag), mac.proof()).await.unwrap(); + + assert_eq!(body.scopes.len(), 3); + assert_eq!(body.scopes[0].approved, Some(true)); + assert_eq!(idle, ScopesAnswer::NotModified); + assert!(matches!(changed, ScopesAnswer::Body { body, .. } if body.scopes[2].role == Some(Role::Admin))); +} + +#[tokio::test] +async fn a_stop_report_shows_to_admins_until_withdrawn_or_a_new_epoch() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Admin)]); + let mac = device(&server, "dev_mac", true); + let version = Version::new(4).unwrap(); + + mac.client.report_stopped(team, version, mac.key.clone()).await.unwrap(); + let listed = server.stop_reports(team); + mac.client.withdraw_stopped(team, mac.key.clone()).await.unwrap(); + let withdrawn = server.stop_reports(team); + mac.client.report_stopped(team, version, mac.key.clone()).await.unwrap(); + server.new_epoch(); + + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].version, version); + assert!(withdrawn.is_empty()); + assert!(server.stop_reports(team).is_empty()); +} + +#[tokio::test] +async fn removing_a_row_needs_a_step_up_and_the_removed_device_is_told_on_every_call() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let lost = device(&server, "dev_lost", true); + + let without = mac + .client + .remove_device_row(lost.client.device_row.clone(), mac.key.clone()) + .await; + server.set_step_up(&mac.client.device_row, true); + mac.client + .remove_device_row(lost.client.device_row.clone(), mac.key.clone()) + .await + .unwrap(); + + assert!(matches!(without, Err(TransportError::StepUpRequired(challenge)) if challenge.max_age_secs == 300)); + assert_eq!( + lost.pull(ScopeName::Personal, None).await.unwrap_err(), + TransportError::DeviceRemoved + ); +} + +#[tokio::test] +async fn sign_out_s_revoke_clears_the_row_only_under_its_own_key() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let other = DpopKey(Arc::new(Ed25519Seed::generate().unwrap())); + + mac.client.revoke_key_device(other).await.unwrap(); + let kept = server.is_approved(&mac.client.device_row); + mac.client.revoke_key_device(mac.key.clone()).await.unwrap(); + + assert!(kept); + assert!(!server.is_approved(&mac.client.device_row)); +} + +#[tokio::test] +async fn past_grace_only_key_objects_are_taken() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + server.set_lapsed(true); + + let data = mac + .push(ScopeName::Personal, vec![write("tag", CONNECTION, None, json!({}))]) + .await; + let keys = mac + .push( + ScopeName::Personal, + vec![write("key.account", &member(1), None, json!({"suite": "tp1"}))], + ) + .await; + + assert_eq!(data.unwrap_err(), TransportError::LicenseExpired); + tag_of(&keys.unwrap()[0]); +} + +#[tokio::test] +async fn an_envelope_is_taken_only_under_the_current_key_version() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + key_versions(&mac, 2).await; + let id = format!("connection/{CONNECTION}/password"); + let sealed = |kv: u32| json!({"suite": "tp1", "kv": kv, "nonce": "n", "ct": "c"}); + + let stale = mac + .push( + ScopeName::Personal, + vec![write("secret_envelope", &id, None, sealed(1))], + ) + .await + .unwrap(); + let unknown = mac + .push( + ScopeName::Personal, + vec![write("secret_envelope", &id, None, sealed(3))], + ) + .await + .unwrap(); + let current = mac + .push( + ScopeName::Personal, + vec![write("secret_envelope", &id, None, sealed(2))], + ) + .await + .unwrap(); + + assert_eq!(rejected(&stale[0]), RejectedCode::KeyVersionStale); + assert_eq!(rejected(&unknown[0]), RejectedCode::KeyVersionUnknown); + tag_of(¤t[0]); +} + +#[tokio::test] +async fn a_team_envelope_is_refused_while_the_team_is_due_a_rotation() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Owner)]); + let mac = device(&server, "dev_mac", true); + let version = format!("{}/team/1", tablepro_keys::encoding::uuid_to_wire(team.0)); + let signed = mac + .push( + ScopeName::Team(team), + vec![write( + "key.version", + &version, + None, + json!({"suite": "tp1", "signer": ACCOUNT}), + )], + ) + .await + .unwrap(); + tag_of(&signed[0]); + server.set_rotation_due(team, true); + let id = format!("library_connection/{}/password", CONNECTION.to_lowercase()); + + let held = mac + .push( + ScopeName::Team(team), + vec![write("secret_envelope", &id, None, json!({"suite": "tp1", "kv": 1}))], + ) + .await + .unwrap(); + + assert_eq!(rejected(&held[0]), RejectedCode::RotationDue); +} + +#[tokio::test] +async fn a_team_library_id_that_matches_another_once_lower_cased_is_refused() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Editor)]); + let mac = device(&server, "dev_mac", true); + let lower = CONNECTION.to_lowercase(); + mac.push( + ScopeName::Team(team), + vec![write("library_folder", &lower, None, json!({"name": "a"}))], + ) + .await + .unwrap(); + + let upper = mac + .push( + ScopeName::Team(team), + vec![write("library_folder", CONNECTION, None, json!({"name": "b"}))], + ) + .await; + + assert_eq!(rejected(&upper.unwrap()[0]), RejectedCode::IdCaseCollision); +} + +#[tokio::test] +async fn a_replay_checks_the_role_again_and_answers_expire_after_a_day() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Editor)]); + let mac = device(&server, "dev_mac", true); + let batch = mac.batch( + ScopeName::Team(team), + vec![write("library_folder", CONNECTION, None, json!({"name": "a"}))], + ); + mac.client.push(batch.clone()).await.unwrap(); + + server.set_role(team, account(), Some(Role::Member)); + let demoted = mac.client.push(batch.clone()).await.unwrap(); + server.set_role(team, account(), Some(Role::Editor)); + server.advance_clock(86_400 * 1_000_000); + let expired = mac.client.push(batch).await.unwrap(); + + assert_eq!(rejected(&demoted.outcomes[0]), RejectedCode::Role); + assert!(matches!(&expired.outcomes[0], ChangeOutcome::Conflict { .. })); +} + +#[tokio::test] +async fn a_body_over_four_mebibytes_is_refused_whole() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let big = "x".repeat(900 * 1024); + let changes: Vec = (0..5) + .map(|_| { + write( + "tag", + &Uuid::new_v4().to_string().to_uppercase(), + None, + json!({"name": big}), + ) + }) + .collect(); + + let refused = mac.push(ScopeName::Personal, changes).await; + + assert!(matches!(refused, Err(TransportError::Server { status: 413, .. }))); + assert_eq!(server.horizon(ScopeOwner::Personal(account())), 0); +} + +#[tokio::test] +async fn before_approval_a_lone_device_certificate_is_refused() { + let server = FakeServer::new(); + let new = device(&server, "dev_new", false); + let certificate = format!("{ACCOUNT}/DB09A1EA-A519-42FF-94F3-CEEE6232F1C2/1"); + + let lone = new + .push( + ScopeName::Personal, + vec![write("key.device", &certificate, None, json!({"suite": "tp1"}))], + ) + .await; + let request = new + .push( + ScopeName::Personal, + vec![write( + "key.request", + "5E2C8B14-7A3D-4F61-9B08-C4D2E6F1A357", + None, + json!({"suite": "tp1", "dsk": dsk_of(&new)}), + )], + ) + .await; + + assert_eq!(lone.unwrap_err(), TransportError::DeviceNotApproved); + tag_of(&request.unwrap()[0]); +} + +#[tokio::test] +async fn a_row_of_another_account_cannot_be_removed_and_a_removed_row_cannot_revoke() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let stranger = server.client(AccountId(Uuid::from_u128(5)), DeviceRowId("dev_other".to_owned())); + let lost = device(&server, "dev_lost", true); + server.set_step_up(&mac.client.device_row, true); + + let other = mac + .client + .remove_device_row(stranger.device_row.clone(), mac.key.clone()) + .await; + mac.client + .remove_device_row(lost.client.device_row.clone(), mac.key.clone()) + .await + .unwrap(); + + assert_eq!(other.unwrap_err(), TransportError::NotFound); + assert_eq!( + lost.client.revoke_key_device(lost.key.clone()).await.unwrap_err(), + TransportError::DeviceRemoved + ); +} + +#[tokio::test] +async fn a_pulled_record_names_the_account_that_wrote_it() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + mac.push( + ScopeName::Personal, + vec![write("tag", CONNECTION, None, json!({"name": "a"}))], + ) + .await + .unwrap(); + + let page = mac.pull(ScopeName::Personal, None).await.unwrap(); + let meta = page.records[0].service.clone().unwrap(); + + assert_eq!(meta.updated_by.as_deref(), Some(ACCOUNT)); + assert_eq!(page.records[0].fields_json.as_deref(), Some(r#"{"name":"a"}"#)); +} + +#[tokio::test] +async fn before_approval_a_genesis_carries_no_plaintext_and_a_nonce_step_is_refused() { + let server = FakeServer::new(); + let new = device(&server, "dev_new", false); + let request = "5E2C8B14-7A3D-4F61-9B08-C4D2E6F1A357"; + + let mixed = new + .push( + ScopeName::Personal, + vec![ + write("key.account", &member(1), None, json!({"suite": "tp1"})), + write("tag", CONNECTION, None, json!({})), + ], + ) + .await; + let nonce = new + .push( + ScopeName::Personal, + vec![write( + "key.sas", + &format!("{request}/nonce"), + None, + json!({"suite": "tp1"}), + )], + ) + .await; + new.push( + ScopeName::Personal, + vec![write( + "key.request", + request, + None, + json!({"suite": "tp1", "dsk": dsk_of(&new)}), + )], + ) + .await + .unwrap(); + let reveal = new + .push( + ScopeName::Personal, + vec![write( + "key.sas", + &format!("{request}/reveal"), + None, + json!({"suite": "tp1"}), + )], + ) + .await; + + assert_eq!(mixed.unwrap_err(), TransportError::DeviceNotApproved); + assert_eq!(nonce.unwrap_err(), TransportError::DeviceNotApproved); + tag_of(&reveal.unwrap()[0]); +} + +#[tokio::test] +async fn an_envelope_patch_that_keeps_an_old_version_is_refused() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + key_versions(&mac, 1).await; + let id = format!("connection/{CONNECTION}/password"); + let created = mac + .push( + ScopeName::Personal, + vec![write( + "secret_envelope", + &id, + None, + json!({"suite": "tp1", "kv": 1, "ct": "a"}), + )], + ) + .await + .unwrap(); + key_versions_from(&mac, 2).await; + + let kept = mac + .push( + ScopeName::Personal, + vec![write( + "secret_envelope", + &id, + Some(tag_of(&created[0])), + json!({"ct": "b"}), + )], + ) + .await + .unwrap(); + + assert_eq!(rejected(&kept[0]), RejectedCode::KeyVersionStale); +} + +async fn key_versions_from(device: &Device, version: u32) { + for purpose in ["personal", "history"] { + let id = format!("{ACCOUNT}/{purpose}/{version}"); + let outcomes = device + .push( + ScopeName::Personal, + vec![write("key.version", &id, None, json!({"suite": "tp1"}))], + ) + .await + .unwrap(); + tag_of(&outcomes[0]); + } +} + +#[tokio::test] +async fn an_admin_s_roster_carries_the_stop_reports_into_its_team_keys() { + use tablepro_sync::api::key_flows::{CaughtUp, Roster, TeamFlows}; + + use crate::key_flows::FakeKeyFlows; + + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + let editor = AccountId(Uuid::from_u128(5)); + server.add_team(team, &[(account(), Role::Admin), (editor, Role::Editor)]); + let admin = device(&server, "dev_admin", true); + let stopped_seed = Ed25519Seed::generate().unwrap(); + let stopped_row = DeviceRowId("dev_stopped".to_owned()); + server.approve(&stopped_row, stopped_seed.public().unwrap().0); + let stopped = server.client(editor, stopped_row.clone()); + let version = Version::new(6).unwrap(); + stopped + .report_stopped(team, version, DpopKey(Arc::new(stopped_seed))) + .await + .unwrap(); + + let ScopesAnswer::Body { body, .. } = admin.client.scopes(None, admin.proof()).await.unwrap() else { + panic!("no body"); + }; + let info = body + .scopes + .iter() + .find(|scope| scope.scope == ScopeName::Team(team)) + .unwrap(); + let page = admin.pull(ScopeName::Team(team), None).await.unwrap(); + let roster = Roster::of(info, CaughtUp::from_page(ScopeName::Team(team), &page)); + let flows = FakeKeyFlows::new( + tablepro_keys::encoding::Origin::parse("https://api.tablepro.app").unwrap(), + account(), + ); + flows.add_team(team, Role::Admin, &[]); + flows.roster_read(team, roster.clone()).await.unwrap(); + let keys = flows.team_keys(team).await.unwrap(); + + assert_eq!(roster.stopped.len(), 1); + assert_eq!(keys.stopped[0].device, stopped_row); + assert_eq!(keys.stopped[0].version, version); + assert_eq!(keys.stopped[0].account, editor); +} + +#[tokio::test] +async fn an_editor_s_roster_carries_no_stop_reports() { + use tablepro_sync::api::key_flows::{CaughtUp, Roster}; + + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Editor)]); + let editor = device(&server, "dev_editor", true); + editor + .client + .report_stopped(team, Version::new(2).unwrap(), editor.key.clone()) + .await + .unwrap(); + + let ScopesAnswer::Body { body, .. } = editor.client.scopes(None, editor.proof()).await.unwrap() else { + panic!("no body"); + }; + let info = body + .scopes + .iter() + .find(|scope| scope.scope == ScopeName::Team(team)) + .unwrap(); + + let page = editor.pull(ScopeName::Team(team), None).await.unwrap(); + let roster = Roster::of(info, CaughtUp::from_page(ScopeName::Team(team), &page)); + + assert!(roster.caught_up()); + assert!(roster.stopped.is_empty()); + assert_eq!(server.stop_reports(team).len(), 1); +} + +#[tokio::test] +async fn a_roster_is_decided_only_with_a_caught_up_pull_of_its_own_team() { + use tablepro_sync::api::key_flows::{CaughtUp, Roster}; + + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + let other = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Editor)]); + server.add_team(other, &[(account(), Role::Editor)]); + let mac = device(&server, "dev_mac", true); + mac.push( + ScopeName::Team(team), + vec![write("library_folder", CONNECTION, None, json!({"name": "a"}))], + ) + .await + .unwrap(); + let ScopesAnswer::Body { body, .. } = mac.client.scopes(None, mac.proof()).await.unwrap() else { + panic!("no body"); + }; + let info = body + .scopes + .iter() + .find(|scope| scope.scope == ScopeName::Team(team)) + .unwrap(); + + let first = mac.pull(ScopeName::Team(team), None).await.unwrap(); + let elsewhere = mac.pull(ScopeName::Team(other), None).await.unwrap(); + + assert!(CaughtUp::from_page(ScopeName::Team(team), &first).is_none()); + assert!(!Roster::of(info, None).caught_up()); + assert!(!Roster::of(info, CaughtUp::from_page(ScopeName::Team(other), &elsewhere)).caught_up()); +} + +#[tokio::test] +async fn a_cancel_before_approval_needs_the_recovery_key_s_signature() { + let server = FakeServer::new(); + let new = device(&server, "dev_new", false); + let id = format!("{ACCOUNT}/8A41C3E2-5B6D-4F7A-9C10-2E3D4B5A6F78"); + + let unsigned = new + .push( + ScopeName::Personal, + vec![write("key.cancel", &id, None, json!({"suite": "tp1"}))], + ) + .await; + let signed = new + .push( + ScopeName::Personal, + vec![write("key.cancel", &id, None, json!({"suite": "tp1", "sig": "s"}))], + ) + .await; + + assert_eq!(unsigned.unwrap_err(), TransportError::DeviceNotApproved); + tag_of(&signed.unwrap()[0]); +} + +#[tokio::test] +async fn a_request_and_its_steps_are_bound_to_their_dpop_keys() { + let server = FakeServer::new(); + let new = device(&server, "dev_new", false); + let mac = device(&server, "dev_mac", true); + let request = "5E2C8B14-7A3D-4F61-9B08-C4D2E6F1A357"; + let step = |name: &str| format!("{request}/{name}"); + + let foreign = new + .push( + ScopeName::Personal, + vec![write( + "key.request", + request, + None, + json!({"suite": "tp1", "dsk": dsk_of(&mac)}), + )], + ) + .await + .unwrap(); + new.push( + ScopeName::Personal, + vec![write( + "key.request", + request, + None, + json!({"suite": "tp1", "dsk": dsk_of(&new)}), + )], + ) + .await + .unwrap(); + let nonce_wrong = mac + .push( + ScopeName::Personal, + vec![write( + "key.sas", + &step("nonce"), + None, + json!({"suite": "tp1", "dsk": dsk_of(&new)}), + )], + ) + .await + .unwrap(); + let nonce = mac + .push( + ScopeName::Personal, + vec![write( + "key.sas", + &step("nonce"), + None, + json!({"suite": "tp1", "dsk": dsk_of(&mac)}), + )], + ) + .await + .unwrap(); + let reveal_by_approver = mac + .push( + ScopeName::Personal, + vec![write("key.sas", &step("reveal"), None, json!({"suite": "tp1"}))], + ) + .await + .unwrap(); + + assert_eq!(rejected(&foreign[0]), RejectedCode::WriterBound); + assert_eq!(rejected(&nonce_wrong[0]), RejectedCode::WriterBound); + tag_of(&nonce[0]); + assert_eq!(rejected(&reveal_by_approver[0]), RejectedCode::WriterBound); +} + +#[tokio::test] +async fn a_team_version_wrap_and_ring_are_bound_to_their_signer() { + let server = FakeServer::new(); + let team = TeamId(Uuid::new_v4()); + server.add_team(team, &[(account(), Role::Owner)]); + let mac = device(&server, "dev_mac", true); + let owner = tablepro_keys::encoding::uuid_to_wire(team.0); + let stranger = "019A6B30-1D27-7E9A-8C44-2F5B7A1E0C63"; + + let as_other = mac + .push( + ScopeName::Team(team), + vec![write( + "key.version", + &format!("{owner}/team/1"), + None, + json!({"suite": "tp1", "signer": stranger}), + )], + ) + .await + .unwrap(); + let set = mac + .push( + ScopeName::Team(team), + vec![ + write( + "key.version", + &format!("{owner}/team/2"), + None, + json!({"suite": "tp1", "signer": ACCOUNT}), + ), + write("key.ring", &format!("{owner}/team/2"), None, json!({"suite": "tp1"})), + ], + ) + .await + .unwrap(); + let wrap = format!("{owner}/team/2/account/{ACCOUNT}/1"); + let wrapped_as_other = mac + .push( + ScopeName::Team(team), + vec![write( + "key.wrap", + &wrap, + None, + json!({"suite": "tp1", "wrapper": stranger}), + )], + ) + .await + .unwrap(); + + assert_eq!(rejected(&as_other[0]), RejectedCode::WriterBound); + tag_of(&set[0]); + tag_of(&set[1]); + assert_eq!(rejected(&wrapped_as_other[0]), RejectedCode::WriterBound); +} + +#[tokio::test] +async fn sign_out_under_a_reset_s_dsk_ends_that_reset() { + let server = FakeServer::new(); + let mac = device(&server, "dev_mac", true); + let other = device(&server, "dev_other", true); + let reset = format!("{ACCOUNT}/8A41C3E2-5B6D-4F7A-9C10-2E3D4B5A6F78"); + let body = json!({"suite": "tp1", "device": {"suite": "tp1", "dsk": dsk_of(&mac)}}); + mac.push(ScopeName::Personal, vec![write("key.reset", &reset, None, body)]) + .await + .unwrap(); + + other.client.revoke_key_device(other.key.clone()).await.unwrap(); + let kept = server + .stored(ScopeOwner::Personal(account()), "key.reset", &reset) + .unwrap() + .deleted; + mac.client.revoke_key_device(mac.key.clone()).await.unwrap(); + let ended = server + .stored(ScopeOwner::Personal(account()), "key.reset", &reset) + .unwrap() + .deleted; + + assert_eq!(kept, None); + assert_eq!(ended, Some(DeletedReason::User)); +} diff --git a/core/crates/sync/testing/src/state/mod.rs b/core/crates/sync/testing/src/state/mod.rs new file mode 100644 index 0000000000..5912cce6c6 --- /dev/null +++ b/core/crates/sync/testing/src/state/mod.rs @@ -0,0 +1,216 @@ +// A state file in memory: one per identity, refusing none it was not made for, with transactions that commit whole +// and raise the counter, and an `Opened` a test sets to stand for what an anchor check found. It computes no MAC and +// keeps no anchor; those are the real file's (K6a-1, K6d). + +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use async_trait::async_trait; +use tablepro_sync::api::error::StateError; +use tablepro_sync::api::ids::FileId; +use tablepro_sync::api::state::{ + BindingRow, Committed, Opened, Provider, Row, RowKey, RowRange, StateFiles, StateIdentity, StateStore, StateTxn, + Table, +}; +use uuid::Uuid; + +type Rows = BTreeMap<(Table, Vec), Row>; + +#[derive(Debug, Default)] +pub struct MemoryStateFiles { + files: Mutex>>, + opened: Mutex>, +} + +impl MemoryStateFiles { + pub fn new() -> Self { + Self::default() + } + + // What the next open of this identity reports, as a stale or unanchored file would. + pub fn set_opened(&self, identity: StateIdentity, opened: Opened) { + lock(&self.opened).insert(identity, opened); + } + + pub fn exists(&self, identity: &StateIdentity) -> bool { + lock(&self.files).contains_key(identity) + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn binding(identity: &StateIdentity) -> BindingRow { + let (provider, origin, account, device) = match identity { + StateIdentity::Service { + origin, + account, + device_row, + .. + } => ( + Provider::Service, + Some(origin.clone()), + account.to_wire(), + device_row.0.clone(), + ), + StateIdentity::ICloud { user_record_name } => (Provider::ICloud, None, user_record_name.clone(), String::new()), + }; + BindingRow { + provider, + origin, + account, + device, + schema_version: 1, + file_id: FileId(*Uuid::new_v4().as_bytes()), + counter: 0, + state_mac: [0; 32], + } +} + +#[async_trait] +impl StateFiles for MemoryStateFiles { + async fn open(&self, identity: StateIdentity) -> Result, StateError> { + let opened = lock(&self.opened).remove(&identity).unwrap_or(Opened::FRESH); + let mut files = lock(&self.files); + let file = files + .entry(identity.clone()) + .or_insert_with(|| { + let mut rows = Rows::new(); + rows.insert((Table::Binding, Vec::new()), Row::Binding(binding(&identity))); + Arc::new(MemoryState { + identity: identity.clone(), + opened: opened.clone(), + rows: Arc::new(Mutex::new(rows)), + }) + }) + .clone(); + let reopened = MemoryState { + identity: file.identity.clone(), + opened, + rows: Arc::clone(&file.rows), + }; + Ok(Arc::new(reopened)) + } + + async fn delete(&self, identity: StateIdentity) -> Result<(), StateError> { + lock(&self.files).remove(&identity); + Ok(()) + } +} + +#[derive(Debug)] +pub struct MemoryState { + identity: StateIdentity, + opened: Opened, + rows: Arc>, +} + +#[async_trait] +impl StateStore for MemoryState { + fn identity(&self) -> &StateIdentity { + &self.identity + } + + fn opened(&self) -> &Opened { + &self.opened + } + + async fn begin(&self) -> Result, StateError> { + let view = lock(&self.rows).clone(); + Ok(Box::new(MemoryTxn { + rows: Arc::clone(&self.rows), + view, + writes: Vec::new(), + })) + } +} + +#[derive(Debug)] +enum Write { + Put(Box), + Delete(RowKey), + ClearKeyTables, +} + +#[derive(Debug)] +struct MemoryTxn { + rows: Arc>, + // The rows as this transaction sees them, its own writes included. + view: Rows, + writes: Vec, +} + +fn slot(key: &RowKey) -> (Table, Vec) { + (key.table(), key.encoded()) +} + +fn apply(rows: &mut Rows, write: &Write) { + match write { + Write::Put(row) => { + rows.insert(slot(&row.key()), Row::clone(row)); + } + Write::Delete(key) => { + rows.remove(&slot(key)); + } + Write::ClearKeyTables => rows.retain(|(table, _), _| !table.is_key_table()), + } +} + +#[async_trait] +impl StateTxn for MemoryTxn { + async fn get(&mut self, key: &RowKey) -> Result, StateError> { + Ok(self.view.get(&slot(key)).cloned()) + } + + async fn scan(&mut self, range: &RowRange) -> Result, StateError> { + let prefix = range.encoded_prefix(); + Ok(self + .view + .iter() + .filter(|((table, key), _)| *table == range.table() && key.starts_with(&prefix)) + .map(|(_, row)| row.clone()) + .collect()) + } + + async fn put(&mut self, row: Row) -> Result<(), StateError> { + let write = Write::Put(Box::new(row)); + apply(&mut self.view, &write); + self.writes.push(write); + Ok(()) + } + + async fn delete(&mut self, key: &RowKey) -> Result<(), StateError> { + let write = Write::Delete(key.clone()); + apply(&mut self.view, &write); + self.writes.push(write); + Ok(()) + } + + async fn clear_key_tables(&mut self) -> Result<(), StateError> { + apply(&mut self.view, &Write::ClearKeyTables); + self.writes.push(Write::ClearKeyTables); + Ok(()) + } + + // On a copy, published only once it is whole, so a refused commit leaves the file as it was. + async fn commit(self: Box) -> Result { + let mut rows = lock(&self.rows); + let mut next = rows.clone(); + for write in &self.writes { + apply(&mut next, write); + } + let Some(Row::Binding(binding)) = next.get_mut(&(Table::Binding, Vec::new())) else { + return Err(StateError::Integrity); + }; + binding.counter += 1; + let committed = Committed { + counter: binding.counter, + }; + *rows = next; + Ok(committed) + } +} + +#[cfg(test)] +mod tests; diff --git a/core/crates/sync/testing/src/state/tests.rs b/core/crates/sync/testing/src/state/tests.rs new file mode 100644 index 0000000000..8c4ca05283 --- /dev/null +++ b/core/crates/sync/testing/src/state/tests.rs @@ -0,0 +1,174 @@ +use tablepro_keys::encoding::{AccountId, Origin, Version}; +use tablepro_keys::keys::Ed25519Public; +use tablepro_keys::trust::PinHow; +use tablepro_records::Kind; +use tablepro_sync::api::ids::{ChangeTag, DeviceRowId, RecordKey, ScopeName}; +use tablepro_sync::api::state::{ + BaseRow, KeyPinRow, KeyTrust, Opened, Row, RowKey, RowRange, ScopeRow, StateFiles, StateIdentity, SyncTrust, Table, +}; +use uuid::Uuid; + +use super::MemoryStateFiles; + +fn identity(account: u128) -> StateIdentity { + StateIdentity::Service { + origin: Origin::parse("https://api.tablepro.app").unwrap(), + sign_in: "sign-in".to_owned(), + account: AccountId(Uuid::from_u128(account)), + device_row: DeviceRowId("dev_a".to_owned()), + } +} + +fn base(id: &str) -> Row { + Row::Base(BaseRow { + key: RecordKey::new(ScopeName::Personal, Kind::Connection, id), + tag: ChangeTag::Service("t".to_owned()), + version: Some(1), + revision: Some(1), + epoch: None, + deleted: None, + fields: None, + created_ms: None, + }) +} + +fn pin() -> Row { + Row::KeyPin(KeyPinRow { + account: AccountId(Uuid::nil()), + ik: Ed25519Public([1; 32]), + av: Version::new(1).unwrap(), + how: PinHow::FirstUse, + alert: false, + replaced: Vec::new(), + }) +} + +#[tokio::test] +async fn a_commit_lands_whole_and_raises_the_counter() { + let files = MemoryStateFiles::new(); + let store = files.open(identity(1)).await.unwrap(); + let mut txn = store.begin().await.unwrap(); + txn.put(base("A")).await.unwrap(); + txn.put(Row::Scope(ScopeRow::new(ScopeName::Personal))).await.unwrap(); + + let before = store + .begin() + .await + .unwrap() + .scan(&RowRange::Table(Table::Bases)) + .await + .unwrap(); + let committed = txn.commit().await.unwrap(); + let after = store + .begin() + .await + .unwrap() + .scan(&RowRange::Table(Table::Bases)) + .await + .unwrap(); + + assert!(before.is_empty()); + assert_eq!(after, [base("A")]); + assert_eq!(committed.counter, 1); +} + +#[tokio::test] +async fn a_transaction_dropped_uncommitted_writes_nothing() { + let files = MemoryStateFiles::new(); + let store = files.open(identity(1)).await.unwrap(); + { + let mut txn = store.begin().await.unwrap(); + txn.put(base("A")).await.unwrap(); + assert!(txn.get(&base("A").key()).await.unwrap().is_some()); + } + + let mut txn = store.begin().await.unwrap(); + + assert!(txn.get(&base("A").key()).await.unwrap().is_none()); +} + +#[tokio::test] +async fn each_identity_opens_its_own_file() { + let files = MemoryStateFiles::new(); + let first = files.open(identity(1)).await.unwrap(); + let mut txn = first.begin().await.unwrap(); + txn.put(base("A")).await.unwrap(); + txn.commit().await.unwrap(); + + let other = files.open(identity(2)).await.unwrap(); + let again = files.open(identity(1)).await.unwrap(); + + assert!( + other + .begin() + .await + .unwrap() + .get(&base("A").key()) + .await + .unwrap() + .is_none() + ); + assert!( + again + .begin() + .await + .unwrap() + .get(&base("A").key()) + .await + .unwrap() + .is_some() + ); + files.delete(identity(1)).await.unwrap(); + assert!(!files.exists(&identity(1))); +} + +#[tokio::test] +async fn clearing_the_key_tables_keeps_the_sync_tables() { + let files = MemoryStateFiles::new(); + let store = files.open(identity(1)).await.unwrap(); + let mut txn = store.begin().await.unwrap(); + txn.put(base("A")).await.unwrap(); + txn.put(pin()).await.unwrap(); + txn.commit().await.unwrap(); + + let mut txn = store.begin().await.unwrap(); + txn.clear_key_tables().await.unwrap(); + txn.commit().await.unwrap(); + + let mut txn = store.begin().await.unwrap(); + assert!(txn.get(&pin().key()).await.unwrap().is_none()); + assert!(txn.get(&base("A").key()).await.unwrap().is_some()); + assert!(txn.get(&RowKey::Binding).await.unwrap().is_some()); +} + +#[tokio::test] +async fn an_open_reports_what_the_test_set_for_it() { + let files = MemoryStateFiles::new(); + let stale = Opened { + sync_tables: SyncTrust::Refill, + key_tables: KeyTrust::Unanchored, + }; + files.set_opened(identity(1), stale.clone()); + + let first = files.open(identity(1)).await.unwrap(); + let second = files.open(identity(1)).await.unwrap(); + + assert_eq!(first.opened(), &stale); + assert_eq!(second.opened(), &Opened::FRESH); +} + +#[tokio::test] +async fn a_refused_commit_writes_nothing() { + let files = MemoryStateFiles::new(); + let store = files.open(identity(1)).await.unwrap(); + let mut txn = store.begin().await.unwrap(); + txn.put(base("A")).await.unwrap(); + txn.delete(&RowKey::Binding).await.unwrap(); + + let refused = txn.commit().await; + + let mut txn = store.begin().await.unwrap(); + assert!(refused.is_err()); + assert!(txn.get(&base("A").key()).await.unwrap().is_none()); + assert!(txn.get(&RowKey::Binding).await.unwrap().is_some()); +} diff --git a/scripts/ci/detect-changed-paths.sh b/scripts/ci/detect-changed-paths.sh index 37e33f761e..4e2e2065cc 100755 --- a/scripts/ci/detect-changed-paths.sh +++ b/scripts/ci/detect-changed-paths.sh @@ -24,6 +24,11 @@ cd "$(git rev-parse --show-toplevel)" SKIP="" KEEP="" +# Test-only paths of the core the apps link: the sync fakes, the key vectors with their script and fuzz targets, and +# the records' fixtures. +CORE_TEST_ONLY='core/crates/sync/testing/|core/crates/keys/(vectors|fuzz|scripts)/|core/crates/records/fixtures/' +# The keys' cargo-fuzz project is its own workspace, which no distribution build reads. +FUZZ='core/crates/keys/fuzz/' case "$SUITE" in macos) PATTERNS=('apple/TablePro/' 'apple/TableProTests/' 'apple/TableProUITests/' 'apple/TestPlans/' @@ -38,7 +43,7 @@ case "$SUITE" in 'core/' 'Cargo\.(toml|lock)$' 'rust-toolchain\.toml$' 'apple/scripts/build-core\.sh$') # No driver, test or doc of the core is in the app's library. The app's tests run the script corpus, the # model merge cases and the source list cases the core's tests run. - SKIP='core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\.md$' + SKIP="core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\\.md\$|$CORE_TEST_ONLY" KEEP='core/crates/core/tests/fixtures/sql_script_corpus\.json$|core/crates/ai/tests/model-merge-cases\.json$|core/crates/foreign-import/tests/fixtures/source_list\.json$' ;; plugins) # Registry plugins link the TableProCore and TableProOracle products. @@ -64,7 +69,7 @@ case "$SUITE" in 'core/resources/Chinook\.sqlite$' # The app links the core's FFI crate without the engines, as the Mac app does. 'core/' 'Cargo\.(toml|lock)$' 'rust-toolchain\.toml$' 'apple/scripts/build-core\.sh$') - SKIP='core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\.md$' + SKIP="core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\\.md\$|$CORE_TEST_ONLY" KEEP='core/crates/core/tests/fixtures/(state_changing_functions|sql_script_corpus)\.json$' # The iOS project compiles files from Plugins/, Packages/ and TablePro/, so every path its # spec reaches outside TableProMobile/ is read from the spec instead of copied here. @@ -91,7 +96,7 @@ case "$SUITE" in 'apple/scripts/ci/verify-plugin-loads\.sh$' 'scripts/ci/detect-changed-paths\.sh$' '\.github/actions/(setup-xcode(gen)?|prepare-build)/' '\.github/workflows/(ci|nightly)\.yml$' 'core/' 'Cargo\.(toml|lock)$' 'rust-toolchain\.toml$' 'apple/scripts/build-core\.sh$') - SKIP='apple/Plugins/[^/]+Tests/|apple/Packages/[^/]+/Tests/|core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\.md$' + SKIP="apple/Plugins/[^/]+Tests/|apple/Packages/[^/]+/Tests/|core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\\.md\$|$CORE_TEST_ONLY" # shipped is what an X.Y.0 may not change after its newest beta: the release build minus its CI. if [ "$SUITE" = shipped ]; then KEPT=() @@ -123,7 +128,8 @@ case "$SUITE" in PATTERNS=('Cargo\.(toml|lock)$' '(linux|core)/(.*/)?Cargo\.toml$' '(rust-toolchain|deny)\.toml$' 'linux/build-aux/flatpak/' 'linux/build-aux/debian/control$' 'linux/build-aux/packaging/add-rust-toolchain-ppa\.sh$' 'scripts/ci/detect-changed-paths\.sh$' - '\.github/workflows/(ci|build-linux)\.yml$') ;; + '\.github/workflows/(ci|build-linux)\.yml$') + SKIP="$FUZZ" ;; packages) # The clean distribution builds: what declares a build or runtime dependency, how the build runs and installs, # and the packaging itself. A source change alone builds no package. @@ -132,7 +138,7 @@ case "$SUITE" in 'linux/meson\.(build|options)$' 'linux/(.*/)?meson\.build$' 'linux/po/LINGUAS$' 'scripts/ci/detect-changed-paths\.sh$' '\.github/workflows/(ci|linux-packages)\.yml$' '\.github/actions/linux-package-disk/') - SKIP='linux/.*\.md$' ;; + SKIP="linux/.*\\.md\$|$FUZZ" ;; core) # core.yml: the core on Windows and macOS, and its Swift bindings, which take the deployment target from # apple/project.yml. A change to linux/ alone runs none of it. diff --git a/scripts/ci/test_detect_changed_paths.py b/scripts/ci/test_detect_changed_paths.py index 10627dd16f..7c91c2c5df 100644 --- a/scripts/ci/test_detect_changed_paths.py +++ b/scripts/ci/test_detect_changed_paths.py @@ -485,6 +485,64 @@ def test_the_apple_apps_skip_the_core_they_do_not_link(self): with self.subTest(path=path, suite=suite): self.assertEqual(self.verdict_after(suite, path), "false") + def test_every_app_runs_on_the_sync_crates_the_core_builds(self): + spec = self.repo / "apple/TableProMobile/project.yml" + spec.parent.mkdir(parents=True) + spec.write_text("sources:\n - path: ../Packages/TableProCore\n", encoding="utf-8") + self.seed = self.commit([]) + for path in [ + "core/crates/sync/src/api/transport.rs", + "core/crates/sync/Cargo.toml", + "core/crates/keys/src/lib.rs", + "core/crates/records/src/lib.rs", + "core/crates/cloud-api/src/lib.rs", + ]: + for suite in ["macos", "ios", "release", "shipped", "linux", "core", "windows"]: + with self.subTest(path=path, suite=suite): + self.assertEqual(self.verdict_after(suite, path), "true") + + def test_the_apple_apps_skip_the_sync_fakes_and_the_key_vectors(self): + spec = self.repo / "apple/TableProMobile/project.yml" + spec.parent.mkdir(parents=True) + spec.write_text("sources:\n - path: ../Packages/TableProCore\n", encoding="utf-8") + self.seed = self.commit([]) + for path in [ + "core/crates/sync/testing/src/lib.rs", + "core/crates/sync/testing/Cargo.toml", + "core/crates/keys/vectors/encoding.json", + "core/crates/keys/fuzz/fuzz_targets/bodies.rs", + "core/crates/keys/scripts/update-vectors.sh", + "core/crates/records/fixtures/merge.json", + ]: + for suite in ["macos", "ios", "release", "shipped"]: + with self.subTest(path=path, suite=suite): + self.assertEqual(self.verdict_after(suite, path), "false") + for suite in ["linux", "core", "windows"]: + with self.subTest(path=path, suite=suite): + self.assertEqual(self.verdict_after(suite, path), "true") + + def test_the_package_builds_skip_the_keys_fuzz_project(self): + for path in ["core/crates/keys/fuzz/Cargo.toml", "core/crates/keys/fuzz/Cargo.lock"]: + for suite in ["linux-deps", "packages"]: + with self.subTest(path=path, suite=suite): + self.assertEqual(self.verdict_after(suite, path), "false") + for suite in ["linux-deps", "packages"]: + with self.subTest(suite=suite): + self.assertEqual(self.verdict_after(suite, "core/crates/sync/Cargo.toml"), "true") + + def test_the_sync_swift_folders_run_their_apps(self): + spec = self.repo / "apple/TableProMobile/project.yml" + spec.parent.mkdir(parents=True) + spec.write_text("sources:\n - path: ../Packages/TableProCore\n", encoding="utf-8") + self.seed = self.commit([]) + transport = "apple/Packages/TableProCore/Sources/TableProSyncTransport/CloudKitTransport.swift" + for suite in ["macos", "ios", "release"]: + with self.subTest(suite=suite): + self.assertEqual(self.verdict_after(suite, transport), "true") + self.assertEqual(self.verdict_after("macos", "apple/TablePro/Views/Sync/Keys/AccountKeysView.swift"), "true") + self.assertEqual(self.verdict_after("ios", "apple/TableProMobile/TableProMobile/Sync/Keys/KeysView.swift"), "true") + self.assertEqual(self.verdict_after("core", "apple/Packages/TableProFFI/Tests/SyncTransportTests.swift"), "true") + def test_the_mac_app_runs_on_the_ai_model_catalog_it_bundles(self): catalog = "core/crates/ai/ai-models.json" for suite in ["macos", "release", "shipped", "linux", "core", "windows"]: diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 05b114a758..69102bf734 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -833,6 +833,70 @@ public delegate void UniffiCallbackInterfaceHostPrompterMethod0( public delegate void UniffiCallbackInterfaceRunListenerMethod0( ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostDeviceStoreMethod0( + ulong @uniffiHandle,RustBuffer @item,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostDeviceStoreMethod1( + ulong @uniffiHandle,RustBuffer @item,RustBuffer @value,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostDeviceStoreMethod2( + ulong @uniffiHandle,RustBuffer @item,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostSettingsMethod0( + ulong @uniffiHandle,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostSettingsMethod1( + ulong @uniffiHandle,RustBuffer @category,RustBuffer @document,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostLegacyMirrorMethod0( + ulong @uniffiHandle,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostLegacyMirrorMethod1( + ulong @uniffiHandle,RustBuffer @metadata,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostLegacyMirrorMethod2( + ulong @uniffiHandle,RustBuffer @dirty,RustBuffer @tombstones,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceSyncListenerMethod0( + ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceSyncListenerMethod1( + ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod0( + ulong @uniffiHandle,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod1( + ulong @uniffiHandle,RustBuffer @account,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod2( + ulong @uniffiHandle,RustBuffer @account,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod3( + ulong @uniffiHandle,RustBuffer @account,RustBuffer @token,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod4( + ulong @uniffiHandle,RustBuffer @account,RustBuffer @names,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceCloudKitTransportMethod5( + ulong @uniffiHandle,RustBuffer @account,RustBuffer @saves,RustBuffer @deletes,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback + ); [StructLayout(LayoutKind.Sequential)] public struct UniffiVTableCallbackInterfaceAccountListener { @@ -908,6 +972,199 @@ public struct UniffiVTableCallbackInterfaceRunListener public IntPtr @uniffiClone; public IntPtr @eventsPending; } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceHostDeviceStore + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @load; + public IntPtr @store; + public IntPtr @delete; + } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceHostSettings + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @categories; + public IntPtr @apply; + } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceHostLegacyMirror + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @read; + public IntPtr @write; + public IntPtr @mark; + } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceSyncListener + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @statusChanged; + public IntPtr @keysChanged; + } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceCloudKitTransport + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @accountStatus; + public IntPtr @ensureZone; + public IntPtr @deleteZone; + public IntPtr @fetchChanges; + public IntPtr @fetchRecords; + public IntPtr @modify; + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1554,15 +1811,20 @@ static _UniFFILib() { _UniFFILib.uniffiCheckContractApiVersion(); _UniFFILib.uniffiCheckApiChecksums(); + UniffiCallbackInterfaceCloudKitTransport.Register(); UniffiCallbackInterfaceAccountListener.Register(); UniffiCallbackInterfaceAiReplyListener.Register(); UniffiCallbackInterfaceHostBrowser.Register(); + UniffiCallbackInterfaceHostDeviceStore.Register(); + UniffiCallbackInterfaceHostLegacyMirror.Register(); UniffiCallbackInterfaceHostPrompter.Register(); UniffiCallbackInterfaceHostSecrets.Register(); + UniffiCallbackInterfaceHostSettings.Register(); UniffiCallbackInterfaceHostWebAuthenticator.Register(); UniffiCallbackInterfaceMcpAppHost.Register(); UniffiCallbackInterfaceMcpListener.Register(); UniffiCallbackInterfaceRunListener.Register(); + UniffiCallbackInterfaceSyncListener.Register(); } #if NET8_0_OR_GREATER @@ -2346,6 +2608,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_method_core_mcp_server(ulong @ptr,ulong @host,ulong @listener,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_core_open_sync(ulong @ptr,RustBuffer @config,ulong @account,RustBuffer @cloudkit,RustBuffer @settings,RustBuffer @deviceStore,RustBuffer @legacyMirror,ulong @listener,ref UniffiRustCallStatus _uniffi_out_err + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -4609,7 +4882,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_clone_tablefolderstore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_clone_cloudkittransport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -4620,7 +4893,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_free_tablefolderstore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_free_cloudkittransport(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -4631,7 +4904,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_create(ulong @ptr,RustBuffer @connectionId,RustBuffer @database,RustBuffer @schema,RustBuffer @name + void uniffi_tablepro_ffi_fn_init_callback_vtable_cloudkittransport(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceCloudKitTransport*/ @vtable ); #if NET8_0_OR_GREATER @@ -4642,7 +4915,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_delete(ulong @ptr,RustBuffer @id + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_account_status(ulong @ptr ); #if NET8_0_OR_GREATER @@ -4653,7 +4926,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_file(ulong @ptr,RustBuffer @connectionId,RustBuffer @tables,RustBuffer @folderId + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_ensure_zone(ulong @ptr,RustBuffer @account ); #if NET8_0_OR_GREATER @@ -4664,7 +4937,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_folders(ulong @ptr,RustBuffer @connectionId + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_delete_zone(ulong @ptr,RustBuffer @account ); #if NET8_0_OR_GREATER @@ -4675,7 +4948,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_items(ulong @ptr,RustBuffer @connectionId + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_fetch_changes(ulong @ptr,RustBuffer @account,RustBuffer @token ); #if NET8_0_OR_GREATER @@ -4686,7 +4959,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_put(ulong @ptr,RustBuffer @folder + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_fetch_records(ulong @ptr,RustBuffer @account,RustBuffer @names ); #if NET8_0_OR_GREATER @@ -4697,7 +4970,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_rename(ulong @ptr,RustBuffer @id,RustBuffer @name + ulong uniffi_tablepro_ffi_fn_method_cloudkittransport_modify(ulong @ptr,RustBuffer @account,RustBuffer @saves,RustBuffer @deletes ); #if NET8_0_OR_GREATER @@ -4708,7 +4981,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_unfile(ulong @ptr,RustBuffer @connectionId,RustBuffer @tables + ulong uniffi_tablepro_ffi_fn_clone_syncservice(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -4719,7 +4992,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable + void uniffi_tablepro_ffi_fn_free_syncservice(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -4730,7 +5003,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_accept_key_change(ulong @ptr,RustBuffer @account,RustBuffer @offeredIk,sbyte @compared ); #if NET8_0_OR_GREATER @@ -4741,7 +5014,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostwebauthenticator(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostWebAuthenticator*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_accept_team_restart(ulong @ptr,RustBuffer @team,RustBuffer @signerIk ); #if NET8_0_OR_GREATER @@ -4752,7 +5025,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_aireplylistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAiReplyListener*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_account_devices(ulong @ptr ); #if NET8_0_OR_GREATER @@ -4763,7 +5036,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_account_fingerprint(ulong @ptr,RustBuffer @account ); #if NET8_0_OR_GREATER @@ -4774,7 +5047,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_mcpapphost(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceMcpAppHost*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_account_key_change(ulong @ptr,RustBuffer @account ); #if NET8_0_OR_GREATER @@ -4785,7 +5058,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_mcplistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceMcpListener*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_activate_reset(ulong @ptr,RustBuffer @reset ); #if NET8_0_OR_GREATER @@ -4796,7 +5069,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_approval_requests(ulong @ptr ); #if NET8_0_OR_GREATER @@ -4807,7 +5080,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable + ulong uniffi_tablepro_ffi_fn_method_syncservice_approval_session(ulong @ptr,RustBuffer @request ); #if NET8_0_OR_GREATER @@ -4818,7 +5091,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_personal_sync_choices(RustBuffer @policy,RustBuffer @offered,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_approval_words_differ(ulong @ptr,RustBuffer @request ); #if NET8_0_OR_GREATER @@ -4829,7 +5102,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_settled_sync_provider(RustBuffer @policy,RustBuffer @offered,RustBuffer @current,sbyte @tableproSyncAvailable,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_begin_device_removal(ulong @ptr,RustBuffer @recoveryKey,RustBuffer @lost ); #if NET8_0_OR_GREATER @@ -4840,7 +5113,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_begin_genesis(ulong @ptr ); #if NET8_0_OR_GREATER @@ -4851,7 +5124,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_begin_replace_recovery_key(ulong @ptr,RustBuffer @recoveryKey ); #if NET8_0_OR_GREATER @@ -4862,7 +5135,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_begin_reset(ulong @ptr,RustBuffer @kind ); #if NET8_0_OR_GREATER @@ -4873,7 +5146,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_ai_action_message(RustBuffer @action,RustBuffer @statement,RustBuffer @error,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_cancel_approval_session(ulong @ptr,RustBuffer @request ); #if NET8_0_OR_GREATER @@ -4884,7 +5157,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte uniffi_tablepro_ffi_fn_func_ai_address_is_valid(RustBuffer @address,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_cancel_reset(ulong @ptr,RustBuffer @reset,RustBuffer @recoveryKey ); #if NET8_0_OR_GREATER @@ -4895,7 +5168,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_ai_host_of(RustBuffer @settings,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_choose_approval_request(ulong @ptr,RustBuffer @request ); #if NET8_0_OR_GREATER @@ -4906,7 +5179,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_ai_providers(ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_compare_fingerprint_qr(ulong @ptr,RustBuffer @account,RustBuffer @text ); #if NET8_0_OR_GREATER @@ -4917,7 +5190,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_parse_app_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_confirm_approval_session(ulong @ptr,RustBuffer @request ); #if NET8_0_OR_GREATER @@ -4928,7 +5201,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_format_sql(RustBuffer @text,RustBuffer @grammar,uint @caret,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_confirm_member(ulong @ptr,RustBuffer @team,RustBuffer @account ); #if NET8_0_OR_GREATER @@ -4939,7 +5212,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_format_sql_selection(RustBuffer @text,RustBuffer @grammar,uint @start,uint @end,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_create_team_keys(ulong @ptr,RustBuffer @team ); #if NET8_0_OR_GREATER @@ -4950,7 +5223,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_credentials_to_rotate(ulong @ptr,RustBuffer @scope ); #if NET8_0_OR_GREATER @@ -4961,7 +5234,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_keymap_preset(RustBuffer @id,RustBuffer @platform,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_dismiss_key_notice(ulong @ptr,RustBuffer @notice ); #if NET8_0_OR_GREATER @@ -4972,7 +5245,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_keymap_presets(RustBuffer @platform,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_finish_device_removal(ulong @ptr,RustBuffer @review,RustBuffer @keep,RustBuffer @remove ); #if NET8_0_OR_GREATER @@ -4983,7 +5256,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_func_check_jump_hosts(RustBuffer @list,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_finish_genesis(ulong @ptr,RustBuffer @draft,RustBuffer @typed ); #if NET8_0_OR_GREATER @@ -4994,7 +5267,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_personal_data(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_finish_replace_recovery_key(ulong @ptr,RustBuffer @draft,RustBuffer @typed,RustBuffer @keep ); #if NET8_0_OR_GREATER @@ -5005,7 +5278,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_mcp_address(ushort @port,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_finish_reset_proposal(ulong @ptr,RustBuffer @draft,RustBuffer @typed ); #if NET8_0_OR_GREATER @@ -5016,7 +5289,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_fn_func_mcp_default_port(ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_held_team_restart(ulong @ptr,RustBuffer @team ); #if NET8_0_OR_GREATER @@ -5027,7 +5300,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_key_notices(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5038,7 +5311,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_key_state(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5049,7 +5322,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_own_fingerprint(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5060,7 +5333,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_pending_reset(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5071,7 +5344,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_recover_with_recovery_key(ulong @ptr,RustBuffer @recoveryKey ); #if NET8_0_OR_GREATER @@ -5082,7 +5355,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_remove_device_row(ulong @ptr,RustBuffer @device ); #if NET8_0_OR_GREATER @@ -5093,7 +5366,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_request_approval(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5104,7 +5377,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - byte ffi_tablepro_ffi_rust_future_complete_u8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_restart_team_key(ulong @ptr,RustBuffer @team,RustBuffer @confirm ); #if NET8_0_OR_GREATER @@ -5115,7 +5388,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i8(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_rotate_team_key(ulong @ptr,RustBuffer @team,RustBuffer @remove ); #if NET8_0_OR_GREATER @@ -5126,7 +5399,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_sign_out_keys(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5137,7 +5410,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_team_keys(ulong @ptr,RustBuffer @team ); #if NET8_0_OR_GREATER @@ -5148,7 +5421,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - sbyte ffi_tablepro_ffi_rust_future_complete_i8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_approvals(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5159,7 +5432,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u16(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_choose_for_new_identity(ulong @ptr,RustBuffer @choice ); #if NET8_0_OR_GREATER @@ -5170,7 +5443,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_choose_provider(ulong @ptr,RustBuffer @provider ); #if NET8_0_OR_GREATER @@ -5181,7 +5454,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_conflicts(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5192,7 +5465,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort ffi_tablepro_ffi_rust_future_complete_u16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_decide_approval(ulong @ptr,RustBuffer @record,RustBuffer @field,sbyte @approve ); #if NET8_0_OR_GREATER @@ -5203,7 +5476,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i16(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_delete_icloud_zone(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5214,7 +5487,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_held_records(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5225,7 +5498,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_load_older_history(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5236,7 +5509,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - short ffi_tablepro_ffi_rust_future_complete_i16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_move_to_icloud(ulong @ptr,ulong @confirmedDeletions ); #if NET8_0_OR_GREATER @@ -5247,7 +5520,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u32(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_move_to_service(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5258,7 +5531,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_plan_move_to_icloud(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5269,7 +5542,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_plan_move_to_service(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5280,7 +5553,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint ffi_tablepro_ffi_rust_future_complete_u32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_record_host_changes(ulong @ptr,RustBuffer @kind,RustBuffer @written,RustBuffer @deleted ); #if NET8_0_OR_GREATER @@ -5291,7 +5564,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i32(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_resolve_conflict(ulong @ptr,RustBuffer @record,RustBuffer @keep ); #if NET8_0_OR_GREATER @@ -5302,7 +5575,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_syncservice_set_categories(ulong @ptr,RustBuffer @categories ); #if NET8_0_OR_GREATER @@ -5313,7 +5586,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i32(ulong @handle + RustBuffer uniffi_tablepro_ffi_fn_method_syncservice_status(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5324,7 +5597,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - int ffi_tablepro_ffi_rust_future_complete_i32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_syncservice_sync_now(ulong @ptr,RustBuffer @why ); #if NET8_0_OR_GREATER @@ -5335,7 +5608,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u64(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_syncservice_upload_again(ulong @ptr ); #if NET8_0_OR_GREATER @@ -5346,7 +5619,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u64(ulong @handle + ulong uniffi_tablepro_ffi_fn_clone_tablefolderstore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5357,7 +5630,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle + void uniffi_tablepro_ffi_fn_free_tablefolderstore(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5368,7 +5641,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ulong ffi_tablepro_ffi_rust_future_complete_u64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_create(ulong @ptr,RustBuffer @connectionId,RustBuffer @database,RustBuffer @schema,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -5379,7 +5652,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_i64(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_delete(ulong @ptr,RustBuffer @id ); #if NET8_0_OR_GREATER @@ -5390,7 +5663,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_i64(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_file(ulong @ptr,RustBuffer @connectionId,RustBuffer @tables,RustBuffer @folderId ); #if NET8_0_OR_GREATER @@ -5401,7 +5674,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_i64(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_folders(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -5412,7 +5685,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - long ffi_tablepro_ffi_rust_future_complete_i64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_items(ulong @ptr,RustBuffer @connectionId ); #if NET8_0_OR_GREATER @@ -5423,7 +5696,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_f32(ulong @handle,IntPtr @callback,ulong @callbackData + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_put(ulong @ptr,RustBuffer @folder ); #if NET8_0_OR_GREATER @@ -5434,7 +5707,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_f32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_rename(ulong @ptr,RustBuffer @id,RustBuffer @name ); #if NET8_0_OR_GREATER @@ -5445,7 +5718,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle + ulong uniffi_tablepro_ffi_fn_method_tablefolderstore_unfile(ulong @ptr,RustBuffer @connectionId,RustBuffer @tables ); #if NET8_0_OR_GREATER @@ -5456,7 +5729,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - float ffi_tablepro_ffi_rust_future_complete_f32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -5467,7 +5740,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_f64(ulong @handle,IntPtr @callback,ulong @callbackData + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable ); #if NET8_0_OR_GREATER @@ -5478,7 +5751,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_f64(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostwebauthenticator(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostWebAuthenticator*/ @vtable ); #if NET8_0_OR_GREATER @@ -5489,7 +5762,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_aireplylistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAiReplyListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -5500,7 +5773,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - double ffi_tablepro_ffi_rust_future_complete_f64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable ); #if NET8_0_OR_GREATER @@ -5511,7 +5784,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_rust_buffer(ulong @handle,IntPtr @callback,ulong @callbackData + void uniffi_tablepro_ffi_fn_init_callback_vtable_mcpapphost(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceMcpAppHost*/ @vtable ); #if NET8_0_OR_GREATER @@ -5522,7 +5795,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_rust_buffer(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_mcplistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceMcpListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -5533,7 +5806,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_rust_buffer(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable ); #if NET8_0_OR_GREATER @@ -5544,7 +5817,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rust_future_complete_rust_buffer(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -5555,7 +5828,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_void(ulong @handle,IntPtr @callback,ulong @callbackData + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostdevicestore(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostDeviceStore*/ @vtable ); #if NET8_0_OR_GREATER @@ -5566,7 +5839,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_void(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsettings(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSettings*/ @vtable ); #if NET8_0_OR_GREATER @@ -5577,7 +5850,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_void(ulong @handle + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostlegacymirror(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostLegacyMirror*/ @vtable ); #if NET8_0_OR_GREATER @@ -5588,7 +5861,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_complete_void(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_synclistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceSyncListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -5599,7 +5872,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_personal_sync_choices( + RustBuffer uniffi_tablepro_ffi_fn_func_personal_sync_choices(RustBuffer @policy,RustBuffer @offered,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5610,7 +5883,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_settled_sync_provider( + RustBuffer uniffi_tablepro_ffi_fn_func_settled_sync_provider(RustBuffer @policy,RustBuffer @offered,RustBuffer @current,sbyte @tableproSyncAvailable,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5621,7 +5894,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets( + RustBuffer uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5632,7 +5905,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( + RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5643,7 +5916,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( + RustBuffer uniffi_tablepro_ffi_fn_func_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5654,7 +5927,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_ai_action_message( + RustBuffer uniffi_tablepro_ffi_fn_func_ai_action_message(RustBuffer @action,RustBuffer @statement,RustBuffer @error,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5665,7 +5938,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_ai_address_is_valid( + sbyte uniffi_tablepro_ffi_fn_func_ai_address_is_valid(RustBuffer @address,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5676,7 +5949,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_ai_host_of( + RustBuffer uniffi_tablepro_ffi_fn_func_ai_host_of(RustBuffer @settings,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5687,7 +5960,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_ai_providers( + RustBuffer uniffi_tablepro_ffi_fn_func_ai_providers(ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5698,7 +5971,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_parse_app_link( + RustBuffer uniffi_tablepro_ffi_fn_func_parse_app_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5709,7 +5982,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_format_sql( + RustBuffer uniffi_tablepro_ffi_fn_func_format_sql(RustBuffer @text,RustBuffer @grammar,uint @caret,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5720,7 +5993,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_format_sql_selection( + RustBuffer uniffi_tablepro_ffi_fn_func_format_sql_selection(RustBuffer @text,RustBuffer @grammar,uint @start,uint @end,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5731,7 +6004,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( + RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5742,7 +6015,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_keymap_preset( + RustBuffer uniffi_tablepro_ffi_fn_func_keymap_preset(RustBuffer @id,RustBuffer @platform,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5753,7 +6026,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_keymap_presets( + RustBuffer uniffi_tablepro_ffi_fn_func_keymap_presets(RustBuffer @platform,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5764,7 +6037,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_check_jump_hosts( + void uniffi_tablepro_ffi_fn_func_check_jump_hosts(RustBuffer @list,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5775,7 +6048,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data( + RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_personal_data(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5786,7 +6059,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_mcp_address( + RustBuffer uniffi_tablepro_ffi_fn_func_mcp_address(ushort @port,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5797,7 +6070,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_func_mcp_default_port( + ushort uniffi_tablepro_ffi_fn_func_mcp_default_port(ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5808,7 +6081,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_access_token( + RustBuffer uniffi_tablepro_ffi_fn_func_device_item_class(RustBuffer @item,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5819,7 +6092,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected( + RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5830,7 +6103,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_allows_tablepro_requests( + RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5841,7 +6114,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_apply_policy( + void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5852,7 +6125,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_choose_server( + RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5863,7 +6136,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( + void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -5874,7 +6147,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( + void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -5885,7 +6158,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_import_offline_file( + void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -5896,7 +6169,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_license( + byte ffi_tablepro_ffi_rust_future_complete_u8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5907,7 +6180,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( + void ffi_tablepro_ffi_rust_future_poll_i8(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -5918,7 +6191,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh( + void ffi_tablepro_ffi_rust_future_cancel_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -5929,7 +6202,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit( + void ffi_tablepro_ffi_rust_future_free_i8(ulong @handle ); #if NET8_0_OR_GREATER @@ -5940,7 +6213,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( + sbyte ffi_tablepro_ffi_rust_future_complete_i8(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5951,7 +6224,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_server( + void ffi_tablepro_ffi_rust_future_poll_u16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -5962,7 +6235,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( + void ffi_tablepro_ffi_rust_future_cancel_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -5973,7 +6246,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_out( + void ffi_tablepro_ffi_rust_future_free_u16(ulong @handle ); #if NET8_0_OR_GREATER @@ -5984,7 +6257,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_status( + ushort ffi_tablepro_ffi_rust_future_complete_u16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -5995,7 +6268,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_use_license_key( + void ffi_tablepro_ffi_rust_future_poll_i16(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6006,7 +6279,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( + void ffi_tablepro_ffi_rust_future_cancel_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -6017,7 +6290,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( + void ffi_tablepro_ffi_rust_future_free_i16(ulong @handle ); #if NET8_0_OR_GREATER @@ -6028,7 +6301,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared( + short ffi_tablepro_ffi_rust_future_complete_i16(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6039,7 +6312,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_list_shares( + void ffi_tablepro_ffi_rust_future_poll_u32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6050,7 +6323,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( + void ffi_tablepro_ffi_rust_future_cancel_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6061,7 +6334,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( + void ffi_tablepro_ffi_rust_future_free_u32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6072,7 +6345,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_default_model( + uint ffi_tablepro_ffi_rust_future_complete_u32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6083,7 +6356,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_has_key( + void ffi_tablepro_ffi_rust_future_poll_i32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6094,7 +6367,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_list_models( + void ffi_tablepro_ffi_rust_future_cancel_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6105,7 +6378,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_offline_models( + void ffi_tablepro_ffi_rust_future_free_i32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6116,7 +6389,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_reply( + int ffi_tablepro_ffi_rust_future_complete_i32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6127,7 +6400,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_set_key( + void ffi_tablepro_ffi_rust_future_poll_u64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6138,7 +6411,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aiassistant_start_conversation( + void ffi_tablepro_ffi_rust_future_cancel_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6149,7 +6422,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aireply_cancel( + void ffi_tablepro_ffi_rust_future_free_u64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6160,7 +6433,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aireply_drain_events( + ulong ffi_tablepro_ffi_rust_future_complete_u64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6171,7 +6444,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_canceltoken_cancel( + void ffi_tablepro_ffi_rust_future_poll_i64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6182,7 +6455,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled( + void ffi_tablepro_ffi_rust_future_cancel_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6193,7 +6466,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_catalogchange_destructive( + void ffi_tablepro_ffi_rust_future_free_i64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6204,7 +6477,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_catalogchange_gate( + long ffi_tablepro_ffi_rust_future_complete_i64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6215,7 +6488,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_catalogchange_run( + void ffi_tablepro_ffi_rust_future_poll_f32(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6226,7 +6499,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_catalogchange_statements( + void ffi_tablepro_ffi_rust_future_cancel_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6237,7 +6510,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_completionlist_rank( + void ffi_tablepro_ffi_rust_future_free_f32(ulong @handle ); #if NET8_0_OR_GREATER @@ -6248,7 +6521,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_completionlist_word( + float ffi_tablepro_ffi_rust_future_complete_f32(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6259,7 +6532,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_completionlist_word_start( + void ffi_tablepro_ffi_rust_future_poll_f64(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6270,7 +6543,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_account( + void ffi_tablepro_ffi_rust_future_cancel_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6281,7 +6554,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_ai_assistant( + void ffi_tablepro_ffi_rust_future_free_f64(ulong @handle ); #if NET8_0_OR_GREATER @@ -6292,7 +6565,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_connect_saved( + double ffi_tablepro_ffi_rust_future_complete_f64(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6303,7 +6576,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_drivers( + void ffi_tablepro_ffi_rust_future_poll_rust_buffer(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6314,7 +6587,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_history( + void ffi_tablepro_ffi_rust_future_cancel_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -6325,7 +6598,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_library( + void ffi_tablepro_ffi_rust_future_free_rust_buffer(ulong @handle ); #if NET8_0_OR_GREATER @@ -6336,7 +6609,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_open_file( + RustBuffer ffi_tablepro_ffi_rust_future_complete_rust_buffer(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6347,7 +6620,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_test_connection( + void ffi_tablepro_ffi_rust_future_poll_void(ulong @handle,IntPtr @callback,ulong @callbackData ); #if NET8_0_OR_GREATER @@ -6358,7 +6631,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_foreign_sources( + void ffi_tablepro_ffi_rust_future_cancel_void(ulong @handle ); #if NET8_0_OR_GREATER @@ -6369,7 +6642,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_read_foreign( + void ffi_tablepro_ffi_rust_future_free_void(ulong @handle ); #if NET8_0_OR_GREATER @@ -6380,7 +6653,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_forget_changed_host_key( + void ffi_tablepro_ffi_rust_future_complete_void(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -6391,7 +6664,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_core_mcp_server( + ushort uniffi_tablepro_ffi_checksum_func_personal_sync_choices( ); #if NET8_0_OR_GREATER @@ -6402,7 +6675,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_close( + ushort uniffi_tablepro_ffi_checksum_func_settled_sync_provider( ); #if NET8_0_OR_GREATER @@ -6413,7 +6686,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_database( + ushort uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets( ); #if NET8_0_OR_GREATER @@ -6424,7 +6697,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_is_lost( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( ); #if NET8_0_OR_GREATER @@ -6435,7 +6708,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_run( + ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( ); #if NET8_0_OR_GREATER @@ -6446,7 +6719,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryeditor_use_database( + ushort uniffi_tablepro_ffi_checksum_func_ai_action_message( ); #if NET8_0_OR_GREATER @@ -6457,7 +6730,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_exportprogress_rows( + ushort uniffi_tablepro_ffi_checksum_func_ai_address_is_valid( ); #if NET8_0_OR_GREATER @@ -6468,7 +6741,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_add_table( + ushort uniffi_tablepro_ffi_checksum_func_ai_host_of( ); #if NET8_0_OR_GREATER @@ -6479,7 +6752,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_databases( + ushort uniffi_tablepro_ffi_checksum_func_ai_providers( ); #if NET8_0_OR_GREATER @@ -6490,7 +6763,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_database( + ushort uniffi_tablepro_ffi_checksum_func_parse_app_link( ); #if NET8_0_OR_GREATER @@ -6501,7 +6774,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_table( + ushort uniffi_tablepro_ffi_checksum_func_format_sql( ); #if NET8_0_OR_GREATER @@ -6512,7 +6785,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_set_database( + ushort uniffi_tablepro_ffi_checksum_func_format_sql_selection( ); #if NET8_0_OR_GREATER @@ -6523,7 +6796,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_favouritestore_tables( + ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( ); #if NET8_0_OR_GREATER @@ -6534,7 +6807,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_app( + ushort uniffi_tablepro_ffi_checksum_func_keymap_preset( ); #if NET8_0_OR_GREATER @@ -6545,7 +6818,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_apply( + ushort uniffi_tablepro_ffi_checksum_func_keymap_presets( ); #if NET8_0_OR_GREATER @@ -6556,7 +6829,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_choices( + ushort uniffi_tablepro_ffi_checksum_func_check_jump_hosts( ); #if NET8_0_OR_GREATER @@ -6567,7 +6840,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_connections( + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data( ); #if NET8_0_OR_GREATER @@ -6578,7 +6851,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_passwords( + ushort uniffi_tablepro_ffi_checksum_func_mcp_address( ); #if NET8_0_OR_GREATER @@ -6589,7 +6862,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_resolve( + ushort uniffi_tablepro_ffi_checksum_func_mcp_default_port( ); #if NET8_0_OR_GREATER @@ -6600,7 +6873,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_saved_queries( + ushort uniffi_tablepro_ffi_checksum_func_device_item_class( ); #if NET8_0_OR_GREATER @@ -6611,7 +6884,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_included( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_access_token( ); #if NET8_0_OR_GREATER @@ -6622,7 +6895,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_selected( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected( ); #if NET8_0_OR_GREATER @@ -6633,7 +6906,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_allows_tablepro_requests( ); #if NET8_0_OR_GREATER @@ -6644,7 +6917,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_apply_policy( ); #if NET8_0_OR_GREATER @@ -6655,7 +6928,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_export( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_choose_server( ); #if NET8_0_OR_GREATER @@ -6666,7 +6939,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( ); #if NET8_0_OR_GREATER @@ -6677,7 +6950,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_prune( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( ); #if NET8_0_OR_GREATER @@ -6688,7 +6961,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_record( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_import_offline_file( ); #if NET8_0_OR_GREATER @@ -6699,7 +6972,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_license( ); #if NET8_0_OR_GREATER @@ -6710,7 +6983,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_search( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( ); #if NET8_0_OR_GREATER @@ -6721,7 +6994,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh( ); #if NET8_0_OR_GREATER @@ -6732,7 +7005,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit( ); #if NET8_0_OR_GREATER @@ -6743,7 +7016,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_columns( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( ); #if NET8_0_OR_GREATER @@ -6754,7 +7027,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_plan( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_server( ); #if NET8_0_OR_GREATER @@ -6765,7 +7038,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_preview( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( ); #if NET8_0_OR_GREATER @@ -6776,7 +7049,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_run( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_out( ); #if NET8_0_OR_GREATER @@ -6787,7 +7060,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_status( ); #if NET8_0_OR_GREATER @@ -6798,7 +7071,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_key( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_use_license_key( ); #if NET8_0_OR_GREATER @@ -6809,7 +7082,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_read_more( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( ); #if NET8_0_OR_GREATER @@ -6820,7 +7093,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_keyreader_rows( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( ); #if NET8_0_OR_GREATER @@ -6831,7 +7104,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared( ); #if NET8_0_OR_GREATER @@ -6842,7 +7115,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_cloud_edits( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_list_shares( ); #if NET8_0_OR_GREATER @@ -6853,7 +7126,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( ); #if NET8_0_OR_GREATER @@ -6864,7 +7137,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( + ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( ); #if NET8_0_OR_GREATER @@ -6875,7 +7148,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_default_model( ); #if NET8_0_OR_GREATER @@ -6886,7 +7159,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_has_key( ); #if NET8_0_OR_GREATER @@ -6897,7 +7170,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_group( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_list_models( ); #if NET8_0_OR_GREATER @@ -6908,7 +7181,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_offline_models( ); #if NET8_0_OR_GREATER @@ -6919,7 +7192,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_reply( ); #if NET8_0_OR_GREATER @@ -6930,7 +7203,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_set_key( ); #if NET8_0_OR_GREATER @@ -6941,7 +7214,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_import_file( + ushort uniffi_tablepro_ffi_checksum_method_aiassistant_start_conversation( ); #if NET8_0_OR_GREATER @@ -6952,7 +7225,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_groups( + ushort uniffi_tablepro_ffi_checksum_method_aireply_cancel( ); #if NET8_0_OR_GREATER @@ -6963,7 +7236,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_to_group( + ushort uniffi_tablepro_ffi_checksum_method_aireply_drain_events( ); #if NET8_0_OR_GREATER @@ -6974,7 +7247,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_remove_favorites( + ushort uniffi_tablepro_ffi_checksum_method_canceltoken_cancel( ); #if NET8_0_OR_GREATER @@ -6985,7 +7258,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_connection( + ushort uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled( ); #if NET8_0_OR_GREATER @@ -6996,7 +7269,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_group( + ushort uniffi_tablepro_ffi_checksum_method_catalogchange_destructive( ); #if NET8_0_OR_GREATER @@ -7007,7 +7280,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save( + ushort uniffi_tablepro_ffi_checksum_method_catalogchange_gate( ); #if NET8_0_OR_GREATER @@ -7018,7 +7291,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_favorite( + ushort uniffi_tablepro_ffi_checksum_method_catalogchange_run( ); #if NET8_0_OR_GREATER @@ -7029,7 +7302,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_group_color( + ushort uniffi_tablepro_ffi_checksum_method_catalogchange_statements( ); #if NET8_0_OR_GREATER @@ -7040,7 +7313,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_snapshot( + ushort uniffi_tablepro_ffi_checksum_method_completionlist_rank( ); #if NET8_0_OR_GREATER @@ -7051,7 +7324,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_tag_connections( + ushort uniffi_tablepro_ffi_checksum_method_completionlist_word( ); #if NET8_0_OR_GREATER @@ -7062,7 +7335,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( + ushort uniffi_tablepro_ffi_checksum_method_completionlist_word_start( ); #if NET8_0_OR_GREATER @@ -7073,7 +7346,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_connection_details( + ushort uniffi_tablepro_ffi_checksum_method_core_open_account( ); #if NET8_0_OR_GREATER @@ -7084,7 +7357,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_credential_profiles( + ushort uniffi_tablepro_ffi_checksum_method_core_ai_assistant( ); #if NET8_0_OR_GREATER @@ -7095,7 +7368,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_credential_profile( + ushort uniffi_tablepro_ffi_checksum_method_core_connect_saved( ); #if NET8_0_OR_GREATER @@ -7106,7 +7379,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_ssh_profile( + ushort uniffi_tablepro_ffi_checksum_method_core_drivers( ); #if NET8_0_OR_GREATER @@ -7117,7 +7390,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_device_settings( + ushort uniffi_tablepro_ffi_checksum_method_core_history( ); #if NET8_0_OR_GREATER @@ -7128,7 +7401,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save_credential_profile( + ushort uniffi_tablepro_ffi_checksum_method_core_library( ); #if NET8_0_OR_GREATER @@ -7139,7 +7412,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save_ssh_profile( + ushort uniffi_tablepro_ffi_checksum_method_core_open_file( ); #if NET8_0_OR_GREATER @@ -7150,7 +7423,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_connection_details( + ushort uniffi_tablepro_ffi_checksum_method_core_test_connection( ); #if NET8_0_OR_GREATER @@ -7161,7 +7434,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_device_settings( + ushort uniffi_tablepro_ffi_checksum_method_core_foreign_sources( ); #if NET8_0_OR_GREATER @@ -7172,7 +7445,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_ssh_profiles( + ushort uniffi_tablepro_ffi_checksum_method_core_read_foreign( ); #if NET8_0_OR_GREATER @@ -7183,7 +7456,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_access_token( + ushort uniffi_tablepro_ffi_checksum_method_core_forget_changed_host_key( ); #if NET8_0_OR_GREATER @@ -7194,7 +7467,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_apply( + ushort uniffi_tablepro_ffi_checksum_method_core_mcp_server( ); #if NET8_0_OR_GREATER @@ -7205,7 +7478,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_regenerate_token( + ushort uniffi_tablepro_ffi_checksum_method_core_open_sync( ); #if NET8_0_OR_GREATER @@ -7216,7 +7489,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_seen_clients( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_close( ); #if NET8_0_OR_GREATER @@ -7227,7 +7500,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_status( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_database( ); #if NET8_0_OR_GREATER @@ -7238,7 +7511,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpservice_stop( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_is_lost( ); #if NET8_0_OR_GREATER @@ -7249,7 +7522,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_run( ); #if NET8_0_OR_GREATER @@ -7260,7 +7533,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablekeys_referencing_tables( + ushort uniffi_tablepro_ffi_checksum_method_queryeditor_use_database( ); #if NET8_0_OR_GREATER @@ -7271,7 +7544,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablekeys_row_references( + ushort uniffi_tablepro_ffi_checksum_method_exportprogress_rows( ); #if NET8_0_OR_GREATER @@ -7282,7 +7555,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_masking( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_add_table( ); #if NET8_0_OR_GREATER @@ -7293,7 +7566,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_preview( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_databases( ); #if NET8_0_OR_GREATER @@ -7304,7 +7577,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_share_summary( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_database( ); #if NET8_0_OR_GREATER @@ -7315,7 +7588,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_remove_table( ); #if NET8_0_OR_GREATER @@ -7326,7 +7599,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_set_database( ); #if NET8_0_OR_GREATER @@ -7337,7 +7610,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head( + ushort uniffi_tablepro_ffi_checksum_method_favouritestore_tables( ); #if NET8_0_OR_GREATER @@ -7348,7 +7621,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_columns( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_app( ); #if NET8_0_OR_GREATER @@ -7359,7 +7632,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_filter_text( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_apply( ); #if NET8_0_OR_GREATER @@ -7370,7 +7643,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_index( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_choices( ); #if NET8_0_OR_GREATER @@ -7381,7 +7654,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_is_finished( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_connections( ); #if NET8_0_OR_GREATER @@ -7392,7 +7665,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_open_cursor( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_passwords( ); #if NET8_0_OR_GREATER @@ -7403,7 +7676,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_row_count( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_resolve( ); #if NET8_0_OR_GREATER @@ -7414,7 +7687,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_resultset_sorted( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_saved_queries( ); #if NET8_0_OR_GREATER @@ -7425,7 +7698,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_gate( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_included( ); #if NET8_0_OR_GREATER @@ -7436,7 +7709,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_is_empty( + ushort uniffi_tablepro_ffi_checksum_method_foreignimportreview_set_selected( ); #if NET8_0_OR_GREATER @@ -7447,7 +7720,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_run( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_clear( ); #if NET8_0_OR_GREATER @@ -7458,7 +7731,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_rowsave_statements( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_delete( ); #if NET8_0_OR_GREATER @@ -7469,7 +7742,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_check( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_export( ); #if NET8_0_OR_GREATER @@ -7480,7 +7753,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_favourites( ); #if NET8_0_OR_GREATER @@ -7491,7 +7764,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_copies_exactly( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_prune( ); #if NET8_0_OR_GREATER @@ -7502,7 +7775,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_record( ); #if NET8_0_OR_GREATER @@ -7513,7 +7786,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_saved_queries( ); #if NET8_0_OR_GREATER @@ -7524,7 +7797,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_search( ); #if NET8_0_OR_GREATER @@ -7535,7 +7808,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_set_pinned( ); #if NET8_0_OR_GREATER @@ -7546,7 +7819,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tableeditor_table( + ushort uniffi_tablepro_ffi_checksum_method_queryhistorystore_table_folders( ); #if NET8_0_OR_GREATER @@ -7557,7 +7830,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_columns( ); #if NET8_0_OR_GREATER @@ -7568,7 +7841,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_plan( ); #if NET8_0_OR_GREATER @@ -7579,7 +7852,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_preview( ); #if NET8_0_OR_GREATER @@ -7590,7 +7863,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_release_set( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_run( ); #if NET8_0_OR_GREATER @@ -7601,7 +7874,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( + ushort uniffi_tablepro_ffi_checksum_method_csvimport_suggest_mapping( ); #if NET8_0_OR_GREATER @@ -7612,7 +7885,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_create_folder( + ushort uniffi_tablepro_ffi_checksum_method_keyreader_key( ); #if NET8_0_OR_GREATER @@ -7623,7 +7896,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete( + ushort uniffi_tablepro_ffi_checksum_method_keyreader_read_more( ); #if NET8_0_OR_GREATER @@ -7634,7 +7907,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_folder( + ushort uniffi_tablepro_ffi_checksum_method_keyreader_rows( ); #if NET8_0_OR_GREATER @@ -7645,7 +7918,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_for_connection( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_apply_cloud_pull( ); #if NET8_0_OR_GREATER @@ -7656,7 +7929,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_move_folder( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_cloud_edits( ); #if NET8_0_OR_GREATER @@ -7667,7 +7940,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_move_query( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_add_favorites( ); #if NET8_0_OR_GREATER @@ -7678,7 +7951,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_rename( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_group( ); #if NET8_0_OR_GREATER @@ -7689,7 +7962,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_rename_folder( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_create_tag( ); #if NET8_0_OR_GREATER @@ -7700,7 +7973,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_save( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete( ); #if NET8_0_OR_GREATER @@ -7711,7 +7984,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_group( ); #if NET8_0_OR_GREATER @@ -7722,7 +7995,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_set_sql( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_tag( ); #if NET8_0_OR_GREATER @@ -7733,7 +8006,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_snapshot( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_duplicate( ); #if NET8_0_OR_GREATER @@ -7744,7 +8017,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_catalog_abilities( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_export_file( ); #if NET8_0_OR_GREATER @@ -7755,7 +8028,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_database_choices( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_import_file( ); #if NET8_0_OR_GREATER @@ -7766,7 +8039,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_plan_catalog_change( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_groups( ); #if NET8_0_OR_GREATER @@ -7777,7 +8050,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_protects_database( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_move_to_group( ); #if NET8_0_OR_GREATER @@ -7788,7 +8061,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_protects_schema( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_remove_favorites( ); #if NET8_0_OR_GREATER @@ -7799,7 +8072,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_schemas( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_connection( ); #if NET8_0_OR_GREATER @@ -7810,7 +8083,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_rows( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_rename_group( ); #if NET8_0_OR_GREATER @@ -7821,7 +8094,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_table( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save( ); #if NET8_0_OR_GREATER @@ -7832,7 +8105,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_csv_import( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_favorite( ); #if NET8_0_OR_GREATER @@ -7843,7 +8116,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_keys( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_group_color( ); #if NET8_0_OR_GREATER @@ -7854,7 +8127,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_close( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_snapshot( ); #if NET8_0_OR_GREATER @@ -7865,7 +8138,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_columns( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_tag_connections( ); #if NET8_0_OR_GREATER @@ -7876,7 +8149,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_complete( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_update_tag( ); #if NET8_0_OR_GREATER @@ -7887,7 +8160,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_database( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_connection_details( ); #if NET8_0_OR_GREATER @@ -7898,7 +8171,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_database_layout( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_credential_profiles( ); #if NET8_0_OR_GREATER @@ -7909,7 +8182,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_databases( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_credential_profile( ); #if NET8_0_OR_GREATER @@ -7920,7 +8193,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_driver_id( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_delete_ssh_profile( ); #if NET8_0_OR_GREATER @@ -7931,7 +8204,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_filter_choices( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_device_settings( ); #if NET8_0_OR_GREATER @@ -7942,7 +8215,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_gate_run( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save_credential_profile( ); #if NET8_0_OR_GREATER @@ -7953,7 +8226,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_save_ssh_profile( ); #if NET8_0_OR_GREATER @@ -7964,7 +8237,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_health_change( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_connection_details( ); #if NET8_0_OR_GREATER @@ -7975,7 +8248,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_id( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_set_device_settings( ); #if NET8_0_OR_GREATER @@ -7986,7 +8259,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_name( + ushort uniffi_tablepro_ffi_checksum_method_connectionlibrary_ssh_profiles( ); #if NET8_0_OR_GREATER @@ -7997,7 +8270,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_object_definition( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_access_token( ); #if NET8_0_OR_GREATER @@ -8008,7 +8281,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_objects( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_apply( ); #if NET8_0_OR_GREATER @@ -8019,7 +8292,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_editor( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_regenerate_token( ); #if NET8_0_OR_GREATER @@ -8030,7 +8303,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_key( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_seen_clients( ); #if NET8_0_OR_GREATER @@ -8041,7 +8314,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_only( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_status( ); #if NET8_0_OR_GREATER @@ -8052,7 +8325,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page( + ushort uniffi_tablepro_ffi_checksum_method_mcpservice_stop( ); #if NET8_0_OR_GREATER @@ -8063,7 +8336,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_reconnect( + ushort uniffi_tablepro_ffi_checksum_method_tablekeys_follow_reference( ); #if NET8_0_OR_GREATER @@ -8074,7 +8347,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects( + ushort uniffi_tablepro_ffi_checksum_method_tablekeys_referencing_tables( ); #if NET8_0_OR_GREATER @@ -8085,7 +8358,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_result_editor( + ushort uniffi_tablepro_ffi_checksum_method_tablekeys_row_references( ); #if NET8_0_OR_GREATER @@ -8096,7 +8369,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_schemas( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_masking( ); #if NET8_0_OR_GREATER @@ -8107,7 +8380,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_preview( ); #if NET8_0_OR_GREATER @@ -8118,7 +8391,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query( + ushort uniffi_tablepro_ffi_checksum_method_resultset_share_summary( ); #if NET8_0_OR_GREATER @@ -8129,7 +8402,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_statement_at( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_bytes( ); #if NET8_0_OR_GREATER @@ -8140,7 +8413,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_editor( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text( ); #if NET8_0_OR_GREATER @@ -8151,7 +8424,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_info( + ushort uniffi_tablepro_ffi_checksum_method_resultset_cell_text_head( ); #if NET8_0_OR_GREATER @@ -8162,7 +8435,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( + ushort uniffi_tablepro_ffi_checksum_method_resultset_columns( ); #if NET8_0_OR_GREATER @@ -8173,7 +8446,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate( + ushort uniffi_tablepro_ffi_checksum_method_resultset_filter_text( ); #if NET8_0_OR_GREATER @@ -8184,7 +8457,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_structure( + ushort uniffi_tablepro_ffi_checksum_method_resultset_index( ); #if NET8_0_OR_GREATER @@ -8195,7 +8468,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek( + ushort uniffi_tablepro_ffi_checksum_method_resultset_is_finished( ); #if NET8_0_OR_GREATER @@ -8206,7 +8479,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_next_page( + ushort uniffi_tablepro_ffi_checksum_method_resultset_open_cursor( ); #if NET8_0_OR_GREATER @@ -8217,7 +8490,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_run( + ushort uniffi_tablepro_ffi_checksum_method_resultset_row_count( ); #if NET8_0_OR_GREATER @@ -8228,7 +8501,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql( + ushort uniffi_tablepro_ffi_checksum_method_resultset_sorted( ); #if NET8_0_OR_GREATER @@ -8239,7 +8512,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_gate( ); #if NET8_0_OR_GREATER @@ -8250,7 +8523,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_create( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_is_empty( ); #if NET8_0_OR_GREATER @@ -8261,7 +8534,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_run( ); #if NET8_0_OR_GREATER @@ -8272,7 +8545,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_file( + ushort uniffi_tablepro_ffi_checksum_method_rowsave_statements( ); #if NET8_0_OR_GREATER @@ -8283,7 +8556,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_check( ); #if NET8_0_OR_GREATER @@ -8294,7 +8567,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_items( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_columns( ); #if NET8_0_OR_GREATER @@ -8305,7 +8578,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_put( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_copies_exactly( ); #if NET8_0_OR_GREATER @@ -8316,7 +8589,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_edit_start( ); #if NET8_0_OR_GREATER @@ -8327,7 +8600,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock( ); #if NET8_0_OR_GREATER @@ -8338,7 +8611,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_canceltoken_new( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_lock_for( ); #if NET8_0_OR_GREATER @@ -8349,7 +8622,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_new( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_plan( ); #if NET8_0_OR_GREATER @@ -8360,7 +8633,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets( + ushort uniffi_tablepro_ffi_checksum_method_tableeditor_table( ); #if NET8_0_OR_GREATER @@ -8371,7 +8644,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_constructor_exportprogress_new( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_cancel( ); #if NET8_0_OR_GREATER @@ -8382,7 +8655,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_drain_events( ); #if NET8_0_OR_GREATER @@ -8393,7 +8666,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_outcome( ); #if NET8_0_OR_GREATER @@ -8404,7 +8677,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_release_set( ); #if NET8_0_OR_GREATER @@ -8415,7 +8688,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate( + ushort uniffi_tablepro_ffi_checksum_method_queryrun_result_set( ); #if NET8_0_OR_GREATER @@ -8426,7 +8699,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_create_folder( ); #if NET8_0_OR_GREATER @@ -8437,7 +8710,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete( ); #if NET8_0_OR_GREATER @@ -8448,7 +8721,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_folder( ); #if NET8_0_OR_GREATER @@ -8459,7 +8732,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_delete_for_connection( ); #if NET8_0_OR_GREATER @@ -8470,7 +8743,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_move_folder( ); #if NET8_0_OR_GREATER @@ -8481,7 +8754,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_move_query( ); #if NET8_0_OR_GREATER @@ -8492,7 +8765,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_rename( ); #if NET8_0_OR_GREATER @@ -8503,7 +8776,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_rename_folder( ); #if NET8_0_OR_GREATER @@ -8514,7 +8787,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_save( ); #if NET8_0_OR_GREATER @@ -8525,7 +8798,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_set_keyword( ); #if NET8_0_OR_GREATER @@ -8536,7 +8809,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_set_sql( ); #if NET8_0_OR_GREATER @@ -8547,7 +8820,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting( + ushort uniffi_tablepro_ffi_checksum_method_savedquerystore_snapshot( ); #if NET8_0_OR_GREATER @@ -8558,7 +8831,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_approve( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_catalog_abilities( ); #if NET8_0_OR_GREATER @@ -8569,7 +8842,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_database_choices( ); #if NET8_0_OR_GREATER @@ -8580,7 +8853,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_mcplistener_changed( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_plan_catalog_change( ); #if NET8_0_OR_GREATER @@ -8591,7 +8864,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostprompter_prompt( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_protects_database( ); #if NET8_0_OR_GREATER @@ -8602,7 +8875,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_runlistener_events_pending( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_protects_schema( ); #if NET8_0_OR_GREATER @@ -8613,146 +8886,1758 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - uint ffi_tablepro_ffi_uniffi_contract_version( + ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_schemas( ); - + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_rows( + ); - static void uniffiCheckContractApiVersion() { - var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); - if (30 != scaffolding_contract_version) { - throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); - } - } - static void uniffiCheckApiChecksums() { - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_personal_sync_choices(); - if (checksum != 53725) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_personal_sync_choices` checksum `53725`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_settled_sync_provider(); - if (checksum != 8008) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_settled_sync_provider` checksum `8008`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets(); - if (checksum != 2030) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets` checksum `2030`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets(); - if (checksum != 6288) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets` checksum `6288`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_share_token_from_link(); - if (checksum != 49369) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_share_token_from_link` checksum `49369`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_action_message(); - if (checksum != 8116) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_action_message` checksum `8116`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_address_is_valid(); - if (checksum != 9771) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_address_is_valid` checksum `9771`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_host_of(); - if (checksum != 2404) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_host_of` checksum `2404`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_providers(); - if (checksum != 7775) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_providers` checksum `7775`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_app_link(); - if (checksum != 17722) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_app_link` checksum `17722`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_format_sql(); - if (checksum != 59571) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_format_sql` checksum `59571`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_format_sql_selection(); - if (checksum != 33116) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_format_sql_selection` checksum `33116`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); - if (checksum != 48047) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_connection_url` checksum `48047`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_keymap_preset(); - if (checksum != 61230) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_keymap_preset` checksum `61230`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_keymap_presets(); - if (checksum != 36740) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_keymap_presets` checksum `36740`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_check_jump_hosts(); - if (checksum != 27175) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_check_jump_hosts` checksum `27175`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data(); - if (checksum != 17541) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data` checksum `17541`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_mcp_address(); - if (checksum != 59452) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_mcp_address` checksum `59452`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_mcp_default_port(); - if (checksum != 46423) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_mcp_default_port` checksum `46423`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_access_token(); - if (checksum != 48110) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_access_token` checksum `48110`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected(); - if (checksum != 16795) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected` checksum `16795`, library returned `{checksum}`"); - } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_allows_tablepro_requests(); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_export_table( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_csv_import( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_keys( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_close( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_columns( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_complete( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_database( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_database_layout( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_databases( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_driver_id( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_filter_choices( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_gate_run( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_health( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_health_change( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_id( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_name( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_object_definition( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_objects( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_editor( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_open_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_only( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_reconnect( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_result_editor( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_schemas( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_statement_at( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_editor( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_info( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_databasesession_table_structure( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablepageread_next_page( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablepageread_run( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_account_status( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_ensure_zone( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_delete_zone( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_changes( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_records( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_cloudkittransport_modify( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_accept_key_change( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_accept_team_restart( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_account_devices( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_account_fingerprint( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_account_key_change( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_activate_reset( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_approval_requests( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_approval_session( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_approval_words_differ( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_begin_device_removal( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_begin_genesis( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_begin_replace_recovery_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_begin_reset( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_cancel_approval_session( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_cancel_reset( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_choose_approval_request( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_compare_fingerprint_qr( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_confirm_approval_session( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_confirm_member( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_create_team_keys( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_credentials_to_rotate( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_dismiss_key_notice( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_finish_device_removal( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_finish_genesis( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_finish_replace_recovery_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_finish_reset_proposal( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_held_team_restart( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_key_notices( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_key_state( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_own_fingerprint( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_pending_reset( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_recover_with_recovery_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_remove_device_row( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_request_approval( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_restart_team_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_rotate_team_key( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_sign_out_keys( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_team_keys( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_approvals( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_choose_for_new_identity( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_choose_provider( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_conflicts( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_decide_approval( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_delete_icloud_zone( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_held_records( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_load_older_history( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_move_to_icloud( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_move_to_service( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_icloud( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_service( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_record_host_changes( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_resolve_conflict( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_set_categories( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_status( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_sync_now( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_syncservice_upload_again( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_create( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_file( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_items( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_put( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_constructor_canceltoken_new( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_constructor_core_new( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_constructor_exportprogress_new( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_approve( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_mcplistener_changed( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostprompter_prompt( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_runlistener_events_pending( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostdevicestore_load( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostdevicestore_store( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostdevicestore_delete( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsettings_categories( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsettings_apply( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostlegacymirror_read( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostlegacymirror_write( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostlegacymirror_mark( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_synclistener_status_changed( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_synclistener_keys_changed( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + uint ffi_tablepro_ffi_uniffi_contract_version( + ); + + + + static void uniffiCheckContractApiVersion() { + var scaffolding_contract_version = _UniFFILib.ffi_tablepro_ffi_uniffi_contract_version(); + if (30 != scaffolding_contract_version) { + throw new UniffiContractVersionException($"TablePro.Interop.Native: uniffi bindings expected version `30`, library returned `{scaffolding_contract_version}`"); + } + } + static void uniffiCheckApiChecksums() { + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_personal_sync_choices(); + if (checksum != 53725) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_personal_sync_choices` checksum `53725`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_settled_sync_provider(); + if (checksum != 8008) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_settled_sync_provider` checksum `8008`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets(); + if (checksum != 2030) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets` checksum `2030`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets(); + if (checksum != 6288) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets` checksum `6288`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_share_token_from_link(); + if (checksum != 49369) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_share_token_from_link` checksum `49369`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_action_message(); + if (checksum != 8116) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_action_message` checksum `8116`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_address_is_valid(); + if (checksum != 9771) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_address_is_valid` checksum `9771`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_host_of(); + if (checksum != 2404) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_host_of` checksum `2404`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_ai_providers(); + if (checksum != 7775) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_ai_providers` checksum `7775`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_app_link(); + if (checksum != 17722) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_app_link` checksum `17722`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_format_sql(); + if (checksum != 59571) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_format_sql` checksum `59571`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_format_sql_selection(); + if (checksum != 33116) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_format_sql_selection` checksum `33116`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); + if (checksum != 48047) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_connection_url` checksum `48047`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_keymap_preset(); + if (checksum != 61230) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_keymap_preset` checksum `61230`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_keymap_presets(); + if (checksum != 36740) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_keymap_presets` checksum `36740`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_check_jump_hosts(); + if (checksum != 27175) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_check_jump_hosts` checksum `27175`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data(); + if (checksum != 17541) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_personal_data` checksum `17541`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_mcp_address(); + if (checksum != 59452) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_mcp_address` checksum `59452`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_mcp_default_port(); + if (checksum != 46423) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_mcp_default_port` checksum `46423`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_device_item_class(); + if (checksum != 30078) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_device_item_class` checksum `30078`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_access_token(); + if (checksum != 48110) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_access_token` checksum `48110`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected(); + if (checksum != 16795) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_access_token_rejected` checksum `16795`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_allows_tablepro_requests(); if (checksum != 9666) { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_allows_tablepro_requests` checksum `9666`, library returned `{checksum}`"); } @@ -9063,6 +10948,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_mcp_server` checksum `26503`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_open_sync(); + if (checksum != 17966) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_open_sync` checksum `17966`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_queryeditor_close(); if (checksum != 47507) { @@ -9934,622 +11825,3325 @@ static void uniffiCheckApiChecksums() { } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_object_definition(); - if (checksum != 7113) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_object_definition` checksum `7113`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_object_definition(); + if (checksum != 7113) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_object_definition` checksum `7113`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_objects(); + if (checksum != 10666) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_objects` checksum `10666`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_open_editor(); + if (checksum != 43974) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_open_editor` checksum `43974`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_open_key(); + if (checksum != 61646) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_open_key` checksum `61646`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_read_only(); + if (checksum != 26585) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_read_only` checksum `26585`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page(); + if (checksum != 45895) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page` checksum `45895`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_reconnect(); + if (checksum != 39245) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_reconnect` checksum `39245`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects(); + if (checksum != 16631) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects` checksum `16631`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_result_editor(); + if (checksum != 60737) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_result_editor` checksum `60737`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_schemas(); + if (checksum != 64032) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_schemas` checksum `64032`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode(); + if (checksum != 16374) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode` checksum `16374`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query(); + if (checksum != 35269) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query` checksum `35269`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_statement_at(); + if (checksum != 63657) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_statement_at` checksum `63657`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_editor(); + if (checksum != 1990) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_editor` checksum `1990`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_info(); + if (checksum != 24338) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_info` checksum `24338`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count(); + if (checksum != 47733) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count` checksum `47733`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate(); + if (checksum != 301) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate` checksum `301`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_structure(); + if (checksum != 41263) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_structure` checksum `41263`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek(); + if (checksum != 58553) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek` checksum `58553`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_next_page(); + if (checksum != 13025) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_next_page` checksum `13025`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_run(); + if (checksum != 28269) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_run` checksum `28269`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql(); + if (checksum != 5883) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql` checksum `5883`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns(); + if (checksum != 21678) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns` checksum `21678`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_account_status(); + if (checksum != 57140) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_account_status` checksum `57140`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_ensure_zone(); + if (checksum != 29900) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_ensure_zone` checksum `29900`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_delete_zone(); + if (checksum != 30064) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_delete_zone` checksum `30064`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_changes(); + if (checksum != 44128) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_changes` checksum `44128`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_records(); + if (checksum != 23155) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_fetch_records` checksum `23155`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_cloudkittransport_modify(); + if (checksum != 50150) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_cloudkittransport_modify` checksum `50150`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_accept_key_change(); + if (checksum != 18769) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_accept_key_change` checksum `18769`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_accept_team_restart(); + if (checksum != 61209) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_accept_team_restart` checksum `61209`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_account_devices(); + if (checksum != 54513) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_account_devices` checksum `54513`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_account_fingerprint(); + if (checksum != 17818) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_account_fingerprint` checksum `17818`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_account_key_change(); + if (checksum != 14893) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_account_key_change` checksum `14893`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_activate_reset(); + if (checksum != 14281) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_activate_reset` checksum `14281`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_approval_requests(); + if (checksum != 45824) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_approval_requests` checksum `45824`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_approval_session(); + if (checksum != 6462) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_approval_session` checksum `6462`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_approval_words_differ(); + if (checksum != 42048) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_approval_words_differ` checksum `42048`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_begin_device_removal(); + if (checksum != 27135) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_begin_device_removal` checksum `27135`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_begin_genesis(); + if (checksum != 62848) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_begin_genesis` checksum `62848`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_begin_replace_recovery_key(); + if (checksum != 2912) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_begin_replace_recovery_key` checksum `2912`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_begin_reset(); + if (checksum != 48061) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_begin_reset` checksum `48061`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_cancel_approval_session(); + if (checksum != 37697) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_cancel_approval_session` checksum `37697`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_cancel_reset(); + if (checksum != 62911) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_cancel_reset` checksum `62911`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_choose_approval_request(); + if (checksum != 63486) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_choose_approval_request` checksum `63486`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_compare_fingerprint_qr(); + if (checksum != 26317) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_compare_fingerprint_qr` checksum `26317`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_confirm_approval_session(); + if (checksum != 57576) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_confirm_approval_session` checksum `57576`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_confirm_member(); + if (checksum != 60361) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_confirm_member` checksum `60361`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_create_team_keys(); + if (checksum != 17628) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_create_team_keys` checksum `17628`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_credentials_to_rotate(); + if (checksum != 44781) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_credentials_to_rotate` checksum `44781`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_dismiss_key_notice(); + if (checksum != 52979) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_dismiss_key_notice` checksum `52979`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_finish_device_removal(); + if (checksum != 60774) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_finish_device_removal` checksum `60774`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_finish_genesis(); + if (checksum != 4570) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_finish_genesis` checksum `4570`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_finish_replace_recovery_key(); + if (checksum != 40762) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_finish_replace_recovery_key` checksum `40762`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_finish_reset_proposal(); + if (checksum != 41543) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_finish_reset_proposal` checksum `41543`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_held_team_restart(); + if (checksum != 20677) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_held_team_restart` checksum `20677`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_key_notices(); + if (checksum != 42612) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_key_notices` checksum `42612`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_key_state(); + if (checksum != 31343) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_key_state` checksum `31343`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_own_fingerprint(); + if (checksum != 55109) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_own_fingerprint` checksum `55109`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_pending_reset(); + if (checksum != 40435) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_pending_reset` checksum `40435`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_recover_with_recovery_key(); + if (checksum != 61755) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_recover_with_recovery_key` checksum `61755`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_remove_device_row(); + if (checksum != 41031) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_remove_device_row` checksum `41031`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_request_approval(); + if (checksum != 24589) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_request_approval` checksum `24589`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_restart_team_key(); + if (checksum != 12980) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_restart_team_key` checksum `12980`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_rotate_team_key(); + if (checksum != 26133) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_rotate_team_key` checksum `26133`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_sign_out_keys(); + if (checksum != 22984) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_sign_out_keys` checksum `22984`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_team_keys(); + if (checksum != 42703) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_team_keys` checksum `42703`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_approvals(); + if (checksum != 1578) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_approvals` checksum `1578`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_choose_for_new_identity(); + if (checksum != 20416) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_choose_for_new_identity` checksum `20416`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_choose_provider(); + if (checksum != 14987) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_choose_provider` checksum `14987`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_conflicts(); + if (checksum != 14871) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_conflicts` checksum `14871`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_decide_approval(); + if (checksum != 56111) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_decide_approval` checksum `56111`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_delete_icloud_zone(); + if (checksum != 59450) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_delete_icloud_zone` checksum `59450`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_held_records(); + if (checksum != 26919) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_held_records` checksum `26919`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_load_older_history(); + if (checksum != 50390) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_load_older_history` checksum `50390`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_move_to_icloud(); + if (checksum != 59916) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_move_to_icloud` checksum `59916`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_move_to_service(); + if (checksum != 50625) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_move_to_service` checksum `50625`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_icloud(); + if (checksum != 63771) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_icloud` checksum `63771`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_service(); + if (checksum != 788) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_plan_move_to_service` checksum `788`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_record_host_changes(); + if (checksum != 20554) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_record_host_changes` checksum `20554`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_resolve_conflict(); + if (checksum != 5445) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_resolve_conflict` checksum `5445`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_set_categories(); + if (checksum != 60820) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_set_categories` checksum `60820`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_status(); + if (checksum != 48957) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_status` checksum `48957`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_sync_now(); + if (checksum != 49306) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_sync_now` checksum `49306`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_syncservice_upload_again(); + if (checksum != 50600) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_syncservice_upload_again` checksum `50600`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_create(); + if (checksum != 55602) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_create` checksum `55602`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete(); + if (checksum != 19118) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete` checksum `19118`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_file(); + if (checksum != 22927) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_file` checksum `22927`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders(); + if (checksum != 42325) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders` checksum `42325`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_items(); + if (checksum != 5594) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_items` checksum `5594`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_put(); + if (checksum != 33778) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_put` checksum `33778`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename(); + if (checksum != 41173) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename` checksum `41173`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile(); + if (checksum != 42640) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile` checksum `42640`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_canceltoken_new(); + if (checksum != 44262) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_canceltoken_new` checksum `44262`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_core_new(); + if (checksum != 11967) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_core_new` checksum `11967`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets(); + if (checksum != 43052) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets` checksum `43052`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_exportprogress_new(); + if (checksum != 63262) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_exportprogress_new` checksum `63262`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed(); + if (checksum != 24504) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed` checksum `24504`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out(); + if (checksum != 33179) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out` checksum `33179`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url(); + if (checksum != 39709) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url` checksum `39709`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate(); + if (checksum != 30636) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate` checksum `30636`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel(); + if (checksum != 29099) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel` checksum `29099`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending(); + if (checksum != 59424) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending` checksum `59424`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_load(); + if (checksum != 39136) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_load` checksum `39136`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_store(); + if (checksum != 40708) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_store` checksum `40708`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel(); + if (checksum != 50042) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel` checksum `50042`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete(); + if (checksum != 3306) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete` checksum `3306`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection(); + if (checksum != 47390) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection` checksum `47390`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item(); + if (checksum != 56817) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item` checksum `56817`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item(); + if (checksum != 48405) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item` checksum `48405`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item(); + if (checksum != 58541) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item` checksum `58541`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection(); + if (checksum != 29837) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection` checksum `29837`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting(); + if (checksum != 37925) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting` checksum `37925`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_approve(); + if (checksum != 37501) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_approve` checksum `37501`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw(); + if (checksum != 6775) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw` checksum `6775`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_objects(); - if (checksum != 10666) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_objects` checksum `10666`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcplistener_changed(); + if (checksum != 6960) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcplistener_changed` checksum `6960`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_open_editor(); - if (checksum != 43974) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_open_editor` checksum `43974`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostprompter_prompt(); + if (checksum != 46308) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostprompter_prompt` checksum `46308`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_open_key(); - if (checksum != 61646) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_open_key` checksum `61646`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_runlistener_events_pending(); + if (checksum != 34969) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_runlistener_events_pending` checksum `34969`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_read_only(); - if (checksum != 26585) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_read_only` checksum `26585`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostdevicestore_load(); + if (checksum != 8212) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostdevicestore_load` checksum `8212`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page(); - if (checksum != 45895) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_read_table_page` checksum `45895`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostdevicestore_store(); + if (checksum != 20650) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostdevicestore_store` checksum `20650`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_reconnect(); - if (checksum != 39245) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_reconnect` checksum `39245`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostdevicestore_delete(); + if (checksum != 56689) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostdevicestore_delete` checksum `56689`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects(); - if (checksum != 16631) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_refresh_objects` checksum `16631`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsettings_categories(); + if (checksum != 37099) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsettings_categories` checksum `37099`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_result_editor(); - if (checksum != 60737) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_result_editor` checksum `60737`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsettings_apply(); + if (checksum != 48609) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsettings_apply` checksum `48609`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_schemas(); - if (checksum != 64032) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_schemas` checksum `64032`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostlegacymirror_read(); + if (checksum != 11830) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostlegacymirror_read` checksum `11830`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode(); - if (checksum != 16374) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_set_safe_mode` checksum `16374`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostlegacymirror_write(); + if (checksum != 41688) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostlegacymirror_write` checksum `41688`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query(); - if (checksum != 35269) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_sorted_query` checksum `35269`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostlegacymirror_mark(); + if (checksum != 36425) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostlegacymirror_mark` checksum `36425`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_statement_at(); - if (checksum != 63657) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_statement_at` checksum `63657`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_synclistener_status_changed(); + if (checksum != 61173) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_synclistener_status_changed` checksum `61173`, library returned `{checksum}`"); } } { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_editor(); - if (checksum != 1990) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_editor` checksum `1990`, library returned `{checksum}`"); + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_synclistener_keys_changed(); + if (checksum != 61805) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_synclistener_keys_changed` checksum `61805`, library returned `{checksum}`"); } } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_info(); - if (checksum != 24338) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_info` checksum `24338`, library returned `{checksum}`"); + } +} + +// Public interface members begin here. + +#pragma warning disable 8625 + + + + +class FfiConverterUInt16: FfiConverter { + public static FfiConverterUInt16 INSTANCE = new FfiConverterUInt16(); + + public override ushort Lift(ushort value) { + return value; + } + + public override ushort Read(BigEndianStream stream) { + return stream.ReadUShort(); + } + + public override ushort Lower(ushort value) { + return value; + } + + public override int AllocationSize(ushort value) { + return 2; + } + + public override void Write(ushort value, BigEndianStream stream) { + stream.WriteUShort(value); + } +} + + + +class FfiConverterUInt32: FfiConverter { + public static FfiConverterUInt32 INSTANCE = new FfiConverterUInt32(); + + public override uint Lift(uint value) { + return value; + } + + public override uint Read(BigEndianStream stream) { + return stream.ReadUInt(); + } + + public override uint Lower(uint value) { + return value; + } + + public override int AllocationSize(uint value) { + return 4; + } + + public override void Write(uint value, BigEndianStream stream) { + stream.WriteUInt(value); + } +} + + + +class FfiConverterUInt64: FfiConverter { + public static FfiConverterUInt64 INSTANCE = new FfiConverterUInt64(); + + public override ulong Lift(ulong value) { + return value; + } + + public override ulong Read(BigEndianStream stream) { + return stream.ReadULong(); + } + + public override ulong Lower(ulong value) { + return value; + } + + public override int AllocationSize(ulong value) { + return 8; + } + + public override void Write(ulong value, BigEndianStream stream) { + stream.WriteULong(value); + } +} + + + +class FfiConverterInt64: FfiConverter { + public static FfiConverterInt64 INSTANCE = new FfiConverterInt64(); + + public override long Lift(long value) { + return value; + } + + public override long Read(BigEndianStream stream) { + return stream.ReadLong(); + } + + public override long Lower(long value) { + return value; + } + + public override int AllocationSize(long value) { + return 8; + } + + public override void Write(long value, BigEndianStream stream) { + stream.WriteLong(value); + } +} + + + +class FfiConverterDouble: FfiConverter { + public static FfiConverterDouble INSTANCE = new FfiConverterDouble(); + + public override double Lift(double value) { + return value; + } + + public override double Read(BigEndianStream stream) { + return stream.ReadDouble(); + } + + public override double Lower(double value) { + return value; + } + + public override int AllocationSize(double value) { + return 8; + } + + public override void Write(double value, BigEndianStream stream) { + stream.WriteDouble(value); + } +} + + + +class FfiConverterBoolean: FfiConverter { + public static FfiConverterBoolean INSTANCE = new FfiConverterBoolean(); + + public override bool Lift(sbyte value) { + return value != 0; + } + + public override bool Read(BigEndianStream stream) { + return Lift(stream.ReadSByte()); + } + + public override sbyte Lower(bool value) { + return value ? (sbyte)1 : (sbyte)0; + } + + public override int AllocationSize(bool value) { + return (sbyte)1; + } + + public override void Write(bool value, BigEndianStream stream) { + stream.WriteSByte(Lower(value)); + } +} + + + +class FfiConverterString: FfiConverter { + public static FfiConverterString INSTANCE = new FfiConverterString(); + + // 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. + public override string Lift(RustBuffer value) { + try { + unsafe { + return System.Text.Encoding.UTF8.GetString( + (byte*)value.data.ToPointer(), Convert.ToInt32(value.len)); } + } finally { + RustBuffer.Free(value); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count(); - if (checksum != 47733) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_count` checksum `47733`, library returned `{checksum}`"); + } + + public override string Read(BigEndianStream stream) { + var length = stream.ReadInt(); + return stream.ReadUtf8String(length); + } + + public override RustBuffer Lower(string value) { + var rustBuffer = RustBuffer.Alloc(System.Text.Encoding.UTF8.GetByteCount(value)); + try { + unsafe { + fixed (char* chars = value) { + System.Text.Encoding.UTF8.GetBytes( + chars, value.Length, (byte*)rustBuffer.data.ToPointer(), Convert.ToInt32(rustBuffer.len)); + } } + return rustBuffer; + } catch { + RustBuffer.Free(rustBuffer); + throw; } + } + + // TODO(CS) + // We aren't sure exactly how many bytes our string will be once it's UTF-8 + // encoded. Allocate 3 bytes per unicode codepoint which will always be + // enough. + public override int AllocationSize(string value) { + const int sizeForLength = 4; + var sizeForString = System.Text.Encoding.UTF8.GetByteCount(value); + return sizeForLength + sizeForString; + } + + public override void Write(string value, BigEndianStream stream) { + stream.WriteUtf8String(value); + } +} + + + + +class FfiConverterByteArray: FfiConverterRustBuffer { + public static FfiConverterByteArray INSTANCE = new FfiConverterByteArray(); + + public override byte[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + return stream.ReadBytes(length); + } + + public override int AllocationSize(byte[] value) { + return 4 + value.Length; + } + + public override void Write(byte[] value, BigEndianStream stream) { + stream.WriteInt(value.Length); + stream.WriteBytes(value); + } +} + + + +internal interface IAccountService { + /// + Task AccessToken(); + Task AccessTokenRejected(SecretString @token); + bool AllowsTableproRequests(); + void ApplyPolicy(ManagedPolicyArg @policy); + /// + Task ChooseServer(string? @url); + /// + Task Devices(); + FeatureAccessTag FeatureAccess(string @feature); + /// + Task ImportOfflineFile(string @path); + ServerLicenseInfo? License(); + /// + Task Profile(); + /// + Task Refresh(); + /// + Task RefreshPastDeviceLimit(); + /// + Task RemoveDevice(string @deviceId); + ServerInfo Server(); + /// + Task SignIn(CancelToken? @cancel); + /// + Task SignOut(); + AccountStatusInfo Status(); + /// + Task UseLicenseKey(SecretString @key); + /// + Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows, ulong? @totalRows, ShareColumnChoice[] @columns); + /// + Task ExtendShare(string @shareId, ShareExpiryTag @expiry); + /// + Task FetchShared(string @token, SecretString? @password); + /// + Task ListShares(bool @liveOnly, string? @teamId, string? @cursor); + /// + Task RevokeShare(string @shareId); + /// + Task ShareLimits(); +} +internal class AccountService : IAccountService, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public AccountService(ulong pointer) { + this.pointer = pointer; + } + + ~AccountService() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_accountservice(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_accountservice(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate(); - if (checksum != 301) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_row_estimate` checksum `301`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_databasesession_table_structure(); - if (checksum != 41263) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_databasesession_table_structure` checksum `41263`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); } + } + + + /// + public async Task AccessToken() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_access_token(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeAccessTokenInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public async Task AccessTokenRejected(SecretString @token) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_access_token_rejected(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@token)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + NullCallStatusErrorHandler.INSTANCE + + ); + } + + public bool AllowsTableproRequests() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_allows_tablepro_requests(thisPtr, ref _status) +))); + } + + + public void ApplyPolicy(ManagedPolicyArg @policy) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_apply_policy(thisPtr, FfiConverterTypeManagedPolicyArg.INSTANCE.Lower(@policy), ref _status) +)); + } + + + + /// + public async Task ChooseServer(string? @url) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_choose_server(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@url)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Devices() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_devices(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeDeviceInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public FeatureAccessTag FeatureAccess(string @feature) { + return CallWithPointer(thisPtr => FfiConverterTypeFeatureAccessTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_feature_access(thisPtr, FfiConverterString.INSTANCE.Lower(@feature), ref _status) +))); + } + + + /// + public async Task ImportOfflineFile(string @path) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_import_offline_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public ServerLicenseInfo? License() { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeServerLicenseInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_license(thisPtr, ref _status) +))); + } + + + /// + public async Task Profile() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_profile(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeProfileInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Refresh() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RefreshPastDeviceLimit() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh_past_device_limit(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + // Lift + (result) => FfiConverterBoolean.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RemoveDevice(string @deviceId) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_remove_device(thisPtr, FfiConverterString.INSTANCE.Lower(@deviceId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public ServerInfo Server() { + return CallWithPointer(thisPtr => FfiConverterTypeServerInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_server(thisPtr, ref _status) +))); + } + + + /// + public async Task SignIn(CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_in(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task SignOut() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_out(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public AccountStatusInfo Status() { + return CallWithPointer(thisPtr => FfiConverterTypeAccountStatusInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_status(thisPtr, ref _status) +))); + } + + + /// + public async Task UseLicenseKey(SecretString @key) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_use_license_key(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@key)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows, ulong? @totalRows, ShareColumnChoice[] @columns) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_create_share(thisPtr, FfiConverterTypeShareRequestArg.INSTANCE.Lower(@request), FfiConverterOptionalTypeResultSet.INSTANCE.Lower(@result), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterOptionalUInt64.INSTANCE.Lower(@totalRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCreatedShareInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ExtendShare(string @shareId, ShareExpiryTag @expiry) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_extend_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId), FfiConverterTypeShareExpiryTag.INSTANCE.Lower(@expiry)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeShareInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task FetchShared(string @token, SecretString? @password) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_fetch_shared(thisPtr, FfiConverterString.INSTANCE.Lower(@token), FfiConverterOptionalTypeSecretString.INSTANCE.Lower(@password)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSharedLinkInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ListShares(bool @liveOnly, string? @teamId, string? @cursor) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_list_shares(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@liveOnly), FfiConverterOptionalString.INSTANCE.Lower(@teamId), FfiConverterOptionalString.INSTANCE.Lower(@cursor)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSharePageInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RevokeShare(string @shareId) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_revoke_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ShareLimits() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_share_limits(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeShareLimitsInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + + +} +class FfiConverterTypeAccountService: FfiConverter { + public static FfiConverterTypeAccountService INSTANCE = new FfiConverterTypeAccountService(); + + + public override ulong Lower(AccountService value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override AccountService Lift(ulong value) { + return new AccountService(value); + } + + public override AccountService Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(AccountService value) { + return 8; + } + + public override void Write(AccountService value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IAiAssistant { + string? DefaultModel(AiProviderTag @provider); + /// + Task HasKey(AiProviderTag @provider); + /// + Task ListModels(AiSettingsArg @settings, CancelToken? @cancel); + AiModelInfo[] OfflineModels(AiProviderTag @provider); + AiReply Reply(DatabaseSession @session, AiSettingsArg @settings, AiChatArg @chat, AiReplyListener @listener); + /// + Task SetKey(AiProviderTag @provider, SecretString @key); + /// + Task StartConversation(DatabaseSession @session, AiConversationArg @conversation, CancelToken? @cancel); +} +internal class AiAssistant : IAiAssistant, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public AiAssistant(ulong pointer) { + this.pointer = pointer; + } + + ~AiAssistant() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_aiassistant(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_aiassistant(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek(); - if (checksum != 58553) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_can_seek` checksum `58553`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_next_page(); - if (checksum != 13025) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_next_page` checksum `13025`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_run(); - if (checksum != 28269) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_run` checksum `28269`, library returned `{checksum}`"); - } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql(); - if (checksum != 5883) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_view_sql` checksum `5883`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns(); - if (checksum != 21678) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablepageread_visible_columns` checksum `21678`, library returned `{checksum}`"); - } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_create(); - if (checksum != 55602) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_create` checksum `55602`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } + } + + + public string? DefaultModel(AiProviderTag @provider) { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_default_model(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), ref _status) +))); + } + + + /// + public async Task HasKey(AiProviderTag @provider) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_has_key(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + // Lift + (result) => FfiConverterBoolean.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ListModels(AiSettingsArg @settings, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_list_models(thisPtr, FfiConverterTypeAiSettingsArg.INSTANCE.Lower(@settings), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeAiModelInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public AiModelInfo[] OfflineModels(AiProviderTag @provider) { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeAiModelInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_offline_models(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), ref _status) +))); + } + + + public AiReply Reply(DatabaseSession @session, AiSettingsArg @settings, AiChatArg @chat, AiReplyListener @listener) { + return CallWithPointer(thisPtr => FfiConverterTypeAiReply.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_reply(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeAiSettingsArg.INSTANCE.Lower(@settings), FfiConverterTypeAiChatArg.INSTANCE.Lower(@chat), FfiConverterTypeAiReplyListener.INSTANCE.Lower(@listener), ref _status) +))); + } + + + /// + public async Task SetKey(AiProviderTag @provider, SecretString @key) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_set_key(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), FfiConverterTypeSecretString.INSTANCE.Lower(@key)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task StartConversation(DatabaseSession @session, AiConversationArg @conversation, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_start_conversation(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeAiConversationArg.INSTANCE.Lower(@conversation), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeAiConversationStart.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + + +} +class FfiConverterTypeAiAssistant: FfiConverter { + public static FfiConverterTypeAiAssistant INSTANCE = new FfiConverterTypeAiAssistant(); + + + public override ulong Lower(AiAssistant value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override AiAssistant Lift(ulong value) { + return new AiAssistant(value); + } + + public override AiAssistant Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(AiAssistant value) { + return 8; + } + + public override void Write(AiAssistant value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IAiReply { + void Cancel(); + AiReplyEvent[] DrainEvents(); +} +internal class AiReply : IAiReply, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public AiReply(ulong pointer) { + this.pointer = pointer; + } + + ~AiReply() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_aireply(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_aireply(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete(); - if (checksum != 19118) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_delete` checksum `19118`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_file(); - if (checksum != 22927) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_file` checksum `22927`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders(); - if (checksum != 42325) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_folders` checksum `42325`, library returned `{checksum}`"); - } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_items(); - if (checksum != 5594) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_items` checksum `5594`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_put(); - if (checksum != 33778) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_put` checksum `33778`, library returned `{checksum}`"); - } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename(); - if (checksum != 41173) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_rename` checksum `41173`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } + } + + + public void Cancel() { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_aireply_cancel(thisPtr, ref _status) +)); + } + + + + public AiReplyEvent[] DrainEvents() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeAiReplyEvent.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_aireply_drain_events(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeAiReply: FfiConverter { + public static FfiConverterTypeAiReply INSTANCE = new FfiConverterTypeAiReply(); + + + public override ulong Lower(AiReply value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override AiReply Lift(ulong value) { + return new AiReply(value); + } + + public override AiReply Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(AiReply value) { + return 8; + } + + public override void Write(AiReply value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +/// +/// A cancel the foreign side passes into an async call, since UniFFI +/// itself never cancels a call. C# fires it from a `CancellationToken`, +/// Swift from a task's cancellation handler. +/// +internal interface ICancelToken { + void Cancel(); + bool IsCancelled(); +} +/// +/// A cancel the foreign side passes into an async call, since UniFFI +/// itself never cancels a call. C# fires it from a `CancellationToken`, +/// Swift from a task's cancellation handler. +/// +internal class CancelToken : ICancelToken, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public CancelToken(ulong pointer) { + this.pointer = pointer; + } + + ~CancelToken() { + Destroy(); + } + public CancelToken() : + this( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_canceltoken_new( ref _status) +)) {} + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_canceltoken(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_canceltoken(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile(); - if (checksum != 42640) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_tablefolderstore_unfile` checksum `42640`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_canceltoken_new(); - if (checksum != 44262) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_canceltoken_new` checksum `44262`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_core_new(); - if (checksum != 11967) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_core_new` checksum `11967`, library returned `{checksum}`"); - } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets(); - if (checksum != 43052) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets` checksum `43052`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_constructor_exportprogress_new(); - if (checksum != 63262) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_exportprogress_new` checksum `63262`, library returned `{checksum}`"); - } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed(); - if (checksum != 24504) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed` checksum `24504`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } + } + + + public void Cancel() { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_cancel(thisPtr, ref _status) +)); + } + + + + public bool IsCancelled() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_is_cancelled(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeCancelToken: FfiConverter { + public static FfiConverterTypeCancelToken INSTANCE = new FfiConverterTypeCancelToken(); + + + public override ulong Lower(CancelToken value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override CancelToken Lift(ulong value) { + return new CancelToken(value); + } + + public override CancelToken Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(CancelToken value) { + return 8; + } + + public override void Write(CancelToken value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface ICatalogChange { + bool Destructive(); + SaveGate Gate(); + /// + Task Run(bool @confirmed, CancelToken? @cancel); + string[] Statements(); +} +internal class CatalogChange : ICatalogChange, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public CatalogChange(ulong pointer) { + this.pointer = pointer; + } + + ~CatalogChange() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_catalogchange(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_catalogchange(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out(); - if (checksum != 33179) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountlistener_signed_out` checksum `33179`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url(); - if (checksum != 39709) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url` checksum `39709`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate(); - if (checksum != 30636) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_authenticate` checksum `30636`, library returned `{checksum}`"); - } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel(); - if (checksum != 29099) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostwebauthenticator_cancel` checksum `29099`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending(); - if (checksum != 59424) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_aireplylistener_events_pending` checksum `59424`, library returned `{checksum}`"); - } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_load(); - if (checksum != 39136) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_load` checksum `39136`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } + } + + + public bool Destructive() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_destructive(thisPtr, ref _status) +))); + } + + + public SaveGate Gate() { + return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_gate(thisPtr, ref _status) +))); + } + + + /// + public async Task Run(bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCatalogChangeOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public string[] Statements() { + return CallWithPointer(thisPtr => FfiConverterSequenceString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_statements(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeCatalogChange: FfiConverter { + public static FfiConverterTypeCatalogChange INSTANCE = new FfiConverterTypeCatalogChange(); + + + public override ulong Lower(CatalogChange value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override CatalogChange Lift(ulong value) { + return new CatalogChange(value); + } + + public override CatalogChange Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(CatalogChange value) { + return 8; + } + + public override void Write(CatalogChange value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface CloudKitTransport { + /// + Task AccountStatus(); + /// + Task EnsureZone(string @account); + /// + Task DeleteZone(string @account); + /// + Task FetchChanges(string @account, byte[]? @token); + /// + Task FetchRecords(string @account, string[] @names); + /// + Task Modify(string @account, CloudKitRecord[] @saves, string[] @deletes); +} +internal class CloudKitTransportImpl : CloudKitTransport, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public CloudKitTransportImpl(ulong pointer) { + this.pointer = pointer; + } + + ~CloudKitTransportImpl() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_cloudkittransport(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_cloudkittransport(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_store(); - if (checksum != 40708) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_store` checksum `40708`, library returned `{checksum}`"); + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); } } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel(); - if (checksum != 50042) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel` checksum `50042`, library returned `{checksum}`"); - } + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete(); - if (checksum != 3306) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete` checksum `3306`, library returned `{checksum}`"); - } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection(); - if (checksum != 47390) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection` checksum `47390`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item(); - if (checksum != 56817) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item` checksum `56817`, library returned `{checksum}`"); - } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item(); - if (checksum != 48405) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item` checksum `48405`, library returned `{checksum}`"); - } + finally { + DecrementCallCounter(); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item(); - if (checksum != 58541) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_item` checksum `58541`, library returned `{checksum}`"); - } + } + + + /// + public async Task AccountStatus() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_account_status(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCloudKitAccount.INSTANCE.Lift(result), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + /// + public async Task EnsureZone(string @account) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_ensure_zone(thisPtr, FfiConverterString.INSTANCE.Lower(@account)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + /// + public async Task DeleteZone(string @account) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_delete_zone(thisPtr, FfiConverterString.INSTANCE.Lower(@account)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + /// + public async Task FetchChanges(string @account, byte[]? @token) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_fetch_changes(thisPtr, FfiConverterString.INSTANCE.Lower(@account), FfiConverterOptionalByteArray.INSTANCE.Lower(@token)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCloudKitChanges.INSTANCE.Lift(result), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + /// + public async Task FetchRecords(string @account, string[] @names) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_fetch_records(thisPtr, FfiConverterString.INSTANCE.Lower(@account), FfiConverterSequenceString.INSTANCE.Lower(@names)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeCloudKitFetched.INSTANCE.Lift(result), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + /// + public async Task Modify(string @account, CloudKitRecord[] @saves, string[] @deletes) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_cloudkittransport_modify(thisPtr, FfiConverterString.INSTANCE.Lower(@account), FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Lower(@saves), FfiConverterSequenceString.INSTANCE.Lower(@deletes)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeCloudKitOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCloudKitFailure.INSTANCE + ); + } + + + +} +class UniffiCallbackInterfaceCloudKitTransport { + static void AccountStatus(ulong @uniffiHandle,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection(); - if (checksum != 29837) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_open_connection` checksum `29837`, library returned `{checksum}`"); - } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting(); - if (checksum != 37925) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_is_connecting` checksum `37925`, library returned `{checksum}`"); + + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + + try { + try { + var result = + + await uniffiObject.AccountStatus() + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + ret.@returnValue = FfiConverterTypeCloudKitAccount.INSTANCE.Lower(result); + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_approve(); - if (checksum != 37501) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_approve` checksum `37501`, library returned `{checksum}`"); + + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); } + }, futureHandle.Cts.Token); + } + static void EnsureZone(ulong @uniffiHandle,RustBuffer @account,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw(); - if (checksum != 6775) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcpapphost_withdraw` checksum `6775`, library returned `{checksum}`"); - } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultVoid(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteVoid>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_mcplistener_changed(); - if (checksum != 6960) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_mcplistener_changed` checksum `6960`, library returned `{checksum}`"); + + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultVoid(); + ret.@callStatus = new UniffiRustCallStatus(); + + try { + try { + + await uniffiObject.EnsureZone( + FfiConverterString.INSTANCE.Lift(@account)) + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } } - } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostprompter_prompt(); - if (checksum != 46308) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostprompter_prompt` checksum `46308`, library returned `{checksum}`"); + + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteVoid>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); } + }, futureHandle.Cts.Token); + } + static void DeleteZone(ulong @uniffiHandle,RustBuffer @account,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); } - { - var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_runlistener_events_pending(); - if (checksum != 34969) { - throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_runlistener_events_pending` checksum `34969`, library returned `{checksum}`"); - } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultVoid(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteVoid>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; } - } -} -// Public interface members begin here. + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultVoid(); + ret.@callStatus = new UniffiRustCallStatus(); -#pragma warning disable 8625 + try { + try { + await uniffiObject.DeleteZone( + FfiConverterString.INSTANCE.Lift(@account)) + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteVoid>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); + } + }, futureHandle.Cts.Token); + } + static void FetchChanges(ulong @uniffiHandle,RustBuffer @account,RustBuffer @token,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); + } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; + } + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); -class FfiConverterUInt16: FfiConverter { - public static FfiConverterUInt16 INSTANCE = new FfiConverterUInt16(); + try { + try { + var result = - public override ushort Lift(ushort value) { - return value; - } + await uniffiObject.FetchChanges( + FfiConverterString.INSTANCE.Lift(@account), + FfiConverterOptionalByteArray.INSTANCE.Lift(@token)) + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + ret.@returnValue = FfiConverterTypeCloudKitChanges.INSTANCE.Lower(result); + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } - public override ushort Read(BigEndianStream stream) { - return stream.ReadUShort(); + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); + } + }, futureHandle.Cts.Token); } + static void FetchRecords(ulong @uniffiHandle,RustBuffer @account,RustBuffer @names,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); + } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; + } - public override ushort Lower(ushort value) { - return value; - } + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); - public override int AllocationSize(ushort value) { - return 2; - } + try { + try { + var result = - public override void Write(ushort value, BigEndianStream stream) { - stream.WriteUShort(value); + await uniffiObject.FetchRecords( + FfiConverterString.INSTANCE.Lift(@account), + FfiConverterSequenceString.INSTANCE.Lift(@names)) + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + ret.@returnValue = FfiConverterSequenceTypeCloudKitFetched.INSTANCE.Lower(result); + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); + } + }, futureHandle.Cts.Token); } -} + static void Modify(ulong @uniffiHandle,RustBuffer @account,RustBuffer @saves,RustBuffer @deletes,IntPtr @uniffiFutureCallback,ulong @uniffiCallbackData,IntPtr /*_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*/ @uniffiOutDroppedCallback) { + var handle = @uniffiHandle; + var futureHandle = new UniffiForeignFutureHandle(); + var foreignHandle = _UniFFIAsync._foreign_futures_map.Insert(futureHandle); + unsafe { + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).handle = foreignHandle; + (*(_UniFFILib.UniffiForeignFutureDroppedCallbackStruct*)@uniffiOutDroppedCallback).free = Marshal.GetFunctionPointerForDelegate(_UniFFIAsync.UniffiForeignFutureDroppedCallbackImpl.callback); + } + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower($"No callback in handlemap '{handle}'"); + } catch { } + var earlyCb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { earlyCb(@uniffiCallbackData, ret); }); + futureHandle.Dispose(); + return; + } + // Optimization: skip queuing if already cancelled before Task.Run schedules. + // TryInvokeCallback is the definitive cancellation guard inside the task body. + Task.Run(async () => { + var ret = new _UniFFILib.UniffiForeignFutureResultRustBuffer(); + ret.@callStatus = new UniffiRustCallStatus(); + try { + try { + var result = -class FfiConverterUInt32: FfiConverter { - public static FfiConverterUInt32 INSTANCE = new FfiConverterUInt32(); + await uniffiObject.Modify( + FfiConverterString.INSTANCE.Lift(@account), + FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Lift(@saves), + FfiConverterSequenceString.INSTANCE.Lift(@deletes)) + #if NET6_0_OR_GREATER + .WaitAsync(futureHandle.Cts.Token) + #endif + ; + ret.@returnValue = FfiConverterSequenceTypeCloudKitOutcome.INSTANCE.Lower(result); + + ret.@callStatus.code = UniffiCallbackResponseStatus.SUCCESS; + } catch (CloudKitFailure e) { + try { + ret.@callStatus.code = UniffiCallbackResponseStatus.ERROR; + ret.@callStatus.error_buf = FfiConverterTypeCloudKitFailure.INSTANCE.Lower(e); + } catch { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } catch (OperationCanceledException) when (futureHandle.Cts.IsCancellationRequested) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower("Future cancelled"); + } catch { } + } catch (System.Exception e) { + ret.@callStatus.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + ret.@callStatus.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } - public override uint Lift(uint value) { - return value; + + var cb = Marshal.GetDelegateForFunctionPointer<_UniFFILib.UniffiForeignFutureCompleteRustBuffer>(@uniffiFutureCallback); + futureHandle.InvokeCallbackOnce(() => { + cb(@uniffiCallbackData, ret); + }); + } finally { + futureHandle.Dispose(); + } + }, futureHandle.Cts.Token); } - public override uint Read(BigEndianStream stream) { - return stream.ReadUInt(); + static void UniffiFree(ulong @handle) { + FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.Remove(@handle); } - public override uint Lower(uint value) { - return value; + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeCloudKitTransport.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } } + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod0(AccountStatus); + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod1(EnsureZone); + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod2 _m2 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod2(DeleteZone); + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod3 _m3 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod3(FetchChanges); + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod4 _m4 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod4(FetchRecords); + static _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod5 _m5 = new _UniFFILib.UniffiCallbackInterfaceCloudKitTransportMethod5(Modify); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); - public override int AllocationSize(uint value) { - return 4; - } + private static GCHandle? _vtablePin; - public override void Write(uint value, BigEndianStream stream) { - stream.WriteUInt(value); + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceCloudKitTransport _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceCloudKitTransport { + @accountStatus = Marshal.GetFunctionPointerForDelegate(_m0), + @ensureZone = Marshal.GetFunctionPointerForDelegate(_m1), + @deleteZone = Marshal.GetFunctionPointerForDelegate(_m2), + @fetchChanges = Marshal.GetFunctionPointerForDelegate(_m3), + @fetchRecords = Marshal.GetFunctionPointerForDelegate(_m4), + @modify = Marshal.GetFunctionPointerForDelegate(_m5), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_cloudkittransport(_vtablePin.Value.AddrOfPinnedObject()); } } -class FfiConverterUInt64: FfiConverter { - public static FfiConverterUInt64 INSTANCE = new FfiConverterUInt64(); +class ConcurrentHandleMap where T: notnull { + readonly ConcurrentDictionary _map = new(); - public override ulong Lift(ulong value) { - return value; + // Handles are odd numbers (1, 3, 5, ...) — the lowest bit must always be set. + // Rust uses (handle & 1) to distinguish foreign-language handles from Rust Arc + // pointers, which are always even due to memory alignment. See uniffi_core/src/ffi/handle.rs. + const long HANDLE_INITIAL = 1; + const long HANDLE_DELTA = 2; + long _currentHandle = HANDLE_INITIAL - HANDLE_DELTA; + + public ulong Insert(T obj) { + var handle = (ulong)Interlocked.Add(ref _currentHandle, HANDLE_DELTA); + if (!_map.TryAdd(handle, obj)) { + throw new InternalException("ConcurrentHandleMap: Duplicate handle"); + } + return handle; } - public override ulong Read(BigEndianStream stream) { - return stream.ReadULong(); + public bool TryGet(ulong handle, [NotNullWhen(true)] out T? result) { + return _map.TryGetValue(handle, out result); } - public override ulong Lower(ulong value) { - return value; + public T Get(ulong handle) { + if (_map.TryGetValue(handle, out var result)) { + return result; + } else { + throw new InternalException("ConcurrentHandleMap: Invalid handle"); + } } - public override int AllocationSize(ulong value) { - return 8; + public bool Remove(ulong handle) { + return _map.TryRemove(handle, out _); } - public override void Write(ulong value, BigEndianStream stream) { - stream.WriteULong(value); + public bool Remove(ulong handle, [NotNullWhen(true)] out T? result) { + return _map.TryRemove(handle, out result); } } +static class UniffiCallbackResponseStatus { + public static sbyte SUCCESS = 0; + public static sbyte ERROR = 1; + public static sbyte UNEXPECTED_ERROR = 2; +} +class FfiConverterTypeCloudKitTransport: FfiConverter { + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public static FfiConverterTypeCloudKitTransport INSTANCE = new FfiConverterTypeCloudKitTransport(); + static FfiConverterTypeCloudKitTransport() { + UniffiCallbackInterfaceCloudKitTransport.Register(); + } -class FfiConverterInt64: FfiConverter { - public static FfiConverterInt64 INSTANCE = new FfiConverterInt64(); - - public override long Lift(long value) { - return value; + public override ulong Lower(CloudKitTransport value) { + if (value is CloudKitTransportImpl rustObj) { + // Rust-implemented object. Clone the handle and return it. + return rustObj.CallWithPointer(thisPtr => thisPtr); + } else { + // C# object, generate a new handle map entry and return it. + return handleMap.Insert(value); + } } - public override long Read(BigEndianStream stream) { - return stream.ReadLong(); + public override CloudKitTransport Lift(ulong value) { + if ((value & 1UL) == 0UL) { + // Rust-generated handle, construct a new wrapper. + return new CloudKitTransportImpl(value); + } else { + // C#-generated handle, retrieve and remove from the handle map. + if (handleMap.Remove(value, out var obj)) { + return obj; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } } - public override long Lower(long value) { - return value; + public override CloudKitTransport Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); } - public override int AllocationSize(long value) { + public override int AllocationSize(CloudKitTransport value) { return 8; } - public override void Write(long value, BigEndianStream stream) { - stream.WriteLong(value); + public override void Write(CloudKitTransport value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); } } -class FfiConverterBoolean: FfiConverter { - public static FfiConverterBoolean INSTANCE = new FfiConverterBoolean(); +internal interface ICompletionList { + CompletionPage Rank(string @word, uint @limit); + string Word(); + uint WordStart(); +} +internal class CompletionList : ICompletionList, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; - public override bool Lift(sbyte value) { - return value != 0; + public CompletionList(ulong pointer) { + this.pointer = pointer; } - public override bool Read(BigEndianStream stream) { - return Lift(stream.ReadSByte()); + ~CompletionList() { + Destroy(); } - public override sbyte Lower(bool value) { - return value ? (sbyte)1 : (sbyte)0; + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_completionlist(this.pointer, ref status); + }); } - public override int AllocationSize(bool value) { - return (sbyte)1; + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_completionlist(this.pointer, ref status); + }); } - public override void Write(bool value, BigEndianStream stream) { - stream.WriteSByte(Lower(value)); + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } } -} + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); -class FfiConverterString: FfiConverter { - public static FfiConverterString INSTANCE = new FfiConverterString(); + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } - // 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. - public override string Lift(RustBuffer value) { - try { - unsafe { - return System.Text.Encoding.UTF8.GetString( - (byte*)value.data.ToPointer(), Convert.ToInt32(value.len)); - } - } finally { - RustBuffer.Free(value); + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); } } - public override string Read(BigEndianStream stream) { - var length = stream.ReadInt(); - return stream.ReadUtf8String(length); + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } - public override RustBuffer Lower(string value) { - var rustBuffer = RustBuffer.Alloc(System.Text.Encoding.UTF8.GetByteCount(value)); + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); try { - unsafe { - fixed (char* chars = value) { - System.Text.Encoding.UTF8.GetBytes( - chars, value.Length, (byte*)rustBuffer.data.ToPointer(), Convert.ToInt32(rustBuffer.len)); - } - } - return rustBuffer; - } catch { - RustBuffer.Free(rustBuffer); - throw; + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); } } - // TODO(CS) - // We aren't sure exactly how many bytes our string will be once it's UTF-8 - // encoded. Allocate 3 bytes per unicode codepoint which will always be - // enough. - public override int AllocationSize(string value) { - const int sizeForLength = 4; - var sizeForString = System.Text.Encoding.UTF8.GetByteCount(value); - return sizeForLength + sizeForString; + + public CompletionPage Rank(string @word, uint @limit) { + return CallWithPointer(thisPtr => FfiConverterTypeCompletionPage.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_rank(thisPtr, FfiConverterString.INSTANCE.Lower(@word), FfiConverterUInt32.INSTANCE.Lower(@limit), ref _status) +))); } - - public override void Write(string value, BigEndianStream stream) { - stream.WriteUtf8String(value); + + + public string Word() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_word(thisPtr, ref _status) +))); } -} + + + public uint WordStart() { + return CallWithPointer(thisPtr => FfiConverterUInt32.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_word_start(thisPtr, ref _status) +))); + } + + + +} +class FfiConverterTypeCompletionList: FfiConverter { + public static FfiConverterTypeCompletionList INSTANCE = new FfiConverterTypeCompletionList(); + public override ulong Lower(CompletionList value) { + return value.CallWithPointer(thisPtr => thisPtr); + } -class FfiConverterByteArray: FfiConverterRustBuffer { - public static FfiConverterByteArray INSTANCE = new FfiConverterByteArray(); + public override CompletionList Lift(ulong value) { + return new CompletionList(value); + } - public override byte[] Read(BigEndianStream stream) { - var length = stream.ReadInt(); - return stream.ReadBytes(length); + public override CompletionList Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); } - public override int AllocationSize(byte[] value) { - return 4 + value.Length; + public override int AllocationSize(CompletionList value) { + return 8; } - public override void Write(byte[] value, BigEndianStream stream) { - stream.WriteInt(value.Length); - stream.WriteBytes(value); + public override void Write(CompletionList value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); } } -internal interface IAccountService { +internal interface IConnectionLibrary { /// - Task AccessToken(); - Task AccessTokenRejected(SecretString @token); - bool AllowsTableproRequests(); - void ApplyPolicy(ManagedPolicyArg @policy); + Task ApplyCloudPull(CloudLibraryPull @pull); /// - Task ChooseServer(string? @url); + Task CloudEdits(CloudLibraryRecords @base); /// - Task Devices(); - FeatureAccessTag FeatureAccess(string @feature); + Task AddFavorites(string[] @ids, string? @before); /// - Task ImportOfflineFile(string @path); - ServerLicenseInfo? License(); + Task CreateGroup(string @name, string? @parentId); /// - Task Profile(); + Task CreateTag(string @name, string @color); /// - Task Refresh(); + Task Delete(string @id); /// - Task RefreshPastDeviceLimit(); + Task DeleteGroup(string @id); /// - Task RemoveDevice(string @deviceId); - ServerInfo Server(); + Task DeleteTag(string @id); /// - Task SignIn(CancelToken? @cancel); + Task Duplicate(string @id, string @name); /// - Task SignOut(); - AccountStatusInfo Status(); + Task ExportFile(string @path); /// - Task UseLicenseKey(SecretString @key); + Task ImportFile(string @path); /// - Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows, ulong? @totalRows, ShareColumnChoice[] @columns); + Task MoveGroups(string[] @ids, string? @parentId, string? @before); /// - Task ExtendShare(string @shareId, ShareExpiryTag @expiry); + Task MoveToGroup(string[] @ids, string? @groupId, string? @before); /// - Task FetchShared(string @token, SecretString? @password); + Task RemoveFavorites(string[] @ids); /// - Task ListShares(bool @liveOnly, string? @teamId, string? @cursor); + Task RenameConnection(string @id, string @name); /// - Task RevokeShare(string @shareId); + Task RenameGroup(string @id, string @name); /// - Task ShareLimits(); + Task Save(ConnectionRecord @record, ConnectionSecrets @secrets); + /// + Task SetFavorite(string @id, bool @favorite); + /// + Task SetGroupColor(string @id, string? @color); + /// + Task Snapshot(); + /// + Task TagConnections(string[] @ids, string @tagId, bool @tagged); + /// + Task UpdateTag(string @id, string @name, string @color); + /// + Task ConnectionDetails(string @id); + /// + Task CredentialProfiles(); + /// + Task DeleteCredentialProfile(string @id); + /// + Task DeleteSshProfile(string @id); + /// + Task DeviceSettings(string @id); + /// + Task SaveCredentialProfile(CredentialProfileRecord @profile); + /// + Task SaveSshProfile(SshProfileRecord @profile); + /// + Task SetConnectionDetails(string @id, ConnectionDetailsRecord @details); + /// + Task SetDeviceSettings(string @id, DeviceSettingsRecord @settings); + /// + Task SshProfiles(); } -internal class AccountService : IAccountService, IDisposable { +internal class ConnectionLibrary : IConnectionLibrary, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public AccountService(ulong pointer) { + public ConnectionLibrary(ulong pointer) { this.pointer = pointer; } - ~AccountService() { + ~ConnectionLibrary() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_accountservice(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_connectionlibrary(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_accountservice(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_connectionlibrary(this.pointer, ref status); }); } @@ -10618,11 +15212,29 @@ internal T CallWithPointer(Func func) /// - public async Task AccessToken() { + public async Task ApplyCloudPull(CloudLibraryPull @pull) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_apply_cloud_pull(thisPtr, FfiConverterTypeCloudLibraryPull.INSTANCE.Lower(@pull)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task CloudEdits(CloudLibraryRecords @base) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_access_token(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_cloud_edits(thisPtr, FfiConverterTypeCloudLibraryRecords.INSTANCE.Lower(@base)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10633,16 +15245,17 @@ public async Task AccessToken() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeAccessTokenInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeCloudLibraryRecords.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public async Task AccessTokenRejected(SecretString @token) {await _UniFFIAsync.UniffiRustCallAsync( + /// + public async Task AddFavorites(string[] @ids, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_access_token_rejected(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@token)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_add_favorites(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@before)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10652,52 +15265,38 @@ public async Task AccessTokenRejected(SecretString @token) {await _UniFFIAsync.U // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error - NullCallStatusErrorHandler.INSTANCE - + FfiConverterTypeCoreError.INSTANCE ); } - public bool AllowsTableproRequests() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_allows_tablepro_requests(thisPtr, ref _status) -))); - } - - - public void ApplyPolicy(ManagedPolicyArg @policy) { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_apply_policy(thisPtr, FfiConverterTypeManagedPolicyArg.INSTANCE.Lower(@policy), ref _status) -)); - } - - - /// - public async Task ChooseServer(string? @url) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task CreateGroup(string @name, string? @parentId) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_choose_server(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@url)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_create_group(thisPtr, FfiConverterString.INSTANCE.Lower(@name), FfiConverterOptionalString.INSTANCE.Lower(@parentId)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeGroupRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Devices() { + public async Task CreateTag(string @name, string @color) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_devices(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_create_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@name), FfiConverterString.INSTANCE.Lower(@color)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10708,25 +15307,35 @@ public async Task Devices() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeDeviceInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeTagRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public FeatureAccessTag FeatureAccess(string @feature) { - return CallWithPointer(thisPtr => FfiConverterTypeFeatureAccessTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_feature_access(thisPtr, FfiConverterString.INSTANCE.Lower(@feature), ref _status) -))); + /// + public async Task Delete(string @id) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task ImportOfflineFile(string @path) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task DeleteGroup(string @id) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_import_offline_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_group(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10740,20 +15349,30 @@ public async Task ImportOfflineFile(string @path) {await _UniFFIAsync.UniffiRust ); } - public ServerLicenseInfo? License() { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeServerLicenseInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_license(thisPtr, ref _status) -))); + /// + public async Task DeleteTag(string @id) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task Profile() { + public async Task Duplicate(string @id, string @name) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_profile(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_duplicate(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10764,57 +15383,61 @@ public async Task Profile() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeProfileInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeConnectionRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Refresh() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task ExportFile(string @path) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_export_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u32(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u32(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u32(future), + // Lift + (result) => FfiConverterUInt32.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RefreshPastDeviceLimit() { + public async Task ImportFile(string @path) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh_past_device_limit(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_import_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterBoolean.INSTANCE.Lift(result), + (result) => FfiConverterTypeImportSummary.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RemoveDevice(string @deviceId) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task MoveGroups(string[] @ids, string? @parentId, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_remove_device(thisPtr, FfiConverterString.INSTANCE.Lower(@deviceId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_move_groups(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@parentId), FfiConverterOptionalString.INSTANCE.Lower(@before)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10828,19 +15451,11 @@ public async Task RemoveDevice(string @deviceId) {await _UniFFIAsync.UniffiRustC ); } - public ServerInfo Server() { - return CallWithPointer(thisPtr => FfiConverterTypeServerInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_server(thisPtr, ref _status) -))); - } - - /// - public async Task SignIn(CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task MoveToGroup(string[] @ids, string? @groupId, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_in(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_move_to_group(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@groupId), FfiConverterOptionalString.INSTANCE.Lower(@before)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10855,10 +15470,10 @@ public async Task SignIn(CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCal } /// - public async Task SignOut() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task RemoveFavorites(string[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_out(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_remove_favorites(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10872,19 +15487,29 @@ public async Task SignOut() {await _UniFFIAsync.UniffiRustCallAsync( ); } - public AccountStatusInfo Status() { - return CallWithPointer(thisPtr => FfiConverterTypeAccountStatusInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_status(thisPtr, ref _status) -))); + /// + public async Task RenameConnection(string @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_connection(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task UseLicenseKey(SecretString @key) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task RenameGroup(string @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_use_license_key(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@key)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_group(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -10899,11 +15524,11 @@ public async Task UseLicenseKey(SecretString @key) {await _UniFFIAsync.UniffiRus } /// - public async Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows, ulong? @totalRows, ShareColumnChoice[] @columns) { + public async Task Save(ConnectionRecord @record, ConnectionSecrets @secrets) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_create_share(thisPtr, FfiConverterTypeShareRequestArg.INSTANCE.Lower(@request), FfiConverterOptionalTypeResultSet.INSTANCE.Lower(@result), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterOptionalUInt64.INSTANCE.Lower(@totalRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10914,62 +15539,54 @@ public async Task CreateShare(ShareRequestArg @request, Result // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeCreatedShareInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeConnectionRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ExtendShare(string @shareId, ShareExpiryTag @expiry) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task SetFavorite(string @id, bool @favorite) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_extend_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId), FfiConverterTypeShareExpiryTag.INSTANCE.Lower(@expiry)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_favorite(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterBoolean.INSTANCE.Lower(@favorite)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeShareInfo.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task FetchShared(string @token, SecretString? @password) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task SetGroupColor(string @id, string? @color) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_fetch_shared(thisPtr, FfiConverterString.INSTANCE.Lower(@token), FfiConverterOptionalTypeSecretString.INSTANCE.Lower(@password)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_group_color(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@color)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeSharedLinkInfo.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ListShares(bool @liveOnly, string? @teamId, string? @cursor) { + public async Task Snapshot() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_list_shares(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@liveOnly), FfiConverterOptionalString.INSTANCE.Lower(@teamId), FfiConverterOptionalString.INSTANCE.Lower(@cursor)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_snapshot(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -10980,17 +15597,17 @@ public async Task ListShares(bool @liveOnly, string? @teamId, str // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeSharePageInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeLibrarySnapshot.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RevokeShare(string @shareId) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task TagConnections(string[] @ids, string @tagId, bool @tagged) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_revoke_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_tag_connections(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterString.INSTANCE.Lower(@tagId), FfiConverterBoolean.INSTANCE.Lower(@tagged)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -11005,195 +15622,51 @@ public async Task RevokeShare(string @shareId) {await _UniFFIAsync.UniffiRustCal } /// - public async Task ShareLimits() { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task UpdateTag(string @id, string @name, string @color) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_share_limits(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_update_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name), FfiConverterString.INSTANCE.Lower(@color)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeShareLimitsInfo.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } - - -} -class FfiConverterTypeAccountService: FfiConverter { - public static FfiConverterTypeAccountService INSTANCE = new FfiConverterTypeAccountService(); - - - public override ulong Lower(AccountService value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override AccountService Lift(ulong value) { - return new AccountService(value); - } - - public override AccountService Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(AccountService value) { - return 8; - } - - public override void Write(AccountService value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface IAiAssistant { - string? DefaultModel(AiProviderTag @provider); - /// - Task HasKey(AiProviderTag @provider); - /// - Task ListModels(AiSettingsArg @settings, CancelToken? @cancel); - AiModelInfo[] OfflineModels(AiProviderTag @provider); - AiReply Reply(DatabaseSession @session, AiSettingsArg @settings, AiChatArg @chat, AiReplyListener @listener); - /// - Task SetKey(AiProviderTag @provider, SecretString @key); - /// - Task StartConversation(DatabaseSession @session, AiConversationArg @conversation, CancelToken? @cancel); -} -internal class AiAssistant : IAiAssistant, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public AiAssistant(ulong pointer) { - this.pointer = pointer; - } - - ~AiAssistant() { - Destroy(); - } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_aiassistant(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_aiassistant(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - - public string? DefaultModel(AiProviderTag @provider) { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_default_model(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), ref _status) -))); - } - - /// - public async Task HasKey(AiProviderTag @provider) { + public async Task ConnectionDetails(string @id) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_has_key(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_connection_details(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterBoolean.INSTANCE.Lift(result), + (result) => FfiConverterTypeConnectionDetailsRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ListModels(AiSettingsArg @settings, CancelToken? @cancel) { + public async Task CredentialProfiles() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_list_models(thisPtr, FfiConverterTypeAiSettingsArg.INSTANCE.Lower(@settings), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_credential_profiles(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -11204,422 +15677,263 @@ public async Task ListModels(AiSettingsArg @settings, CancelToken // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeAiModelInfo.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeCredentialProfileRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public AiModelInfo[] OfflineModels(AiProviderTag @provider) { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeAiModelInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_offline_models(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), ref _status) -))); - } - - - public AiReply Reply(DatabaseSession @session, AiSettingsArg @settings, AiChatArg @chat, AiReplyListener @listener) { - return CallWithPointer(thisPtr => FfiConverterTypeAiReply.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_reply(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeAiSettingsArg.INSTANCE.Lower(@settings), FfiConverterTypeAiChatArg.INSTANCE.Lower(@chat), FfiConverterTypeAiReplyListener.INSTANCE.Lower(@listener), ref _status) -))); - } - - /// - public async Task SetKey(AiProviderTag @provider, SecretString @key) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task DeleteCredentialProfile(string @id) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_set_key(thisPtr, FfiConverterTypeAiProviderTag.INSTANCE.Lower(@provider), FfiConverterTypeSecretString.INSTANCE.Lower(@key)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_credential_profile(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + // Lift + (result) => FfiConverterBoolean.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task StartConversation(DatabaseSession @session, AiConversationArg @conversation, CancelToken? @cancel) { + public async Task DeleteSshProfile(string @id) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_aiassistant_start_conversation(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeAiConversationArg.INSTANCE.Lower(@conversation), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_ssh_profile(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), // Lift - (result) => FfiConverterTypeAiConversationStart.INSTANCE.Lift(result), + (result) => FfiConverterBoolean.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - - - -} -class FfiConverterTypeAiAssistant: FfiConverter { - public static FfiConverterTypeAiAssistant INSTANCE = new FfiConverterTypeAiAssistant(); - - - public override ulong Lower(AiAssistant value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override AiAssistant Lift(ulong value) { - return new AiAssistant(value); - } - - public override AiAssistant Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(AiAssistant value) { - return 8; - } - - public override void Write(AiAssistant value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface IAiReply { - void Cancel(); - AiReplyEvent[] DrainEvents(); -} -internal class AiReply : IAiReply, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public AiReply(ulong pointer) { - this.pointer = pointer; - } - - ~AiReply() { - Destroy(); - } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_aireply(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_aireply(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - - public void Cancel() { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_aireply_cancel(thisPtr, ref _status) -)); - } - - - - public AiReplyEvent[] DrainEvents() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeAiReplyEvent.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_aireply_drain_events(thisPtr, ref _status) -))); - } - - - - -} -class FfiConverterTypeAiReply: FfiConverter { - public static FfiConverterTypeAiReply INSTANCE = new FfiConverterTypeAiReply(); - - - public override ulong Lower(AiReply value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override AiReply Lift(ulong value) { - return new AiReply(value); - } - - public override AiReply Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(AiReply value) { - return 8; - } - - public override void Write(AiReply value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -/// -/// A cancel the foreign side passes into an async call, since UniFFI -/// itself never cancels a call. C# fires it from a `CancellationToken`, -/// Swift from a task's cancellation handler. -/// -internal interface ICancelToken { - void Cancel(); - bool IsCancelled(); -} -/// -/// A cancel the foreign side passes into an async call, since UniFFI -/// itself never cancels a call. C# fires it from a `CancellationToken`, -/// Swift from a task's cancellation handler. -/// -internal class CancelToken : ICancelToken, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public CancelToken(ulong pointer) { - this.pointer = pointer; - } - - ~CancelToken() { - Destroy(); - } - public CancelToken() : - this( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_canceltoken_new( ref _status) -)) {} - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_canceltoken(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_canceltoken(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + + /// + public async Task DeviceSettings(string @id) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_device_settings(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeDeviceSettingsRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public void Cancel() { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_cancel(thisPtr, ref _status) -)); + /// + public async Task SaveCredentialProfile(CredentialProfileRecord @profile) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save_credential_profile(thisPtr, FfiConverterTypeCredentialProfileRecord.INSTANCE.Lower(@profile)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCredentialProfileRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task SaveSshProfile(SshProfileRecord @profile) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save_ssh_profile(thisPtr, FfiConverterTypeSshProfileRecord.INSTANCE.Lower(@profile)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSshProfileRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// + public async Task SetConnectionDetails(string @id, ConnectionDetailsRecord @details) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_connection_details(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterTypeConnectionDetailsRecord.INSTANCE.Lower(@details)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - public bool IsCancelled() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_is_cancelled(thisPtr, ref _status) -))); + /// + public async Task SetDeviceSettings(string @id, DeviceSettingsRecord @settings) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_device_settings(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterTypeDeviceSettingsRecord.INSTANCE.Lower(@settings)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task SshProfiles() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_ssh_profiles(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeSshProfileRecord.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } } -class FfiConverterTypeCancelToken: FfiConverter { - public static FfiConverterTypeCancelToken INSTANCE = new FfiConverterTypeCancelToken(); +class FfiConverterTypeConnectionLibrary: FfiConverter { + public static FfiConverterTypeConnectionLibrary INSTANCE = new FfiConverterTypeConnectionLibrary(); - public override ulong Lower(CancelToken value) { + public override ulong Lower(ConnectionLibrary value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override CancelToken Lift(ulong value) { - return new CancelToken(value); + public override ConnectionLibrary Lift(ulong value) { + return new ConnectionLibrary(value); } - public override CancelToken Read(BigEndianStream stream) { + public override ConnectionLibrary Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(CancelToken value) { + public override int AllocationSize(ConnectionLibrary value) { return 8; } - public override void Write(CancelToken value, BigEndianStream stream) { + public override void Write(ConnectionLibrary value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface ICatalogChange { - bool Destructive(); - SaveGate Gate(); +internal interface ICore { /// - Task Run(bool @confirmed, CancelToken? @cancel); - string[] Statements(); + Task OpenAccount(AccountConfig @config, HostBrowser @browser, HostWebAuthenticator? @webAuthenticator, AccountListener @listener); + AiAssistant AiAssistant(); + /// + Task ConnectSaved(string @id, string? @database, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel); + DriverInfo[] Drivers(); + /// + Task History(); + /// + ConnectionLibrary Library(); + /// + Task OpenFile(FileOpenRequest @request, CancelToken? @cancel); + /// + Task TestConnection(ConnectionRecord @record, ConnectionSecrets @secrets, HostPrompter? @prompter, CancelToken? @cancel); + /// + Task ForeignSources(ForeignAppDirsArg @dirs, ScanDepthTag @depth); + /// + Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel); + /// + Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts); + /// + McpService McpServer(McpAppHost @host, McpListener @listener); + /// + SyncService OpenSync(SyncConfig @config, AccountService @account, CloudKitTransport? @cloudkit, HostSettings? @settings, HostDeviceStore? @deviceStore, HostLegacyMirror? @legacyMirror, SyncListener @listener); } -internal class CatalogChange : ICatalogChange, IDisposable { +internal class Core : ICore, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public CatalogChange(ulong pointer) { + public Core(ulong pointer) { this.pointer = pointer; } - ~CatalogChange() { + ~Core() { Destroy(); } + public Core(HostConfig @config, HostSecrets @secrets) : + this( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_new(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), FfiConverterTypeHostSecrets.INSTANCE.Lower(@secrets), ref _status) +)) {} protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_catalogchange(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_core(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_catalogchange(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_core(this.pointer, ref status); }); } @@ -11687,28 +16001,143 @@ internal T CallWithPointer(Func func) } - public bool Destructive() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + /// + public async Task OpenAccount(AccountConfig @config, HostBrowser @browser, HostWebAuthenticator? @webAuthenticator, AccountListener @listener) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_account(thisPtr, FfiConverterTypeAccountConfig.INSTANCE.Lower(@config), FfiConverterTypeHostBrowser.INSTANCE.Lower(@browser), FfiConverterOptionalTypeHostWebAuthenticator.INSTANCE.Lower(@webAuthenticator), FfiConverterTypeAccountListener.INSTANCE.Lower(@listener)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeAccountService.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public AiAssistant AiAssistant() { + return CallWithPointer(thisPtr => FfiConverterTypeAiAssistant.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_destructive(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_core_ai_assistant(thisPtr, ref _status) ))); } - public SaveGate Gate() { - return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( + /// + public async Task ConnectSaved(string @id, string? @database, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_connect_saved(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@keep), FfiConverterOptionalTypeHostPrompter.INSTANCE.Lower(@prompter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeDatabaseSession.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public DriverInfo[] Drivers() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeDriverInfo.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_gate(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_core_drivers(thisPtr, ref _status) ))); } /// - public async Task Run(bool @confirmed, CancelToken? @cancel) { + public async Task History() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_history(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeQueryHistoryStore.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public ConnectionLibrary Library() { + return CallWithPointer(thisPtr => FfiConverterTypeConnectionLibrary.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_core_library(thisPtr, ref _status) +))); + } + + + /// + public async Task OpenFile(FileOpenRequest @request, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_file(thisPtr, FfiConverterTypeFileOpenRequest.INSTANCE.Lower(@request), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeDatabaseSession.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task TestConnection(ConnectionRecord @record, ConnectionSecrets @secrets, HostPrompter? @prompter, CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_test_connection(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets), FfiConverterOptionalTypeHostPrompter.INSTANCE.Lower(@prompter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ForeignSources(ForeignAppDirsArg @dirs, ScanDepthTag @depth) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_foreign_sources(thisPtr, FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs), FfiConverterTypeScanDepthTag.INSTANCE.Lower(@depth)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -11719,77 +16148,141 @@ public async Task Run(bool @confirmed, CancelToken? @cance // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeCatalogChangeOutcome.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeForeignSourceInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public string[] Statements() { - return CallWithPointer(thisPtr => FfiConverterSequenceString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_catalogchange_statements(thisPtr, ref _status) + /// + public async Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_read_foreign(thisPtr, FfiConverterTypeForeignAppTag.INSTANCE.Lower(@app), FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs), FfiConverterOptionalString.INSTANCE.Lower(@file), FfiConverterTypeForeignImportRequest.INSTANCE.Lower(@request), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeForeignImportReview.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_forget_changed_host_key(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterString.INSTANCE.Lower(@host), FfiConverterString.INSTANCE.Lower(@knownHosts)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public McpService McpServer(McpAppHost @host, McpListener @listener) { + return CallWithPointer(thisPtr => FfiConverterTypeMcpService.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_core_mcp_server(thisPtr, FfiConverterTypeMcpAppHost.INSTANCE.Lower(@host), FfiConverterTypeMcpListener.INSTANCE.Lower(@listener), ref _status) +))); + } + + + /// + public SyncService OpenSync(SyncConfig @config, AccountService @account, CloudKitTransport? @cloudkit, HostSettings? @settings, HostDeviceStore? @deviceStore, HostLegacyMirror? @legacyMirror, SyncListener @listener) { + return CallWithPointer(thisPtr => FfiConverterTypeSyncService.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_sync(thisPtr, FfiConverterTypeSyncConfig.INSTANCE.Lower(@config), FfiConverterTypeAccountService.INSTANCE.Lower(@account), FfiConverterOptionalTypeCloudKitTransport.INSTANCE.Lower(@cloudkit), FfiConverterOptionalTypeHostSettings.INSTANCE.Lower(@settings), FfiConverterOptionalTypeHostDeviceStore.INSTANCE.Lower(@deviceStore), FfiConverterOptionalTypeHostLegacyMirror.INSTANCE.Lower(@legacyMirror), FfiConverterTypeSyncListener.INSTANCE.Lower(@listener), ref _status) ))); } + /// + public static Core WithSystemSecrets(HostConfig @config) { + return new Core( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_with_system_secrets(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), ref _status) +)); + } + + } -class FfiConverterTypeCatalogChange: FfiConverter { - public static FfiConverterTypeCatalogChange INSTANCE = new FfiConverterTypeCatalogChange(); +class FfiConverterTypeCore: FfiConverter { + public static FfiConverterTypeCore INSTANCE = new FfiConverterTypeCore(); - public override ulong Lower(CatalogChange value) { + public override ulong Lower(Core value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override CatalogChange Lift(ulong value) { - return new CatalogChange(value); + public override Core Lift(ulong value) { + return new Core(value); } - public override CatalogChange Read(BigEndianStream stream) { + public override Core Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(CatalogChange value) { + public override int AllocationSize(Core value) { return 8; } - public override void Write(CatalogChange value, BigEndianStream stream) { + public override void Write(Core value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface ICompletionList { - CompletionPage Rank(string @word, uint @limit); - string Word(); - uint WordStart(); +internal interface ICsvImport { + ImportColumnInfo[] Columns(); + /// + Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping); + /// + Task Preview(string @path, CsvReadOptions @options); + /// + Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel); + uint?[] SuggestMapping(string[] @headers); } -internal class CompletionList : ICompletionList, IDisposable { +internal class CsvImport : ICsvImport, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public CompletionList(ulong pointer) { + public CsvImport(ulong pointer) { this.pointer = pointer; } - ~CompletionList() { + ~CsvImport() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_completionlist(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_csvimport(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_completionlist(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_csvimport(this.pointer, ref status); }); } @@ -11857,26 +16350,84 @@ internal T CallWithPointer(Func func) } - public CompletionPage Rank(string @word, uint @limit) { - return CallWithPointer(thisPtr => FfiConverterTypeCompletionPage.INSTANCE.Lift( + public ImportColumnInfo[] Columns() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeImportColumnInfo.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_rank(thisPtr, FfiConverterString.INSTANCE.Lower(@word), FfiConverterUInt32.INSTANCE.Lower(@limit), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_columns(thisPtr, ref _status) ))); } - public string Word() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_word(thisPtr, ref _status) -))); + /// + public async Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_plan(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options), FfiConverterSequenceOptionalUInt32.INSTANCE.Lower(@mapping)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCsvImportCheck.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task Preview(string @path, CsvReadOptions @options) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_preview(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCsvPreview.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - public uint WordStart() { - return CallWithPointer(thisPtr => FfiConverterUInt32.INSTANCE.Lift( + /// + public async Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_run(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@plan), FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCsvImportOutcome.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public uint?[] SuggestMapping(string[] @headers) { + return CallWithPointer(thisPtr => FfiConverterSequenceOptionalUInt32.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_completionlist_word_start(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_suggest_mapping(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@headers), ref _status) ))); } @@ -11884,121 +16435,124 @@ public uint WordStart() { } -class FfiConverterTypeCompletionList: FfiConverter { - public static FfiConverterTypeCompletionList INSTANCE = new FfiConverterTypeCompletionList(); +class FfiConverterTypeCsvImport: FfiConverter { + public static FfiConverterTypeCsvImport INSTANCE = new FfiConverterTypeCsvImport(); - public override ulong Lower(CompletionList value) { + public override ulong Lower(CsvImport value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override CompletionList Lift(ulong value) { - return new CompletionList(value); + public override CsvImport Lift(ulong value) { + return new CsvImport(value); } - public override CompletionList Read(BigEndianStream stream) { + public override CsvImport Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(CompletionList value) { + public override int AllocationSize(CsvImport value) { return 8; } - public override void Write(CompletionList value, BigEndianStream stream) { + public override void Write(CsvImport value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IConnectionLibrary { - /// - Task ApplyCloudPull(CloudLibraryPull @pull); - /// - Task CloudEdits(CloudLibraryRecords @base); - /// - Task AddFavorites(string[] @ids, string? @before); - /// - Task CreateGroup(string @name, string? @parentId); - /// - Task CreateTag(string @name, string @color); - /// - Task Delete(string @id); +internal interface IDatabaseSession { + CatalogAbilities CatalogAbilities(); /// - Task DeleteGroup(string @id); + Task DatabaseChoices(CancelToken? @cancel); /// - Task DeleteTag(string @id); + CatalogChange PlanCatalogChange(CatalogOperation @operation); + bool ProtectsDatabase(string @name); + bool ProtectsSchema(string @name); /// - Task Duplicate(string @id, string @name); + Task RefreshSchemas(CancelToken? @cancel); /// - Task ExportFile(string @path); + Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, ExportProgress? @progress, CancelToken? @cancel); /// - Task ImportFile(string @path); + Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, ExportProgress? @progress, CancelToken? @cancel); /// - Task MoveGroups(string[] @ids, string? @parentId, string? @before); + Task OpenCsvImport(TableName @table, CancelToken? @cancel); /// - Task MoveToGroup(string[] @ids, string? @groupId, string? @before); + Task TableKeys(TableName @table, CancelToken? @cancel); /// - Task RemoveFavorites(string[] @ids); + Task Close(); /// - Task RenameConnection(string @id, string @name); + Task Columns(TableName @table, CancelToken? @cancel); /// - Task RenameGroup(string @id, string @name); + Task Complete(string @text, uint @caret, bool @asked, string? @database, CancelToken? @cancel); + string? Database(); + DatabaseLayoutTag DatabaseLayout(); /// - Task Save(ConnectionRecord @record, ConnectionSecrets @secrets); + Task Databases(CancelToken? @cancel); + string DriverId(); /// - Task SetFavorite(string @id, bool @favorite); + Task FilterChoices(TableName @table, CancelToken? @cancel); + RunGate GateRun(string @sql); + SessionHealthTag Health(); /// - Task SetGroupColor(string @id, string? @color); + Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel); + string Id(); + string Name(); /// - Task Snapshot(); + Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel); /// - Task TagConnections(string[] @ids, string @tagId, bool @tagged); + Task Objects(ObjectScopeArg @scope, CancelToken? @cancel); /// - Task UpdateTag(string @id, string @name, string @color); + Task OpenEditor(string? @database, CancelToken? @cancel); + KeyReader OpenKey(string @key); + bool ReadOnly(); /// - Task ConnectionDetails(string @id); + Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel); + void Reconnect(); /// - Task CredentialProfiles(); + Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel); /// - Task DeleteCredentialProfile(string @id); + Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel); /// - Task DeleteSshProfile(string @id); + Task Schemas(CancelToken? @cancel); + bool SetSafeMode(SafeModeTag @level); /// - Task DeviceSettings(string @id); + string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending); + StatementSpan? StatementAt(string @sql, uint @caret); /// - Task SaveCredentialProfile(CredentialProfileRecord @profile); + Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel); /// - Task SaveSshProfile(SshProfileRecord @profile); + Task TableInfo(TableName @table, CancelToken? @cancel); /// - Task SetConnectionDetails(string @id, ConnectionDetailsRecord @details); + Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel); /// - Task SetDeviceSettings(string @id, DeviceSettingsRecord @settings); + Task TableRowEstimate(TableName @table, CancelToken? @cancel); /// - Task SshProfiles(); + Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel); } -internal class ConnectionLibrary : IConnectionLibrary, IDisposable { +internal class DatabaseSession : IDatabaseSession, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public ConnectionLibrary(ulong pointer) { + public DatabaseSession(ulong pointer) { this.pointer = pointer; } - ~ConnectionLibrary() { + ~DatabaseSession() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_connectionlibrary(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_databasesession(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_connectionlibrary(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_databasesession(this.pointer, ref status); }); } @@ -12066,30 +16620,20 @@ internal T CallWithPointer(Func func) } - /// - public async Task ApplyCloudPull(CloudLibraryPull @pull) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_apply_cloud_pull(thisPtr, FfiConverterTypeCloudLibraryPull.INSTANCE.Lower(@pull)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public CatalogAbilities CatalogAbilities() { + return CallWithPointer(thisPtr => FfiConverterTypeCatalogAbilities.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_catalog_abilities(thisPtr, ref _status) +))); } + /// - public async Task CloudEdits(CloudLibraryRecords @base) { + public async Task DatabaseChoices(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_cloud_edits(thisPtr, FfiConverterTypeCloudLibraryRecords.INSTANCE.Lower(@base)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_choices(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12100,134 +16644,43 @@ public async Task CloudEdits(CloudLibraryRecords @base) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeCloudLibraryRecords.INSTANCE.Lift(result), + (result) => FfiConverterTypeDatabaseChoicesInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task AddFavorites(string[] @ids, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_add_favorites(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@before)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public CatalogChange PlanCatalogChange(CatalogOperation @operation) { + return CallWithPointer(thisPtr => FfiConverterTypeCatalogChange.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_plan_catalog_change(thisPtr, FfiConverterTypeCatalogOperation.INSTANCE.Lower(@operation), ref _status) +))); } - /// - public async Task CreateGroup(string @name, string? @parentId) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_create_group(thisPtr, FfiConverterString.INSTANCE.Lower(@name), FfiConverterOptionalString.INSTANCE.Lower(@parentId)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeGroupRecord.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - /// - public async Task CreateTag(string @name, string @color) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_create_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@name), FfiConverterString.INSTANCE.Lower(@color)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeTagRecord.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public bool ProtectsDatabase(string @name) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_protects_database(thisPtr, FfiConverterString.INSTANCE.Lower(@name), ref _status) +))); } - /// - public async Task Delete(string @id) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - /// - public async Task DeleteGroup(string @id) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_group(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public bool ProtectsSchema(string @name) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_protects_schema(thisPtr, FfiConverterString.INSTANCE.Lower(@name), ref _status) +))); } - /// - public async Task DeleteTag(string @id) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } /// - public async Task Duplicate(string @id, string @name) { + public async Task RefreshSchemas(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_duplicate(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12238,133 +16691,105 @@ public async Task Duplicate(string @id, string @name) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeConnectionRecord.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ExportFile(string @path) { + public async Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, ExportProgress? @progress, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_export_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_rows(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterOptionalTypeTableName.INSTANCE.Lower(@table), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeExportProgress.INSTANCE.Lower(@progress), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u32(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u32(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u32(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterUInt32.INSTANCE.Lift(result), + (result) => FfiConverterUInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ImportFile(string @path) { + public async Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, ExportProgress? @progress, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_import_file(thisPtr, FfiConverterString.INSTANCE.Lower(@path)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_table(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeExportProgress.INSTANCE.Lower(@progress), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterTypeImportSummary.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task MoveGroups(string[] @ids, string? @parentId, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_move_groups(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@parentId), FfiConverterOptionalString.INSTANCE.Lower(@before)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task MoveToGroup(string[] @ids, string? @groupId, string? @before) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_move_to_group(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterOptionalString.INSTANCE.Lower(@groupId), FfiConverterOptionalString.INSTANCE.Lower(@before)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (result) => FfiConverterUInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RemoveFavorites(string[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task OpenCsvImport(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_remove_favorites(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_csv_import(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeCsvImport.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RenameConnection(string @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task TableKeys(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_connection(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_keys(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeTableKeys.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task RenameGroup(string @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_rename_group(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_close(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -12379,11 +16804,11 @@ public async Task RenameGroup(string @id, string @name) {await _UniFFIAsync.Unif } /// - public async Task Save(ConnectionRecord @record, ConnectionSecrets @secrets) { + public async Task Columns(TableName @table, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_columns(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12394,54 +16819,18 @@ public async Task Save(ConnectionRecord @record, ConnectionSec // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeConnectionRecord.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task SetFavorite(string @id, bool @favorite) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_favorite(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterBoolean.INSTANCE.Lower(@favorite)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task SetGroupColor(string @id, string? @color) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_group_color(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@color)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (result) => FfiConverterSequenceTypeColumnEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Snapshot() { + public async Task Complete(string @text, uint @caret, bool @asked, string? @database, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_snapshot(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_complete(thisPtr, FfiConverterString.INSTANCE.Lower(@text), FfiConverterUInt32.INSTANCE.Lower(@caret), FfiConverterBoolean.INSTANCE.Lower(@asked), FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12452,76 +16841,34 @@ public async Task Snapshot() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeLibrarySnapshot.INSTANCE.Lift(result), + (result) => FfiConverterOptionalTypeCompletionList.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task TagConnections(string[] @ids, string @tagId, bool @tagged) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_tag_connections(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@ids), FfiConverterString.INSTANCE.Lower(@tagId), FfiConverterBoolean.INSTANCE.Lower(@tagged)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public string? Database() { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database(thisPtr, ref _status) +))); } - /// - public async Task UpdateTag(string @id, string @name, string @color) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_update_tag(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name), FfiConverterString.INSTANCE.Lower(@color)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - /// - public async Task ConnectionDetails(string @id) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_connection_details(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeConnectionDetailsRecord.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public DatabaseLayoutTag DatabaseLayout() { + return CallWithPointer(thisPtr => FfiConverterTypeDatabaseLayoutTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_layout(thisPtr, ref _status) +))); } + /// - public async Task CredentialProfiles() { + public async Task Databases(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_credential_profiles(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_databases(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12532,62 +16879,26 @@ public async Task CredentialProfiles() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeCredentialProfileRecord.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task DeleteCredentialProfile(string @id) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_credential_profile(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), - // Lift - (result) => FfiConverterBoolean.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public string DriverId() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_driver_id(thisPtr, ref _status) +))); } - /// - public async Task DeleteSshProfile(string @id) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_delete_ssh_profile(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), - // Lift - (result) => FfiConverterBoolean.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } /// - public async Task DeviceSettings(string @id) { + public async Task FilterChoices(TableName @table, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_device_settings(thisPtr, FfiConverterString.INSTANCE.Lower(@id)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12598,18 +16909,34 @@ public async Task DeviceSettings(string @id) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeDeviceSettingsRecord.INSTANCE.Lift(result), + (result) => FfiConverterTypeFilterChoices.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } + public RunGate GateRun(string @sql) { + return CallWithPointer(thisPtr => FfiConverterTypeRunGate.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_gate_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), ref _status) +))); + } + + + public SessionHealthTag Health() { + return CallWithPointer(thisPtr => FfiConverterTypeSessionHealthTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health(thisPtr, ref _status) +))); + } + + /// - public async Task SaveCredentialProfile(CredentialProfileRecord @profile) { + public async Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save_credential_profile(thisPtr, FfiConverterTypeCredentialProfileRecord.INSTANCE.Lower(@profile)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health_change(thisPtr, FfiConverterTypeSessionHealthTag.INSTANCE.Lower(@seen), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12620,18 +16947,34 @@ public async Task SaveCredentialProfile(CredentialProfi // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeCredentialProfileRecord.INSTANCE.Lift(result), + (result) => FfiConverterTypeSessionHealthTag.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } + public string Id() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_id(thisPtr, ref _status) +))); + } + + + public string Name() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_name(thisPtr, ref _status) +))); + } + + /// - public async Task SaveSshProfile(SshProfileRecord @profile) { + public async Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_save_ssh_profile(thisPtr, FfiConverterTypeSshProfileRecord.INSTANCE.Lower(@profile)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_object_definition(thisPtr, FfiConverterTypeObjectEntry.INSTANCE.Lower(@object), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -12642,254 +16985,131 @@ public async Task SaveSshProfile(SshProfileRecord @profile) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeSshProfileRecord.INSTANCE.Lift(result), + (result) => FfiConverterOptionalTypeObjectSource.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task SetConnectionDetails(string @id, ConnectionDetailsRecord @details) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Objects(ObjectScopeArg @scope, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_connection_details(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterTypeConnectionDetailsRecord.INSTANCE.Lower(@details)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task SetDeviceSettings(string @id, DeviceSettingsRecord @settings) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task OpenEditor(string? @database, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_set_device_settings(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterTypeDeviceSettingsRecord.INSTANCE.Lower(@settings)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_editor(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeQueryEditor.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } + public KeyReader OpenKey(string @key) { + return CallWithPointer(thisPtr => FfiConverterTypeKeyReader.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_key(thisPtr, FfiConverterString.INSTANCE.Lower(@key), ref _status) +))); + } + + + public bool ReadOnly() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_only(thisPtr, ref _status) +))); + } + + /// - public async Task SshProfiles() { + public async Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_connectionlibrary_ssh_profiles(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterUInt64.INSTANCE.Lower(@limit), FfiConverterUInt64.INSTANCE.Lower(@offset), FfiConverterOptionalTypePageResume.INSTANCE.Lower(@resume), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterSequenceTypeSshProfileRecord.INSTANCE.Lift(result), + (result) => FfiConverterTypeTablePageRead.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - - -} -class FfiConverterTypeConnectionLibrary: FfiConverter { - public static FfiConverterTypeConnectionLibrary INSTANCE = new FfiConverterTypeConnectionLibrary(); - - - public override ulong Lower(ConnectionLibrary value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override ConnectionLibrary Lift(ulong value) { - return new ConnectionLibrary(value); - } - - public override ConnectionLibrary Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(ConnectionLibrary value) { - return 8; - } - - public override void Write(ConnectionLibrary value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface ICore { - /// - Task OpenAccount(AccountConfig @config, HostBrowser @browser, HostWebAuthenticator? @webAuthenticator, AccountListener @listener); - AiAssistant AiAssistant(); - /// - Task ConnectSaved(string @id, string? @database, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel); - DriverInfo[] Drivers(); - /// - Task History(); - /// - ConnectionLibrary Library(); - /// - Task OpenFile(FileOpenRequest @request, CancelToken? @cancel); - /// - Task TestConnection(ConnectionRecord @record, ConnectionSecrets @secrets, HostPrompter? @prompter, CancelToken? @cancel); - /// - Task ForeignSources(ForeignAppDirsArg @dirs, ScanDepthTag @depth); - /// - Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel); - /// - Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts); - /// - McpService McpServer(McpAppHost @host, McpListener @listener); -} -internal class Core : ICore, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public Core(ulong pointer) { - this.pointer = pointer; - } - - ~Core() { - Destroy(); - } - public Core(HostConfig @config, HostSecrets @secrets) : - this( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_new(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), FfiConverterTypeHostSecrets.INSTANCE.Lower(@secrets), ref _status) -)) {} - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_core(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_core(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + public void Reconnect() { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_reconnect(thisPtr, ref _status) +)); } - + + /// - public async Task OpenAccount(AccountConfig @config, HostBrowser @browser, HostWebAuthenticator? @webAuthenticator, AccountListener @listener) { + public async Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_account(thisPtr, FfiConverterTypeAccountConfig.INSTANCE.Lower(@config), FfiConverterTypeHostBrowser.INSTANCE.Lower(@browser), FfiConverterOptionalTypeHostWebAuthenticator.INSTANCE.Lower(@webAuthenticator), FfiConverterTypeAccountListener.INSTANCE.Lower(@listener)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeAccountService.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public AiAssistant AiAssistant() { - return CallWithPointer(thisPtr => FfiConverterTypeAiAssistant.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_core_ai_assistant(thisPtr, ref _status) -))); - } - - /// - public async Task ConnectSaved(string @id, string? @database, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel) { + public async Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_connect_saved(thisPtr, FfiConverterString.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@keep), FfiConverterOptionalTypeHostPrompter.INSTANCE.Lower(@prompter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_result_editor(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), @@ -12900,57 +17120,65 @@ public async Task ConnectSaved(string @id, string? @database, C // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterTypeDatabaseSession.INSTANCE.Lift(result), + (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public DriverInfo[] Drivers() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeDriverInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_core_drivers(thisPtr, ref _status) -))); - } - - /// - public async Task History() { + public async Task Schemas(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_history(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeQueryHistoryStore.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } + public bool SetSafeMode(SafeModeTag @level) { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(thisPtr, FfiConverterTypeSafeModeTag.INSTANCE.Lower(@level), ref _status) +))); + } + + /// - public ConnectionLibrary Library() { - return CallWithPointer(thisPtr => FfiConverterTypeConnectionLibrary.INSTANCE.Lift( + public string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending) { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_core_library(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterSequenceString.INSTANCE.Lower(@columns), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) +))); + } + + + public StatementSpan? StatementAt(string @sql, uint @caret) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeStatementSpan.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_statement_at(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterUInt32.INSTANCE.Lower(@caret), ref _status) ))); } /// - public async Task OpenFile(FileOpenRequest @request, CancelToken? @cancel) { + public async Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_file(thisPtr, FfiConverterTypeFileOpenRequest.INSTANCE.Lower(@request), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_editor(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterBoolean.INSTANCE.Lower(@refresh), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), @@ -12961,172 +17189,160 @@ public async Task OpenFile(FileOpenRequest @request, CancelToke // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterTypeDatabaseSession.INSTANCE.Lift(result), + (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TestConnection(ConnectionRecord @record, ConnectionSecrets @secrets, HostPrompter? @prompter, CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task TableInfo(TableName @table, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_test_connection(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterTypeConnectionSecrets.INSTANCE.Lower(@secrets), FfiConverterOptionalTypeHostPrompter.INSTANCE.Lower(@prompter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_info(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeTableInfoRecord.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ForeignSources(ForeignAppDirsArg @dirs, ScanDepthTag @depth) { + public async Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_foreign_sources(thisPtr, FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs), FfiConverterTypeScanDepthTag.INSTANCE.Lower(@depth)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), // Lift - (result) => FfiConverterSequenceTypeForeignSourceInfo.INSTANCE.Lift(result), + (result) => FfiConverterUInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ReadForeign(ForeignAppTag @app, ForeignAppDirsArg @dirs, string? @file, ForeignImportRequest @request, CancelToken? @cancel) { + public async Task TableRowEstimate(TableName @table, CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_read_foreign(thisPtr, FfiConverterTypeForeignAppTag.INSTANCE.Lower(@app), FfiConverterTypeForeignAppDirsArg.INSTANCE.Lower(@dirs), FfiConverterOptionalString.INSTANCE.Lower(@file), FfiConverterTypeForeignImportRequest.INSTANCE.Lower(@request), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeForeignImportReview.INSTANCE.Lift(result), + (result) => FfiConverterTypeRowEstimate.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ForgetChangedHostKey(ConnectionRecord @record, string @host, string @knownHosts) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_forget_changed_host_key(thisPtr, FfiConverterTypeConnectionRecord.INSTANCE.Lower(@record), FfiConverterString.INSTANCE.Lower(@host), FfiConverterString.INSTANCE.Lower(@knownHosts)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_structure(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterTypeObjectKindTag.INSTANCE.Lower(@kind), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeTableStructure.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public McpService McpServer(McpAppHost @host, McpListener @listener) { - return CallWithPointer(thisPtr => FfiConverterTypeMcpService.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_core_mcp_server(thisPtr, FfiConverterTypeMcpAppHost.INSTANCE.Lower(@host), FfiConverterTypeMcpListener.INSTANCE.Lower(@listener), ref _status) -))); - } - - - /// - public static Core WithSystemSecrets(HostConfig @config) { - return new Core( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_core_with_system_secrets(FfiConverterTypeHostConfig.INSTANCE.Lower(@config), ref _status) -)); - } - - } -class FfiConverterTypeCore: FfiConverter { - public static FfiConverterTypeCore INSTANCE = new FfiConverterTypeCore(); +class FfiConverterTypeDatabaseSession: FfiConverter { + public static FfiConverterTypeDatabaseSession INSTANCE = new FfiConverterTypeDatabaseSession(); - public override ulong Lower(Core value) { + public override ulong Lower(DatabaseSession value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override Core Lift(ulong value) { - return new Core(value); + public override DatabaseSession Lift(ulong value) { + return new DatabaseSession(value); } - public override Core Read(BigEndianStream stream) { + public override DatabaseSession Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(Core value) { + public override int AllocationSize(DatabaseSession value) { return 8; } - public override void Write(Core value, BigEndianStream stream) { + public override void Write(DatabaseSession value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface ICsvImport { - ImportColumnInfo[] Columns(); - /// - Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping); - /// - Task Preview(string @path, CsvReadOptions @options); - /// - Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel); - uint?[] SuggestMapping(string[] @headers); +internal interface IExportProgress { + ulong Rows(); } -internal class CsvImport : ICsvImport, IDisposable { +internal class ExportProgress : IExportProgress, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public CsvImport(ulong pointer) { + public ExportProgress(ulong pointer) { this.pointer = pointer; } - ~CsvImport() { + ~ExportProgress() { Destroy(); } + public ExportProgress() : + this( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_exportprogress_new( ref _status) +)) {} protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_csvimport(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_exportprogress(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_csvimport(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_exportprogress(this.pointer, ref status); }); } @@ -13173,105 +17389,31 @@ private void DecrementCallCounter() internal void CallWithPointer(Action action) { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - - public ImportColumnInfo[] Columns() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeImportColumnInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_columns(thisPtr, ref _status) -))); - } - - - /// - public async Task Plan(string @path, CsvReadOptions @options, uint?[] @mapping) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_plan(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options), FfiConverterSequenceOptionalUInt32.INSTANCE.Lower(@mapping)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeCsvImportCheck.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task Preview(string @path, CsvReadOptions @options) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_preview(thisPtr, FfiConverterString.INSTANCE.Lower(@path), FfiConverterTypeCsvReadOptions.INSTANCE.Lower(@options)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeCsvPreview.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } - - /// - public async Task Run(ulong @plan, bool @confirmed, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_run(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@plan), FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeCsvImportOutcome.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } + - public uint?[] SuggestMapping(string[] @headers) { - return CallWithPointer(thisPtr => FfiConverterSequenceOptionalUInt32.INSTANCE.Lift( + public ulong Rows() { + return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_csvimport_suggest_mapping(thisPtr, FfiConverterSequenceString.INSTANCE.Lower(@headers), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_exportprogress_rows(thisPtr, ref _status) ))); } @@ -13279,124 +17421,69 @@ public async Task Run(ulong @plan, bool @confirmed, CancelToke } -class FfiConverterTypeCsvImport: FfiConverter { - public static FfiConverterTypeCsvImport INSTANCE = new FfiConverterTypeCsvImport(); +class FfiConverterTypeExportProgress: FfiConverter { + public static FfiConverterTypeExportProgress INSTANCE = new FfiConverterTypeExportProgress(); - public override ulong Lower(CsvImport value) { + public override ulong Lower(ExportProgress value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override CsvImport Lift(ulong value) { - return new CsvImport(value); + public override ExportProgress Lift(ulong value) { + return new ExportProgress(value); } - public override CsvImport Read(BigEndianStream stream) { + public override ExportProgress Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(CsvImport value) { + public override int AllocationSize(ExportProgress value) { return 8; } - public override void Write(CsvImport value, BigEndianStream stream) { + public override void Write(ExportProgress value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IDatabaseSession { - CatalogAbilities CatalogAbilities(); - /// - Task DatabaseChoices(CancelToken? @cancel); - /// - CatalogChange PlanCatalogChange(CatalogOperation @operation); - bool ProtectsDatabase(string @name); - bool ProtectsSchema(string @name); - /// - Task RefreshSchemas(CancelToken? @cancel); - /// - Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, ExportProgress? @progress, CancelToken? @cancel); - /// - Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, ExportProgress? @progress, CancelToken? @cancel); - /// - Task OpenCsvImport(TableName @table, CancelToken? @cancel); - /// - Task TableKeys(TableName @table, CancelToken? @cancel); - /// - Task Close(); - /// - Task Columns(TableName @table, CancelToken? @cancel); - /// - Task Complete(string @text, uint @caret, bool @asked, string? @database, CancelToken? @cancel); - string? Database(); - DatabaseLayoutTag DatabaseLayout(); - /// - Task Databases(CancelToken? @cancel); - string DriverId(); - /// - Task FilterChoices(TableName @table, CancelToken? @cancel); - RunGate GateRun(string @sql); - SessionHealthTag Health(); - /// - Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel); - string Id(); - string Name(); - /// - Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel); - /// - Task Objects(ObjectScopeArg @scope, CancelToken? @cancel); - /// - Task OpenEditor(string? @database, CancelToken? @cancel); - KeyReader OpenKey(string @key); - bool ReadOnly(); - /// - Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel); - void Reconnect(); - /// - Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel); - /// - Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel); - /// - Task Schemas(CancelToken? @cancel); - bool SetSafeMode(SafeModeTag @level); +internal interface IFavouriteStore { /// - string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending); - StatementSpan? StatementAt(string @sql, uint @caret); + Task AddTable(string @connectionId, FavouriteTableInfo @table); /// - Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel); + Task Databases(string @connectionId); /// - Task TableInfo(TableName @table, CancelToken? @cancel); + Task RemoveDatabase(string @connectionId, string @database); /// - Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel); + Task RemoveTable(string @connectionId, FavouriteTableInfo @table); /// - Task TableRowEstimate(TableName @table, CancelToken? @cancel); + Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment); /// - Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel); + Task Tables(string @connectionId); } -internal class DatabaseSession : IDatabaseSession, IDisposable { +internal class FavouriteStore : IFavouriteStore, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public DatabaseSession(ulong pointer) { + public FavouriteStore(ulong pointer) { this.pointer = pointer; } - ~DatabaseSession() { + ~FavouriteStore() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_databasesession(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_favouritestore(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_databasesession(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_favouritestore(this.pointer, ref status); }); } @@ -13464,67 +17551,30 @@ internal T CallWithPointer(Func func) } - public CatalogAbilities CatalogAbilities() { - return CallWithPointer(thisPtr => FfiConverterTypeCatalogAbilities.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_catalog_abilities(thisPtr, ref _status) -))); - } - - /// - public async Task DatabaseChoices(CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task AddTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_choices(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_add_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeDatabaseChoicesInfo.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public CatalogChange PlanCatalogChange(CatalogOperation @operation) { - return CallWithPointer(thisPtr => FfiConverterTypeCatalogChange.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_plan_catalog_change(thisPtr, FfiConverterTypeCatalogOperation.INSTANCE.Lower(@operation), ref _status) -))); - } - - - public bool ProtectsDatabase(string @name) { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_protects_database(thisPtr, FfiConverterString.INSTANCE.Lower(@name), ref _status) -))); - } - - - public bool ProtectsSchema(string @name) { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_protects_schema(thisPtr, FfiConverterString.INSTANCE.Lower(@name), ref _status) -))); - } - - - /// - public async Task RefreshSchemas(CancelToken? @cancel) { + public async Task Databases(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_databases(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -13535,105 +17585,53 @@ public async Task RefreshSchemas(CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task ExportRows(ResultSet @rows, uint @visibleColumns, ExportFormatTag @format, TableName? @table, string @path, ExportProgress? @progress, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_rows(thisPtr, FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterOptionalTypeTableName.INSTANCE.Lower(@table), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeExportProgress.INSTANCE.Lower(@progress), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - /// - public async Task ExportTable(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ExportFormatTag @format, string @path, ExportProgress? @progress, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_export_table(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterTypeExportFormatTag.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path), FfiConverterOptionalTypeExportProgress.INSTANCE.Lower(@progress), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeFavouriteDatabaseInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task OpenCsvImport(TableName @table, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task RemoveDatabase(string @connectionId, string @database) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_csv_import(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeCsvImport.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task TableKeys(TableName @table, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task RemoveTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_keys(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeTableKeys.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_close(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_set_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database), FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Lower(@environment)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -13648,11 +17646,11 @@ public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( } /// - public async Task Columns(TableName @table, CancelToken? @cancel) { + public async Task Tables(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_columns(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_tables(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -13663,162 +17661,158 @@ public async Task Columns(TableName @table, CancelToken? @cancel) // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeColumnEntry.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeFavouriteTableInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task Complete(string @text, uint @caret, bool @asked, string? @database, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_complete(thisPtr, FfiConverterString.INSTANCE.Lower(@text), FfiConverterUInt32.INSTANCE.Lower(@caret), FfiConverterBoolean.INSTANCE.Lower(@asked), FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterOptionalTypeCompletionList.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } + - public string? Database() { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database(thisPtr, ref _status) -))); +} +class FfiConverterTypeFavouriteStore: FfiConverter { + public static FfiConverterTypeFavouriteStore INSTANCE = new FfiConverterTypeFavouriteStore(); + + + public override ulong Lower(FavouriteStore value) { + return value.CallWithPointer(thisPtr => thisPtr); } - - - public DatabaseLayoutTag DatabaseLayout() { - return CallWithPointer(thisPtr => FfiConverterTypeDatabaseLayoutTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_database_layout(thisPtr, ref _status) -))); + + public override FavouriteStore Lift(ulong value) { + return new FavouriteStore(value); } - - - /// - public async Task Databases(CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_databases(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + public override FavouriteStore Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); } - - public string DriverId() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_driver_id(thisPtr, ref _status) -))); + + public override int AllocationSize(FavouriteStore value) { + return 8; } - - + + public override void Write(FavouriteStore value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IForeignImportReview { + ForeignAppTag App(); /// - public async Task FilterChoices(TableName @table, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_filter_choices(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeFilterChoices.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + Task Apply(); + ForeignImportChoices Choices(); + ForeignConnectionRow[] Connections(); + PasswordOutcomeTag Passwords(); + /// + bool Resolve(string @reference, ResolutionTag @resolution); + ForeignQueryRow[] SavedQueries(); + void SetIncluded(string @reference, bool @included); + void SetSelected(string @reference, bool @selected); +} +internal class ForeignImportReview : IForeignImportReview, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public ForeignImportReview(ulong pointer) { + this.pointer = pointer; } - - public RunGate GateRun(string @sql) { - return CallWithPointer(thisPtr => FfiConverterTypeRunGate.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_gate_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), ref _status) -))); + + ~ForeignImportReview() { + Destroy(); } - - - public SessionHealthTag Health() { - return CallWithPointer(thisPtr => FfiConverterTypeSessionHealthTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health(thisPtr, ref _status) -))); + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_foreignimportreview(this.pointer, ref status); + }); } - - - /// - public async Task HealthChange(SessionHealthTag @seen, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_health_change(thisPtr, FfiConverterTypeSessionHealthTag.INSTANCE.Lower(@seen), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeSessionHealthTag.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_foreignimportreview(this.pointer, ref status); + }); } - - public string Id() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_id(thisPtr, ref _status) -))); + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } + - - public string Name() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + public ForeignAppTag App() { + return CallWithPointer(thisPtr => FfiConverterTypeForeignAppTag.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_name(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_app(thisPtr, ref _status) ))); } /// - public async Task ObjectDefinition(ObjectEntry @object, CancelToken? @cancel) { + public async Task Apply() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_object_definition(thisPtr, FfiConverterTypeObjectEntry.INSTANCE.Lower(@object), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_apply(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -13829,153 +17823,210 @@ public string Name() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterOptionalTypeObjectSource.INSTANCE.Lift(result), + (result) => FfiConverterTypeForeignImportOutcome.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task Objects(ObjectScopeArg @scope, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public ForeignImportChoices Choices() { + return CallWithPointer(thisPtr => FfiConverterTypeForeignImportChoices.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_choices(thisPtr, ref _status) +))); } - /// - public async Task OpenEditor(string? @database, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_editor(thisPtr, FfiConverterOptionalString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeQueryEditor.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + public ForeignConnectionRow[] Connections() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignConnectionRow.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_connections(thisPtr, ref _status) +))); } - public KeyReader OpenKey(string @key) { - return CallWithPointer(thisPtr => FfiConverterTypeKeyReader.INSTANCE.Lift( + + public PasswordOutcomeTag Passwords() { + return CallWithPointer(thisPtr => FfiConverterTypePasswordOutcomeTag.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_open_key(thisPtr, FfiConverterString.INSTANCE.Lower(@key), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_passwords(thisPtr, ref _status) ))); } - public bool ReadOnly() { + /// + public bool Resolve(string @reference, ResolutionTag @resolution) { return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_resolve(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterTypeResolutionTag.INSTANCE.Lower(@resolution), ref _status) +))); + } + + + public ForeignQueryRow[] SavedQueries() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignQueryRow.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_only(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_saved_queries(thisPtr, ref _status) ))); } - /// - public async Task ReadTablePage(TableName @table, ColumnSort? @sort, TableFilterArg? @filter, ulong @limit, ulong @offset, PageResume? @resume, RunListener @listener, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_read_table_page(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeColumnSort.INSTANCE.Lower(@sort), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterUInt64.INSTANCE.Lower(@limit), FfiConverterUInt64.INSTANCE.Lower(@offset), FfiConverterOptionalTypePageResume.INSTANCE.Lower(@resume), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeTablePageRead.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public void SetIncluded(string @reference, bool @included) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_included(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@included), ref _status) +)); } - public void Reconnect() { + + + public void SetSelected(string @reference, bool @selected) { CallWithPointer(thisPtr => _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_reconnect(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_selected(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@selected), ref _status) )); } + + +} +class FfiConverterTypeForeignImportReview: FfiConverter { + public static FfiConverterTypeForeignImportReview INSTANCE = new FfiConverterTypeForeignImportReview(); + + + public override ulong Lower(ForeignImportReview value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override ForeignImportReview Lift(ulong value) { + return new ForeignImportReview(value); + } + + public override ForeignImportReview Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(ForeignImportReview value) { + return 8; + } + + public override void Write(ForeignImportReview value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IKeyReader { + string Key(); /// - public async Task RefreshObjects(ObjectScopeArg @scope, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_refresh_objects(thisPtr, FfiConverterTypeObjectScopeArg.INSTANCE.Lower(@scope), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeObjectEntry.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + Task ReadMore(CancelToken? @cancel); + ResultSet? Rows(); +} +internal class KeyReader : IKeyReader, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public KeyReader(ulong pointer) { + this.pointer = pointer; + } + + ~KeyReader() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_keyreader(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_keyreader(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } + - /// - public async Task ResultEditor(string @sql, ResultSet @rows, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_result_editor(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterTypeResultSet.INSTANCE.Lower(@rows), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public string Key() { + return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_key(thisPtr, ref _status) +))); } + /// - public async Task Schemas(CancelToken? @cancel) { + public async Task ReadMore(CancelToken? @cancel) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_schemas(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_read_more(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -13986,65 +18037,155 @@ public async Task Schemas(CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeSchemaEntry.INSTANCE.Lift(result), + (result) => FfiConverterOptionalTypeKeyWindowInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public bool SetSafeMode(SafeModeTag @level) { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + public ResultSet? Rows() { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_set_safe_mode(thisPtr, FfiConverterTypeSafeModeTag.INSTANCE.Lower(@level), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_rows(thisPtr, ref _status) ))); } - /// - public string? SortedQuery(string @sql, string[] @columns, uint @column, bool @ascending) { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_sorted_query(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterSequenceString.INSTANCE.Lower(@columns), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) -))); - } - + - public StatementSpan? StatementAt(string @sql, uint @caret) { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeStatementSpan.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_statement_at(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterUInt32.INSTANCE.Lower(@caret), ref _status) -))); +} +class FfiConverterTypeKeyReader: FfiConverter { + public static FfiConverterTypeKeyReader INSTANCE = new FfiConverterTypeKeyReader(); + + + public override ulong Lower(KeyReader value) { + return value.CallWithPointer(thisPtr => thisPtr); } - - + + public override KeyReader Lift(ulong value) { + return new KeyReader(value); + } + + public override KeyReader Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(KeyReader value) { + return 8; + } + + public override void Write(KeyReader value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IMcpService { /// - public async Task TableEditor(TableName @table, bool @refresh, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_editor(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterBoolean.INSTANCE.Lower(@refresh), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterTypeTableEditor.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + Task AccessToken(); + void Apply(bool @enabled, ushort @port); + /// + Task RegenerateToken(); + SeenClientInfo[] SeenClients(); + McpStatusTag Status(); + Task Stop(); +} +internal class McpService : IMcpService, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public McpService(ulong pointer) { + this.pointer = pointer; + } + + ~McpService() { + Destroy(); + } + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_mcpservice(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_mcpservice(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } } + /// - public async Task TableInfo(TableName @table, CancelToken? @cancel) { + public async Task AccessToken() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_info(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_access_token(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -14055,138 +18196,127 @@ public async Task TableInfo(TableName @table, CancelToken? @can // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeTableInfoRecord.INSTANCE.Lift(result), + (result) => FfiConverterTypeSecretString.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task TableRowCount(TableName @table, TableFilterArg? @filter, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_count(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeTableFilterArg.INSTANCE.Lower(@filter), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), - // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public void Apply(bool @enabled, ushort @port) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_apply(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@enabled), FfiConverterUInt16.INSTANCE.Lower(@port), ref _status) +)); } + + /// - public async Task TableRowEstimate(TableName @table, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task RegenerateToken() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_row_estimate(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_regenerate_token(thisPtr); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeRowEstimate.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - public async Task TableStructure(TableName @table, ObjectKindTag @kind, CancelToken? @cancel) { - return await _UniFFIAsync.UniffiRustCallAsync( + public SeenClientInfo[] SeenClients() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeSeenClientInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_seen_clients(thisPtr, ref _status) +))); + } + + + public McpStatusTag Status() { + return CallWithPointer(thisPtr => FfiConverterTypeMcpStatusTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_status(thisPtr, ref _status) +))); + } + + + public async Task Stop() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_databasesession_table_structure(thisPtr, FfiConverterTypeTableName.INSTANCE.Lower(@table), FfiConverterTypeObjectKindTag.INSTANCE.Lower(@kind), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_stop(thisPtr); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeTableStructure.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error - FfiConverterTypeCoreError.INSTANCE + NullCallStatusErrorHandler.INSTANCE + ); } } -class FfiConverterTypeDatabaseSession: FfiConverter { - public static FfiConverterTypeDatabaseSession INSTANCE = new FfiConverterTypeDatabaseSession(); +class FfiConverterTypeMcpService: FfiConverter { + public static FfiConverterTypeMcpService INSTANCE = new FfiConverterTypeMcpService(); - public override ulong Lower(DatabaseSession value) { + public override ulong Lower(McpService value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override DatabaseSession Lift(ulong value) { - return new DatabaseSession(value); + public override McpService Lift(ulong value) { + return new McpService(value); } - public override DatabaseSession Read(BigEndianStream stream) { + public override McpService Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(DatabaseSession value) { + public override int AllocationSize(McpService value) { return 8; } - public override void Write(DatabaseSession value, BigEndianStream stream) { + public override void Write(McpService value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IExportProgress { - ulong Rows(); +internal interface IPageResume { } -internal class ExportProgress : IExportProgress, IDisposable { +internal class PageResume : IPageResume, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public ExportProgress(ulong pointer) { + public PageResume(ulong pointer) { this.pointer = pointer; } - ~ExportProgress() { + ~PageResume() { Destroy(); } - public ExportProgress() : - this( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_exportprogress_new( ref _status) -)) {} protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_exportprogress(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_pageresume(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_exportprogress(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_pageresume(this.pointer, ref status); }); } @@ -14254,80 +18384,87 @@ internal T CallWithPointer(Func func) } - public ulong Rows() { - return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_exportprogress_rows(thisPtr, ref _status) -))); - } - - } -class FfiConverterTypeExportProgress: FfiConverter { - public static FfiConverterTypeExportProgress INSTANCE = new FfiConverterTypeExportProgress(); +class FfiConverterTypePageResume: FfiConverter { + public static FfiConverterTypePageResume INSTANCE = new FfiConverterTypePageResume(); - public override ulong Lower(ExportProgress value) { + public override ulong Lower(PageResume value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override ExportProgress Lift(ulong value) { - return new ExportProgress(value); + public override PageResume Lift(ulong value) { + return new PageResume(value); } - public override ExportProgress Read(BigEndianStream stream) { + public override PageResume Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(ExportProgress value) { + public override int AllocationSize(PageResume value) { return 8; } - public override void Write(ExportProgress value, BigEndianStream stream) { + public override void Write(PageResume value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IFavouriteStore { - /// - Task AddTable(string @connectionId, FavouriteTableInfo @table); - /// - Task Databases(string @connectionId); - /// - Task RemoveDatabase(string @connectionId, string @database); - /// - Task RemoveTable(string @connectionId, FavouriteTableInfo @table); +/// +/// An editor tab's own connection, which keeps its transaction and +/// session settings from one run to the next. +/// +internal interface IQueryEditor { + /// + /// Closes the editor's connection, ending its transaction. + /// /// - Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment); + Task Close(); + string? Database(); + /// + /// The editor's connection is gone. It is never opened again by + /// itself, since its transaction would not come back with it, so the + /// tab opens a new editor. + /// + bool IsLost(); + /// + /// Starts `sql` and returns at once. `listener` hears when events + /// are waiting; the run ends with a `Finished` event. + /// + QueryRun Run(string @sql, RunSettings @settings, RunListener @listener); /// - Task Tables(string @connectionId); + Task UseDatabase(string @database, CancelToken? @cancel); } -internal class FavouriteStore : IFavouriteStore, IDisposable { +/// +/// An editor tab's own connection, which keeps its transaction and +/// session settings from one run to the next. +/// +internal class QueryEditor : IQueryEditor, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public FavouriteStore(ulong pointer) { + public QueryEditor(ulong pointer) { this.pointer = pointer; } - ~FavouriteStore() { + ~QueryEditor() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_favouritestore(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_queryeditor(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_favouritestore(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryeditor(this.pointer, ref status); }); } @@ -14395,11 +18532,14 @@ internal T CallWithPointer(Func func) } + /// + /// Closes the editor's connection, ending its transaction. + /// /// - public async Task AddTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_add_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_close(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -14413,69 +18553,44 @@ public async Task AddTable(string @connectionId, FavouriteTableInfo @table) {awa ); } - /// - public async Task Databases(string @connectionId) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_databases(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeFavouriteDatabaseInfo.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + public string? Database() { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_database(thisPtr, ref _status) +))); } - /// - public async Task RemoveDatabase(string @connectionId, string @database) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + /// + /// The editor's connection is gone. It is never opened again by + /// itself, since its transaction would not come back with it, so the + /// tab opens a new editor. + /// + public bool IsLost() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_is_lost(thisPtr, ref _status) +))); } - /// - public async Task RemoveTable(string @connectionId, FavouriteTableInfo @table) {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_remove_table(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterTypeFavouriteTableInfo.INSTANCE.Lower(@table)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); + + /// + /// Starts `sql` and returns at once. `listener` hears when events + /// are waiting; the run ends with a `Finished` event. + /// + public QueryRun Run(string @sql, RunSettings @settings, RunListener @listener) { + return CallWithPointer(thisPtr => FfiConverterTypeQueryRun.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterTypeRunSettings.INSTANCE.Lower(@settings), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), ref _status) +))); } + /// - public async Task SetDatabase(string @connectionId, string @database, DatabaseEnvironmentTag @environment) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task UseDatabase(string @database, CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_set_database(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@database), FfiConverterTypeDatabaseEnvironmentTag.INSTANCE.Lower(@environment)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_use_database(thisPtr, FfiConverterString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -14489,93 +18604,77 @@ public async Task SetDatabase(string @connectionId, string @database, DatabaseEn ); } - /// - public async Task Tables(string @connectionId) { - return await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_favouritestore_tables(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterSequenceTypeFavouriteTableInfo.INSTANCE.Lift(result), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - } -class FfiConverterTypeFavouriteStore: FfiConverter { - public static FfiConverterTypeFavouriteStore INSTANCE = new FfiConverterTypeFavouriteStore(); +class FfiConverterTypeQueryEditor: FfiConverter { + public static FfiConverterTypeQueryEditor INSTANCE = new FfiConverterTypeQueryEditor(); - public override ulong Lower(FavouriteStore value) { + public override ulong Lower(QueryEditor value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override FavouriteStore Lift(ulong value) { - return new FavouriteStore(value); + public override QueryEditor Lift(ulong value) { + return new QueryEditor(value); } - public override FavouriteStore Read(BigEndianStream stream) { + public override QueryEditor Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(FavouriteStore value) { + public override int AllocationSize(QueryEditor value) { return 8; } - public override void Write(FavouriteStore value, BigEndianStream stream) { + public override void Write(QueryEditor value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IForeignImportReview { - ForeignAppTag App(); +internal interface IQueryHistoryStore { /// - Task Apply(); - ForeignImportChoices Choices(); - ForeignConnectionRow[] Connections(); - PasswordOutcomeTag Passwords(); + Task Clear(); /// - bool Resolve(string @reference, ResolutionTag @resolution); - ForeignQueryRow[] SavedQueries(); - void SetIncluded(string @reference, bool @included); - void SetSelected(string @reference, bool @selected); + Task Delete(long[] @ids); + /// + Task Export(long[] @ids, HistoryExportFormat @format, string @path); + FavouriteStore Favourites(); + /// + Task Prune(uint @retentionDays, uint @maxEntries); + /// + Task Record(DatabaseSession @session, HistoryRun @run); + SavedQueryStore SavedQueries(); + /// + Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit); + /// + Task SetPinned(long @id, bool @pinned); + TableFolderStore TableFolders(); } -internal class ForeignImportReview : IForeignImportReview, IDisposable { +internal class QueryHistoryStore : IQueryHistoryStore, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public ForeignImportReview(ulong pointer) { + public QueryHistoryStore(ulong pointer) { this.pointer = pointer; } - ~ForeignImportReview() { + ~QueryHistoryStore() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_foreignimportreview(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_queryhistorystore(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_foreignimportreview(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryhistorystore(this.pointer, ref status); }); } @@ -14643,153 +18742,243 @@ internal T CallWithPointer(Func func) } - public ForeignAppTag App() { - return CallWithPointer(thisPtr => FfiConverterTypeForeignAppTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_app(thisPtr, ref _status) -))); + /// + public async Task Clear() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task Apply() { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_apply(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterTypeForeignImportOutcome.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } - public ForeignImportChoices Choices() { - return CallWithPointer(thisPtr => FfiConverterTypeForeignImportChoices.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_choices(thisPtr, ref _status) -))); + /// + public async Task Export(long[] @ids, HistoryExportFormat @format, string @path) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_export(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids), FfiConverterTypeHistoryExportFormat.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public ForeignConnectionRow[] Connections() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignConnectionRow.INSTANCE.Lift( + public FavouriteStore Favourites() { + return CallWithPointer(thisPtr => FfiConverterTypeFavouriteStore.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_connections(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_favourites(thisPtr, ref _status) ))); } - public PasswordOutcomeTag Passwords() { - return CallWithPointer(thisPtr => FfiConverterTypePasswordOutcomeTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_passwords(thisPtr, ref _status) -))); + /// + public async Task Prune(uint @retentionDays, uint @maxEntries) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_prune(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@retentionDays), FfiConverterUInt32.INSTANCE.Lower(@maxEntries)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterUInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public bool Resolve(string @reference, ResolutionTag @resolution) { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_resolve(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterTypeResolutionTag.INSTANCE.Lower(@resolution), ref _status) -))); + public async Task Record(DatabaseSession @session, HistoryRun @run) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_record(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeHistoryRun.INSTANCE.Lower(@run)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterOptionalInt64.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public ForeignQueryRow[] SavedQueries() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeForeignQueryRow.INSTANCE.Lift( + public SavedQueryStore SavedQueries() { + return CallWithPointer(thisPtr => FfiConverterTypeSavedQueryStore.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_saved_queries(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_saved_queries(thisPtr, ref _status) ))); } - public void SetIncluded(string @reference, bool @included) { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_included(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@included), ref _status) -)); + /// + public async Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_search(thisPtr, FfiConverterString.INSTANCE.Lower(@text), FfiConverterOptionalString.INSTANCE.Lower(@connectionId), FfiConverterOptionalTypeHistoryCursorArg.INSTANCE.Lower(@after), FfiConverterUInt32.INSTANCE.Lower(@limit)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeHistoryPageInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task SetPinned(long @id, bool @pinned) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_set_pinned(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterBoolean.INSTANCE.Lower(@pinned)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - - public void SetSelected(string @reference, bool @selected) { - CallWithPointer(thisPtr => + public TableFolderStore TableFolders() { + return CallWithPointer(thisPtr => FfiConverterTypeTableFolderStore.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_foreignimportreview_set_selected(thisPtr, FfiConverterString.INSTANCE.Lower(@reference), FfiConverterBoolean.INSTANCE.Lower(@selected), ref _status) -)); + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_table_folders(thisPtr, ref _status) +))); } - } -class FfiConverterTypeForeignImportReview: FfiConverter { - public static FfiConverterTypeForeignImportReview INSTANCE = new FfiConverterTypeForeignImportReview(); +class FfiConverterTypeQueryHistoryStore: FfiConverter { + public static FfiConverterTypeQueryHistoryStore INSTANCE = new FfiConverterTypeQueryHistoryStore(); - public override ulong Lower(ForeignImportReview value) { + public override ulong Lower(QueryHistoryStore value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override ForeignImportReview Lift(ulong value) { - return new ForeignImportReview(value); + public override QueryHistoryStore Lift(ulong value) { + return new QueryHistoryStore(value); } - public override ForeignImportReview Read(BigEndianStream stream) { + public override QueryHistoryStore Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(ForeignImportReview value) { + public override int AllocationSize(QueryHistoryStore value) { return 8; } - public override void Write(ForeignImportReview value, BigEndianStream stream) { + public override void Write(QueryHistoryStore value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IKeyReader { - string Key(); +/// +/// The app's handle on a running statement. Dropping it stops the run. +/// +internal interface IQueryRun { + void Cancel(); + /// + /// Every event since the last drain, which also acknowledges the wake. + /// + RunEvent[] DrainEvents(); + /// + /// Waits for the run to end. Dropping the wait leaves the run going. + /// /// - Task ReadMore(CancelToken? @cancel); - ResultSet? Rows(); + Task Outcome(); + /// + /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. + /// + void ReleaseSet(uint @index); + ResultSet? ResultSet(uint @index); } -internal class KeyReader : IKeyReader, IDisposable { +/// +/// The app's handle on a running statement. Dropping it stops the run. +/// +internal class QueryRun : IQueryRun, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public KeyReader(ulong pointer) { + public QueryRun(ulong pointer) { this.pointer = pointer; } - ~KeyReader() { + ~QueryRun() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_keyreader(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_queryrun(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_keyreader(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryrun(this.pointer, ref status); }); } @@ -14857,20 +19046,35 @@ internal T CallWithPointer(Func func) } - public string Key() { - return CallWithPointer(thisPtr => FfiConverterString.INSTANCE.Lift( + public void Cancel() { + CallWithPointer(thisPtr => _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_key(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_cancel(thisPtr, ref _status) +)); + } + + + + /// + /// Every event since the last drain, which also acknowledges the wake. + /// + public RunEvent[] DrainEvents() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeRunEvent.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_drain_events(thisPtr, ref _status) ))); } + /// + /// Waits for the run to end. Dropping the wait leaves the run going. + /// /// - public async Task ReadMore(CancelToken? @cancel) { + public async Task Outcome() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_read_more(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_outcome(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -14881,16 +19085,28 @@ public string Key() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterOptionalTypeKeyWindowInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeRunOutcome.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public ResultSet? Rows() { + /// + /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. + /// + public void ReleaseSet(uint @index) { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_release_set(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@index), ref _status) +)); + } + + + + public ResultSet? ResultSet(uint @index) { return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_keyreader_rows(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_result_set(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@index), ref _status) ))); } @@ -14898,65 +19114,84 @@ public string Key() { } -class FfiConverterTypeKeyReader: FfiConverter { - public static FfiConverterTypeKeyReader INSTANCE = new FfiConverterTypeKeyReader(); +class FfiConverterTypeQueryRun: FfiConverter { + public static FfiConverterTypeQueryRun INSTANCE = new FfiConverterTypeQueryRun(); - public override ulong Lower(KeyReader value) { + public override ulong Lower(QueryRun value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override KeyReader Lift(ulong value) { - return new KeyReader(value); + public override QueryRun Lift(ulong value) { + return new QueryRun(value); } - public override KeyReader Read(BigEndianStream stream) { + public override QueryRun Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(KeyReader value) { + public override int AllocationSize(QueryRun value) { return 8; } - public override void Write(KeyReader value, BigEndianStream stream) { + public override void Write(QueryRun value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IMcpService { +internal interface IResultSet { /// - Task AccessToken(); - void Apply(bool @enabled, ushort @port); + Task ShareMasking(uint @visibleColumns, uint @maxRows); /// - Task RegenerateToken(); - SeenClientInfo[] SeenClients(); - McpStatusTag Status(); - Task Stop(); + Task SharePreview(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); + /// + Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); + /// + CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes); + /// + string? CellText(ulong @row, uint @column); + /// + CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars); + ResultColumnInfo[] Columns(); + /// + string? FilterText(ulong @row, uint @column); + /// + /// Its place among the run's result sets, from 0. + /// + uint Index(); + /// + /// True once every row the set will hold is here. + /// + bool IsFinished(); + ulong OpenCursor(); + ulong RowCount(); + /// + ResultSet Sorted(uint @column, bool @ascending); } -internal class McpService : IMcpService, IDisposable { +internal class ResultSet : IResultSet, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public McpService(ulong pointer) { + public ResultSet(ulong pointer) { this.pointer = pointer; } - ~McpService() { + ~ResultSet() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_mcpservice(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_resultset(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_mcpservice(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_resultset(this.pointer, ref status); }); } @@ -15025,11 +19260,11 @@ internal T CallWithPointer(Func func) /// - public async Task AccessToken() { + public async Task ShareMasking(uint @visibleColumns, uint @maxRows) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_access_token(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_masking(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -15040,275 +19275,206 @@ public async Task AccessToken() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeSecretString.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeShareColumnMasking.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public void Apply(bool @enabled, ushort @port) { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_apply(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@enabled), FfiConverterUInt16.INSTANCE.Lower(@port), ref _status) -)); - } - - - /// - public async Task RegenerateToken() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task SharePreview(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_regenerate_token(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_preview(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeResultSet.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public SeenClientInfo[] SeenClients() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeSeenClientInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_seen_clients(thisPtr, ref _status) -))); - } - - - public McpStatusTag Status() { - return CallWithPointer(thisPtr => FfiConverterTypeMcpStatusTag.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_status(thisPtr, ref _status) -))); - } - - - public async Task Stop() {await _UniFFIAsync.UniffiRustCallAsync( + /// + public async Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_mcpservice_stop(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_summary(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeShareSummary.INSTANCE.Lift(result), // Error - NullCallStatusErrorHandler.INSTANCE - + FfiConverterTypeCoreError.INSTANCE ); } - - -} -class FfiConverterTypeMcpService: FfiConverter { - public static FfiConverterTypeMcpService INSTANCE = new FfiConverterTypeMcpService(); - - - public override ulong Lower(McpService value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override McpService Lift(ulong value) { - return new McpService(value); - } - - public override McpService Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(McpService value) { - return 8; - } - - public override void Write(McpService value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface IPageResume { -} -internal class PageResume : IPageResume, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public PageResume(ulong pointer) { - this.pointer = pointer; + /// + public CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellBytes.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt64.INSTANCE.Lower(@maxBytes), ref _status) +))); } - - ~PageResume() { - Destroy(); + + + /// + public string? CellText(ulong @row, uint @column) { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_text(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) +))); } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_pageresume(this.pointer, ref status); - }); + + + /// + public CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars) { + return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellTextHead.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_text_head(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt32.INSTANCE.Lower(@maxChars), ref _status) +))); } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_pageresume(this.pointer, ref status); - }); + + + public ResultColumnInfo[] Columns() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypeResultColumnInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_columns(thisPtr, ref _status) +))); } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } + + + /// + public string? FilterText(ulong @row, uint @column) { + return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_filter_text(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) +))); } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + + + /// + /// Its place among the run's result sets, from 0. + /// + public uint Index() { + return CallWithPointer(thisPtr => FfiConverterUInt32.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_index(thisPtr, ref _status) +))); } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + + + /// + /// True once every row the set will hold is here. + /// + public bool IsFinished() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_is_finished(thisPtr, ref _status) +))); } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } + + + public ulong OpenCursor() { + return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_open_cursor(thisPtr, ref _status) +))); } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + + + public ulong RowCount() { + return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_row_count(thisPtr, ref _status) +))); } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + + + /// + public ResultSet Sorted(uint @column, bool @ascending) { + return CallWithPointer(thisPtr => FfiConverterTypeResultSet.INSTANCE.Lift( + _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_sorted(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) +))); } - + } -class FfiConverterTypePageResume: FfiConverter { - public static FfiConverterTypePageResume INSTANCE = new FfiConverterTypePageResume(); +class FfiConverterTypeResultSet: FfiConverter { + public static FfiConverterTypeResultSet INSTANCE = new FfiConverterTypeResultSet(); - public override ulong Lower(PageResume value) { + public override ulong Lower(ResultSet value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override PageResume Lift(ulong value) { - return new PageResume(value); + public override ResultSet Lift(ulong value) { + return new ResultSet(value); } - public override PageResume Read(BigEndianStream stream) { + public override ResultSet Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(PageResume value) { + public override int AllocationSize(ResultSet value) { return 8; } - public override void Write(PageResume value, BigEndianStream stream) { + public override void Write(ResultSet value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -/// -/// An editor tab's own connection, which keeps its transaction and -/// session settings from one run to the next. -/// -internal interface IQueryEditor { - /// - /// Closes the editor's connection, ending its transaction. - /// - /// - Task Close(); - string? Database(); - /// - /// The editor's connection is gone. It is never opened again by - /// itself, since its transaction would not come back with it, so the - /// tab opens a new editor. - /// - bool IsLost(); - /// - /// Starts `sql` and returns at once. `listener` hears when events - /// are waiting; the run ends with a `Finished` event. - /// - QueryRun Run(string @sql, RunSettings @settings, RunListener @listener); +internal interface IRowSave { + SaveGate Gate(); + bool IsEmpty(); /// - Task UseDatabase(string @database, CancelToken? @cancel); + Task Run(bool @confirmed, CancelToken? @cancel); + PlannedStatement[] Statements(); } -/// -/// An editor tab's own connection, which keeps its transaction and -/// session settings from one run to the next. -/// -internal class QueryEditor : IQueryEditor, IDisposable { +internal class RowSave : IRowSave, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public QueryEditor(ulong pointer) { + public RowSave(ulong pointer) { this.pointer = pointer; } - ~QueryEditor() { + ~RowSave() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_queryeditor(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_rowsave(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryeditor(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_rowsave(this.pointer, ref status); }); } @@ -15376,149 +19542,130 @@ internal T CallWithPointer(Func func) } - /// - /// Closes the editor's connection, ending its transaction. - /// - /// - public async Task Close() {await _UniFFIAsync.UniffiRustCallAsync( - // Get rust future - CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_close(thisPtr); - }), - // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), - // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); - }, - // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), - // Error - FfiConverterTypeCoreError.INSTANCE - ); - } - - public string? Database() { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( + public SaveGate Gate() { + return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_database(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_gate(thisPtr, ref _status) ))); } - /// - /// The editor's connection is gone. It is never opened again by - /// itself, since its transaction would not come back with it, so the - /// tab opens a new editor. - /// - public bool IsLost() { + public bool IsEmpty() { return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_is_lost(thisPtr, ref _status) -))); - } - - - /// - /// Starts `sql` and returns at once. `listener` hears when events - /// are waiting; the run ends with a `Finished` event. - /// - public QueryRun Run(string @sql, RunSettings @settings, RunListener @listener) { - return CallWithPointer(thisPtr => FfiConverterTypeQueryRun.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_run(thisPtr, FfiConverterString.INSTANCE.Lower(@sql), FfiConverterTypeRunSettings.INSTANCE.Lower(@settings), FfiConverterTypeRunListener.INSTANCE.Lower(@listener), ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_is_empty(thisPtr, ref _status) ))); } /// - public async Task UseDatabase(string @database, CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Run(bool @confirmed, CancelToken? @cancel) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryeditor_use_database(thisPtr, FfiConverterString.INSTANCE.Lower(@database), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRowSaveOutcome.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } + public PlannedStatement[] Statements() { + return CallWithPointer(thisPtr => FfiConverterSequenceTypePlannedStatement.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_statements(thisPtr, ref _status) +))); + } + + } -class FfiConverterTypeQueryEditor: FfiConverter { - public static FfiConverterTypeQueryEditor INSTANCE = new FfiConverterTypeQueryEditor(); +class FfiConverterTypeRowSave: FfiConverter { + public static FfiConverterTypeRowSave INSTANCE = new FfiConverterTypeRowSave(); - public override ulong Lower(QueryEditor value) { + public override ulong Lower(RowSave value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override QueryEditor Lift(ulong value) { - return new QueryEditor(value); + public override RowSave Lift(ulong value) { + return new RowSave(value); } - public override QueryEditor Read(BigEndianStream stream) { + public override RowSave Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(QueryEditor value) { + public override int AllocationSize(RowSave value) { return 8; } - public override void Write(QueryEditor value, BigEndianStream stream) { + public override void Write(RowSave value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -internal interface IQueryHistoryStore { +internal interface ISavedQueryStore { + /// + Task CreateFolder(string @connectionId, string @name, long? @parentId); + /// + Task Delete(long @id); /// - Task Clear(); + Task DeleteFolder(long @id); /// - Task Delete(long[] @ids); + Task DeleteForConnection(string @connectionId); /// - Task Export(long[] @ids, HistoryExportFormat @format, string @path); - FavouriteStore Favourites(); + Task MoveFolder(long @id, long? @parentId); /// - Task Prune(uint @retentionDays, uint @maxEntries); + Task MoveQuery(long @id, long? @folderId, long? @before); /// - Task Record(DatabaseSession @session, HistoryRun @run); - SavedQueryStore SavedQueries(); + Task Rename(long @id, string @name); /// - Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit); + Task RenameFolder(long @id, string @name); /// - Task SetPinned(long @id, bool @pinned); - TableFolderStore TableFolders(); + Task Save(SavedQueryDraft @draft, bool @replace); + /// + Task SetKeyword(long @id, string? @keyword); + /// + Task SetSql(long @id, string @sql); + /// + Task Snapshot(string @connectionId); } -internal class QueryHistoryStore : IQueryHistoryStore, IDisposable { +internal class SavedQueryStore : ISavedQueryStore, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public QueryHistoryStore(ulong pointer) { + public SavedQueryStore(ulong pointer) { this.pointer = pointer; } - ~QueryHistoryStore() { + ~SavedQueryStore() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_queryhistorystore(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_savedquerystore(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryhistorystore(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_savedquerystore(this.pointer, ref status); }); } @@ -15587,28 +19734,32 @@ internal T CallWithPointer(Func func) /// - public async Task Clear() {await _UniFFIAsync.UniffiRustCallAsync( + public async Task CreateFolder(string @connectionId, string @name, long? @parentId) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_clear(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_create_folder(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@name), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i64(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i64(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i64(future), + // Lift + (result) => FfiConverterInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Delete(long @id) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_delete(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -15623,10 +19774,10 @@ public async Task Delete(long[] @ids) {await _UniFFIAsync.UniffiRustCallAsync( } /// - public async Task Export(long[] @ids, HistoryExportFormat @format, string @path) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task DeleteFolder(long @id) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_export(thisPtr, FfiConverterSequenceInt64.INSTANCE.Lower(@ids), FfiConverterTypeHistoryExportFormat.INSTANCE.Lower(@format), FfiConverterString.INSTANCE.Lower(@path)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -15640,20 +19791,12 @@ public async Task Export(long[] @ids, HistoryExportFormat @format, string @path) ); } - public FavouriteStore Favourites() { - return CallWithPointer(thisPtr => FfiConverterTypeFavouriteStore.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_favourites(thisPtr, ref _status) -))); - } - - /// - public async Task Prune(uint @retentionDays, uint @maxEntries) { + public async Task DeleteForConnection(string @connectionId) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_prune(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@retentionDays), FfiConverterUInt32.INSTANCE.Lower(@maxEntries)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete_for_connection(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), @@ -15671,41 +19814,83 @@ public async Task Prune(uint @retentionDays, uint @maxEntries) { } /// - public async Task Record(DatabaseSession @session, HistoryRun @run) { - return await _UniFFIAsync.UniffiRustCallAsync( + public async Task MoveFolder(long @id, long? @parentId) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_record(thisPtr, FfiConverterTypeDatabaseSession.INSTANCE.Lower(@session), FfiConverterTypeHistoryRun.INSTANCE.Lower(@run)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), // Complete - (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), - // Lift - (result) => FfiConverterOptionalInt64.INSTANCE.Lift(result), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); } - public SavedQueryStore SavedQueries() { - return CallWithPointer(thisPtr => FfiConverterTypeSavedQueryStore.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_saved_queries(thisPtr, ref _status) -))); + /// + public async Task MoveQuery(long @id, long? @folderId, long? @before) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_query(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@folderId), FfiConverterOptionalInt64.INSTANCE.Lower(@before)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task Rename(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } /// - public async Task Search(string @text, string? @connectionId, HistoryCursorArg? @after, uint @limit) { + public async Task RenameFolder(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Save(SavedQueryDraft @draft, bool @replace) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_search(thisPtr, FfiConverterString.INSTANCE.Lower(@text), FfiConverterOptionalString.INSTANCE.Lower(@connectionId), FfiConverterOptionalTypeHistoryCursorArg.INSTANCE.Lower(@after), FfiConverterUInt32.INSTANCE.Lower(@limit)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_save(thisPtr, FfiConverterTypeSavedQueryDraft.INSTANCE.Lower(@draft), FfiConverterBoolean.INSTANCE.Lower(@replace)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -15716,17 +19901,17 @@ public async Task Search(string @text, string? @connectionId, H // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeHistoryPageInfo.INSTANCE.Lift(result), + (result) => FfiConverterOptionalInt64.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task SetPinned(long @id, bool @pinned) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task SetKeyword(long @id, string? @keyword) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_set_pinned(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterBoolean.INSTANCE.Lower(@pinned)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_keyword(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@keyword)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -15740,89 +19925,211 @@ public async Task SetPinned(long @id, bool @pinned) {await _UniFFIAsync.UniffiRu ); } - public TableFolderStore TableFolders() { - return CallWithPointer(thisPtr => FfiConverterTypeTableFolderStore.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryhistorystore_table_folders(thisPtr, ref _status) -))); + /// + public async Task SetSql(long @id, string @sql) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_sql(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@sql)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task Snapshot(string @connectionId) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_snapshot(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSavedQueriesInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } } -class FfiConverterTypeQueryHistoryStore: FfiConverter { - public static FfiConverterTypeQueryHistoryStore INSTANCE = new FfiConverterTypeQueryHistoryStore(); +class FfiConverterTypeSavedQueryStore: FfiConverter { + public static FfiConverterTypeSavedQueryStore INSTANCE = new FfiConverterTypeSavedQueryStore(); - public override ulong Lower(QueryHistoryStore value) { + public override ulong Lower(SavedQueryStore value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override QueryHistoryStore Lift(ulong value) { - return new QueryHistoryStore(value); + public override SavedQueryStore Lift(ulong value) { + return new SavedQueryStore(value); } - public override QueryHistoryStore Read(BigEndianStream stream) { + public override SavedQueryStore Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(QueryHistoryStore value) { + public override int AllocationSize(SavedQueryStore value) { return 8; } - public override void Write(QueryHistoryStore value, BigEndianStream stream) { + public override void Write(SavedQueryStore value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } -/// -/// The app's handle on a running statement. Dropping it stops the run. -/// -internal interface IQueryRun { - void Cancel(); - /// - /// Every event since the last drain, which also acknowledges the wake. - /// - RunEvent[] DrainEvents(); - /// - /// Waits for the run to end. Dropping the wait leaves the run going. - /// +internal interface ISyncService { /// - Task Outcome(); - /// - /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. - /// - void ReleaseSet(uint @index); - ResultSet? ResultSet(uint @index); + Task AcceptKeyChange(string @account, string @offeredIk, bool @compared); + /// + Task AcceptTeamRestart(string @team, string @signerIk); + /// + Task AccountDevices(); + /// + Task AccountFingerprint(string @account); + /// + Task AccountKeyChange(string @account); + /// + Task ActivateReset(string @reset); + /// + Task ApprovalRequests(); + /// + Task ApprovalSession(string @request); + /// + Task ApprovalWordsDiffer(string @request); + /// + Task BeginDeviceRemoval(SecretString @recoveryKey, string[] @lost); + /// + Task BeginGenesis(); + /// + Task BeginReplaceRecoveryKey(SecretString @recoveryKey); + /// + Task BeginReset(ResetKindTag @kind); + /// + Task CancelApprovalSession(string @request); + /// + Task CancelReset(string @reset, SecretString? @recoveryKey); + /// + Task ChooseApprovalRequest(string @request); + /// + Task CompareFingerprintQr(string @account, string @text); + /// + Task ConfirmApprovalSession(string @request); + /// + Task ConfirmMember(string @team, string @account); + /// + Task CreateTeamKeys(string @team); + /// + Task CredentialsToRotate(string @scope); + /// + Task DismissKeyNotice(string @notice); + /// + Task FinishDeviceRemoval(string @review, string[] @keep, ReviewedMemberInfo[] @remove); + /// + Task FinishGenesis(string @draft, SecretString[] @typed); + /// + Task FinishReplaceRecoveryKey(string @draft, SecretString[] @typed, string[] @keep); + /// + Task FinishResetProposal(string @draft, SecretString[] @typed); + /// + Task HeldTeamRestart(string @team); + /// + Task KeyNotices(); + /// + Task KeyState(); + /// + Task OwnFingerprint(); + /// + Task PendingReset(); + /// + Task RecoverWithRecoveryKey(SecretString @recoveryKey); + /// + Task RemoveDeviceRow(string @device); + /// + Task RequestApproval(); + /// + Task RestartTeamKey(string @team, string[] @confirm); + /// + Task RotateTeamKey(string @team, string[] @remove); + /// + Task SignOutKeys(); + /// + Task TeamKeys(string @team); + /// + Task Approvals(); + /// + Task ChooseForNewIdentity(NewIdentityChoiceTag @choice); + /// + Task ChooseProvider(SyncProviderTag @provider); + /// + Task Conflicts(); + /// + Task DecideApproval(SyncRecordRef @record, string @field, bool @approve); + /// + Task DeleteIcloudZone(); + /// + Task HeldRecords(); + /// + Task LoadOlderHistory(); + /// + Task MoveToIcloud(ulong @confirmedDeletions); + /// + Task MoveToService(); + /// + Task PlanMoveToIcloud(); + /// + Task PlanMoveToService(); + /// + Task RecordHostChanges(string @kind, string[] @written, string[] @deleted); + /// + Task ResolveConflict(SyncRecordRef @record, ConflictChoiceTag @keep); + /// + Task SetCategories(SyncCategoriesArg @categories); + SyncStatusInfo Status(); + /// + Task SyncNow(PassReasonTag @why); + /// + Task UploadAgain(); } -/// -/// The app's handle on a running statement. Dropping it stops the run. -/// -internal class QueryRun : IQueryRun, IDisposable { +internal class SyncService : ISyncService, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public QueryRun(ulong pointer) { + public SyncService(ulong pointer) { this.pointer = pointer; } - ~QueryRun() { + ~SyncService() { Destroy(); } protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_queryrun(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_syncservice(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_queryrun(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_syncservice(this.pointer, ref status); }); } @@ -15890,35 +20197,260 @@ internal T CallWithPointer(Func func) } - public void Cancel() { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_cancel(thisPtr, ref _status) -)); + /// + public async Task AcceptKeyChange(string @account, string @offeredIk, bool @compared) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_accept_key_change(thisPtr, FfiConverterString.INSTANCE.Lower(@account), FfiConverterString.INSTANCE.Lower(@offeredIk), FfiConverterBoolean.INSTANCE.Lower(@compared)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task AcceptTeamRestart(string @team, string @signerIk) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_accept_team_restart(thisPtr, FfiConverterString.INSTANCE.Lower(@team), FfiConverterString.INSTANCE.Lower(@signerIk)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// + public async Task AccountDevices() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_account_devices(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeAccountDeviceInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - /// - /// Every event since the last drain, which also acknowledges the wake. - /// - public RunEvent[] DrainEvents() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeRunEvent.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_drain_events(thisPtr, ref _status) -))); + /// + public async Task AccountFingerprint(string @account) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_account_fingerprint(thisPtr, FfiConverterString.INSTANCE.Lower(@account)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFingerprintInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } + /// + public async Task AccountKeyChange(string @account) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_account_key_change(thisPtr, FfiConverterString.INSTANCE.Lower(@account)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterOptionalTypeKeyChangeInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } - /// - /// Waits for the run to end. Dropping the wait leaves the run going. - /// /// - public async Task Outcome() { + public async Task ActivateReset(string @reset) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_activate_reset(thisPtr, FfiConverterString.INSTANCE.Lower(@reset)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ApprovalRequests() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_approval_requests(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeApprovalRequestInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ApprovalSession(string @request) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_approval_session(thisPtr, FfiConverterString.INSTANCE.Lower(@request)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeApprovalSessionInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ApprovalWordsDiffer(string @request) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_approval_words_differ(thisPtr, FfiConverterString.INSTANCE.Lower(@request)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task BeginDeviceRemoval(SecretString @recoveryKey, string[] @lost) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_begin_device_removal(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@recoveryKey), FfiConverterSequenceString.INSTANCE.Lower(@lost)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRemovalReviewInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task BeginGenesis() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_begin_genesis(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRecoveryKeyDraftInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task BeginReplaceRecoveryKey(SecretString @recoveryKey) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_begin_replace_recovery_key(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@recoveryKey)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeRotationDraftInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task BeginReset(ResetKindTag @kind) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_outcome(thisPtr); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_begin_reset(thisPtr, FfiConverterTypeResetKindTag.INSTANCE.Lower(@kind)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -15929,186 +20461,54 @@ public async Task Outcome() { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeRunOutcome.INSTANCE.Lift(result), + (result) => FfiConverterTypeRecoveryKeyDraftInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - /// - /// The app shows this set no more, so the run lets go of its rows; they go once no `ResultSet` holds them. - /// - public void ReleaseSet(uint @index) { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_release_set(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@index), ref _status) -)); - } - - - - public ResultSet? ResultSet(uint @index) { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeResultSet.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_queryrun_result_set(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@index), ref _status) -))); + /// + public async Task CancelApprovalSession(string @request) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_cancel_approval_session(thisPtr, FfiConverterString.INSTANCE.Lower(@request)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - - -} -class FfiConverterTypeQueryRun: FfiConverter { - public static FfiConverterTypeQueryRun INSTANCE = new FfiConverterTypeQueryRun(); - - - public override ulong Lower(QueryRun value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override QueryRun Lift(ulong value) { - return new QueryRun(value); - } - - public override QueryRun Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(QueryRun value) { - return 8; - } - - public override void Write(QueryRun value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface IResultSet { - /// - Task ShareMasking(uint @visibleColumns, uint @maxRows); - /// - Task SharePreview(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); - /// - Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns); - /// - CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes); - /// - string? CellText(ulong @row, uint @column); - /// - CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars); - ResultColumnInfo[] Columns(); - /// - string? FilterText(ulong @row, uint @column); - /// - /// Its place among the run's result sets, from 0. - /// - uint Index(); - /// - /// True once every row the set will hold is here. - /// - bool IsFinished(); - ulong OpenCursor(); - ulong RowCount(); /// - ResultSet Sorted(uint @column, bool @ascending); -} -internal class ResultSet : IResultSet, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public ResultSet(ulong pointer) { - this.pointer = pointer; - } - - ~ResultSet() { - Destroy(); - } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_resultset(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_resultset(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + public async Task CancelReset(string @reset, SecretString? @recoveryKey) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_cancel_reset(thisPtr, FfiConverterString.INSTANCE.Lower(@reset), FfiConverterOptionalTypeSecretString.INSTANCE.Lower(@recoveryKey)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task ShareMasking(uint @visibleColumns, uint @maxRows) { + public async Task ChooseApprovalRequest(string @request) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_masking(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_choose_approval_request(thisPtr, FfiConverterString.INSTANCE.Lower(@request)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -16119,40 +20519,40 @@ public async Task ShareMasking(uint @visibleColumns, uint // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterSequenceTypeShareColumnMasking.INSTANCE.Lift(result), + (result) => FfiConverterTypeApprovalSessionInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task SharePreview(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns) { + public async Task CompareFingerprintQr(string @account, string @text) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_preview(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_compare_fingerprint_qr(thisPtr, FfiConverterString.INSTANCE.Lower(@account), FfiConverterString.INSTANCE.Lower(@text)); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), // Lift - (result) => FfiConverterTypeResultSet.INSTANCE.Lift(result), + (result) => FfiConverterBoolean.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task ShareSummary(uint @visibleColumns, uint @maxRows, ShareColumnChoice[] @columns) { + public async Task ConfirmApprovalSession(string @request) { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_share_summary(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows), FfiConverterSequenceTypeShareColumnChoice.INSTANCE.Lower(@columns)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_confirm_approval_session(thisPtr, FfiConverterString.INSTANCE.Lower(@request)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -16163,251 +20563,218 @@ public async Task ShareSummary(uint @visibleColumns, uint @maxRows // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeShareSummary.INSTANCE.Lift(result), + (result) => FfiConverterTypeApprovalSessionInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public CellBytes? CellBytes(ulong @row, uint @column, ulong @maxBytes) { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellBytes.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_bytes(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt64.INSTANCE.Lower(@maxBytes), ref _status) -))); + public async Task ConfirmMember(string @team, string @account) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_confirm_member(thisPtr, FfiConverterString.INSTANCE.Lower(@team), FfiConverterString.INSTANCE.Lower(@account)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public string? CellText(ulong @row, uint @column) { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_text(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) -))); + public async Task CreateTeamKeys(string @team) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_create_team_keys(thisPtr, FfiConverterString.INSTANCE.Lower(@team)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public CellTextHead? CellTextHead(ulong @row, uint @column, uint @maxChars) { - return CallWithPointer(thisPtr => FfiConverterOptionalTypeCellTextHead.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_cell_text_head(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterUInt32.INSTANCE.Lower(@maxChars), ref _status) -))); - } - - - public ResultColumnInfo[] Columns() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypeResultColumnInfo.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_columns(thisPtr, ref _status) -))); + public async Task CredentialsToRotate(string @scope) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_credentials_to_rotate(thisPtr, FfiConverterString.INSTANCE.Lower(@scope)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceString.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public string? FilterText(ulong @row, uint @column) { - return CallWithPointer(thisPtr => FfiConverterOptionalString.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_filter_text(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@row), FfiConverterUInt32.INSTANCE.Lower(@column), ref _status) -))); - } - - - /// - /// Its place among the run's result sets, from 0. - /// - public uint Index() { - return CallWithPointer(thisPtr => FfiConverterUInt32.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_index(thisPtr, ref _status) -))); - } - - - /// - /// True once every row the set will hold is here. - /// - public bool IsFinished() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_is_finished(thisPtr, ref _status) -))); + public async Task DismissKeyNotice(string @notice) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_dismiss_key_notice(thisPtr, FfiConverterString.INSTANCE.Lower(@notice)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public ulong OpenCursor() { - return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_open_cursor(thisPtr, ref _status) -))); + /// + public async Task FinishDeviceRemoval(string @review, string[] @keep, ReviewedMemberInfo[] @remove) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_finish_device_removal(thisPtr, FfiConverterString.INSTANCE.Lower(@review), FfiConverterSequenceString.INSTANCE.Lower(@keep), FfiConverterSequenceTypeReviewedMemberInfo.INSTANCE.Lower(@remove)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public ulong RowCount() { - return CallWithPointer(thisPtr => FfiConverterUInt64.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_row_count(thisPtr, ref _status) -))); + /// + public async Task FinishGenesis(string @draft, SecretString[] @typed) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_finish_genesis(thisPtr, FfiConverterString.INSTANCE.Lower(@draft), FfiConverterSequenceTypeSecretString.INSTANCE.Lower(@typed)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeGenesisOutcomeTag.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public ResultSet Sorted(uint @column, bool @ascending) { - return CallWithPointer(thisPtr => FfiConverterTypeResultSet.INSTANCE.Lift( - _UniffiHelpers.RustCallWithError(FfiConverterTypeCoreError.INSTANCE, (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_resultset_sorted(thisPtr, FfiConverterUInt32.INSTANCE.Lower(@column), FfiConverterBoolean.INSTANCE.Lower(@ascending), ref _status) -))); + public async Task FinishReplaceRecoveryKey(string @draft, SecretString[] @typed, string[] @keep) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_finish_replace_recovery_key(thisPtr, FfiConverterString.INSTANCE.Lower(@draft), FfiConverterSequenceTypeSecretString.INSTANCE.Lower(@typed), FfiConverterSequenceString.INSTANCE.Lower(@keep)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - - -} -class FfiConverterTypeResultSet: FfiConverter { - public static FfiConverterTypeResultSet INSTANCE = new FfiConverterTypeResultSet(); - - - public override ulong Lower(ResultSet value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override ResultSet Lift(ulong value) { - return new ResultSet(value); - } - - public override ResultSet Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(ResultSet value) { - return 8; - } - - public override void Write(ResultSet value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface IRowSave { - SaveGate Gate(); - bool IsEmpty(); /// - Task Run(bool @confirmed, CancelToken? @cancel); - PlannedStatement[] Statements(); -} -internal class RowSave : IRowSave, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public RowSave(ulong pointer) { - this.pointer = pointer; - } - - ~RowSave() { - Destroy(); - } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_rowsave(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_rowsave(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } - } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } - } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + public async Task FinishResetProposal(string @draft, SecretString[] @typed) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_finish_reset_proposal(thisPtr, FfiConverterString.INSTANCE.Lower(@draft), FfiConverterSequenceTypeSecretString.INSTANCE.Lower(@typed)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypePendingResetInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public SaveGate Gate() { - return CallWithPointer(thisPtr => FfiConverterTypeSaveGate.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_gate(thisPtr, ref _status) -))); + /// + public async Task HeldTeamRestart(string @team) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_held_team_restart(thisPtr, FfiConverterString.INSTANCE.Lower(@team)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterOptionalTypeHeldRestartInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public bool IsEmpty() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_is_empty(thisPtr, ref _status) -))); + /// + public async Task KeyNotices() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_key_notices(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeKeyNoticeInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task Run(bool @confirmed, CancelToken? @cancel) { + public async Task KeyState() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_run(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@confirmed), FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_key_state(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -16418,192 +20785,119 @@ public async Task Run(bool @confirmed, CancelToken? @cancel) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeRowSaveOutcome.INSTANCE.Lift(result), + (result) => FfiConverterTypeKeyStateInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } - public PlannedStatement[] Statements() { - return CallWithPointer(thisPtr => FfiConverterSequenceTypePlannedStatement.INSTANCE.Lift( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_rowsave_statements(thisPtr, ref _status) -))); + /// + public async Task OwnFingerprint() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_own_fingerprint(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeFingerprintInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - - -} -class FfiConverterTypeRowSave: FfiConverter { - public static FfiConverterTypeRowSave INSTANCE = new FfiConverterTypeRowSave(); - - - public override ulong Lower(RowSave value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override RowSave Lift(ulong value) { - return new RowSave(value); - } - - public override RowSave Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); - } - - public override int AllocationSize(RowSave value) { - return 8; - } - - public override void Write(RowSave value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); - } -} - - - -internal interface ISavedQueryStore { - /// - Task CreateFolder(string @connectionId, string @name, long? @parentId); - /// - Task Delete(long @id); - /// - Task DeleteFolder(long @id); - /// - Task DeleteForConnection(string @connectionId); - /// - Task MoveFolder(long @id, long? @parentId); - /// - Task MoveQuery(long @id, long? @folderId, long? @before); - /// - Task Rename(long @id, string @name); - /// - Task RenameFolder(long @id, string @name); - /// - Task Save(SavedQueryDraft @draft, bool @replace); - /// - Task SetKeyword(long @id, string? @keyword); - /// - Task SetSql(long @id, string @sql); /// - Task Snapshot(string @connectionId); -} -internal class SavedQueryStore : ISavedQueryStore, IDisposable { - protected ulong pointer; - private int _wasDestroyed = 0; - private long _callCounter = 1; - - public SavedQueryStore(ulong pointer) { - this.pointer = pointer; - } - - ~SavedQueryStore() { - Destroy(); - } - - protected void FreeRustArcPtr() { - _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_savedquerystore(this.pointer, ref status); - }); - } - - protected ulong CloneRustArcPtr() { - return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_savedquerystore(this.pointer, ref status); - }); - } - - public void Destroy() - { - // Only allow a single call to this method. - if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) - { - // This decrement always matches the initial count of 1 given at creation time. - if (Interlocked.Decrement(ref _callCounter) == 0) - { - FreeRustArcPtr(); - } - } - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. - } - - private void IncrementCallCounter() - { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - long count; - do - { - count = Interlocked.Read(ref _callCounter); - if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); - if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); - - } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); - } - - private void DecrementCallCounter() - { - // This decrement always matches the increment we performed above. - if (Interlocked.Decrement(ref _callCounter) == 0) { - FreeRustArcPtr(); - } + public async Task PendingReset() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_pending_reset(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterOptionalTypePendingResetInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - internal void CallWithPointer(Action action) - { - IncrementCallCounter(); - try { - action(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + + /// + public async Task RecoverWithRecoveryKey(SecretString @recoveryKey) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_recover_with_recovery_key(thisPtr, FfiConverterTypeSecretString.INSTANCE.Lower(@recoveryKey)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - internal T CallWithPointer(Func func) - { - IncrementCallCounter(); - try { - return func(CloneRustArcPtr()); - } - finally { - DecrementCallCounter(); - } + + /// + public async Task RemoveDeviceRow(string @device) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_remove_device_row(thisPtr, FfiConverterString.INSTANCE.Lower(@device)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - /// - public async Task CreateFolder(string @connectionId, string @name, long? @parentId) { + public async Task RequestApproval() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_create_folder(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId), FfiConverterString.INSTANCE.Lower(@name), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_request_approval(thisPtr); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterInt64.INSTANCE.Lift(result), + (result) => FfiConverterString.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task Delete(long @id) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task RestartTeamKey(string @team, string[] @confirm) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_restart_team_key(thisPtr, FfiConverterString.INSTANCE.Lower(@team), FfiConverterSequenceString.INSTANCE.Lower(@confirm)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16618,10 +20912,10 @@ public async Task Delete(long @id) {await _UniFFIAsync.UniffiRustCallAsync( } /// - public async Task DeleteFolder(long @id) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task RotateTeamKey(string @team, string[] @remove) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_rotate_team_key(thisPtr, FfiConverterString.INSTANCE.Lower(@team), FfiConverterSequenceString.INSTANCE.Lower(@remove)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16636,32 +20930,76 @@ public async Task DeleteFolder(long @id) {await _UniFFIAsync.UniffiRustCallAsync } /// - public async Task DeleteForConnection(string @connectionId) { + public async Task SignOutKeys() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_delete_for_connection(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_sign_out_keys(thisPtr); }), // Poll - (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), // Complete (ulong future, ref UniffiRustCallStatus status) => { - return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); }, // Free - (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterUInt64.INSTANCE.Lift(result), + (result) => FfiConverterTypeSignOutOutcomeTag.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task MoveFolder(long @id, long? @parentId) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task TeamKeys(string @team) { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@parentId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_team_keys(thisPtr, FfiConverterString.INSTANCE.Lower(@team)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeTeamKeysInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task Approvals() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_approvals(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypePendingApprovalInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ChooseForNewIdentity(NewIdentityChoiceTag @choice) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_choose_for_new_identity(thisPtr, FfiConverterTypeNewIdentityChoiceTag.INSTANCE.Lower(@choice)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16676,10 +21014,10 @@ public async Task MoveFolder(long @id, long? @parentId) {await _UniFFIAsync.Unif } /// - public async Task MoveQuery(long @id, long? @folderId, long? @before) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task ChooseProvider(SyncProviderTag @provider) {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_move_query(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalInt64.INSTANCE.Lower(@folderId), FfiConverterOptionalInt64.INSTANCE.Lower(@before)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_choose_provider(thisPtr, FfiConverterTypeSyncProviderTag.INSTANCE.Lower(@provider)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16694,10 +21032,32 @@ public async Task MoveQuery(long @id, long? @folderId, long? @before) {await _Un } /// - public async Task Rename(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task Conflicts() { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_conflicts(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeTeamConflictInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task DecideApproval(SyncRecordRef @record, string @field, bool @approve) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_decide_approval(thisPtr, FfiConverterTypeSyncRecordRef.INSTANCE.Lower(@record), FfiConverterString.INSTANCE.Lower(@field), FfiConverterBoolean.INSTANCE.Lower(@approve)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16712,10 +21072,10 @@ public async Task Rename(long @id, string @name) {await _UniFFIAsync.UniffiRustC } /// - public async Task RenameFolder(long @id, string @name) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task DeleteIcloudZone() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_rename_folder(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@name)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_delete_icloud_zone(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16730,11 +21090,11 @@ public async Task RenameFolder(long @id, string @name) {await _UniFFIAsync.Uniff } /// - public async Task Save(SavedQueryDraft @draft, bool @replace) { + public async Task HeldRecords() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_save(thisPtr, FfiConverterTypeSavedQueryDraft.INSTANCE.Lower(@draft), FfiConverterBoolean.INSTANCE.Lower(@replace)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_held_records(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -16745,17 +21105,39 @@ public async Task RenameFolder(long @id, string @name) {await _UniFFIAsync.Uniff // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterOptionalInt64.INSTANCE.Lift(result), + (result) => FfiConverterSequenceTypeHeldRecordInfo.INSTANCE.Lift(result), // Error FfiConverterTypeCoreError.INSTANCE ); } /// - public async Task SetKeyword(long @id, string? @keyword) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task LoadOlderHistory() { + return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_keyword(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterOptionalString.INSTANCE.Lower(@keyword)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_load_older_history(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + // Lift + (result) => FfiConverterBoolean.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task MoveToIcloud(ulong @confirmedDeletions) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_move_to_icloud(thisPtr, FfiConverterUInt64.INSTANCE.Lower(@confirmedDeletions)); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16770,10 +21152,10 @@ public async Task SetKeyword(long @id, string? @keyword) {await _UniFFIAsync.Uni } /// - public async Task SetSql(long @id, string @sql) {await _UniFFIAsync.UniffiRustCallAsync( + public async Task MoveToService() {await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_set_sql(thisPtr, FfiConverterInt64.INSTANCE.Lower(@id), FfiConverterString.INSTANCE.Lower(@sql)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_move_to_service(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), @@ -16788,11 +21170,11 @@ public async Task SetSql(long @id, string @sql) {await _UniFFIAsync.UniffiRustCa } /// - public async Task Snapshot(string @connectionId) { + public async Task PlanMoveToIcloud() { return await _UniFFIAsync.UniffiRustCallAsync( // Get rust future CallWithPointer(thisPtr => { - return _UniFFILib.uniffi_tablepro_ffi_fn_method_savedquerystore_snapshot(thisPtr, FfiConverterString.INSTANCE.Lower(@connectionId)); + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_plan_move_to_icloud(thisPtr); }), // Poll (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), @@ -16803,7 +21185,127 @@ public async Task Snapshot(string @connectionId) { // Free (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), // Lift - (result) => FfiConverterTypeSavedQueriesInfo.INSTANCE.Lift(result), + (result) => FfiConverterTypeMoveBackPlanInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task PlanMoveToService() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_plan_move_to_service(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeMovePlanInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RecordHostChanges(string @kind, string[] @written, string[] @deleted) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_record_host_changes(thisPtr, FfiConverterString.INSTANCE.Lower(@kind), FfiConverterSequenceString.INSTANCE.Lower(@written), FfiConverterSequenceString.INSTANCE.Lower(@deleted)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ResolveConflict(SyncRecordRef @record, ConflictChoiceTag @keep) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_resolve_conflict(thisPtr, FfiConverterTypeSyncRecordRef.INSTANCE.Lower(@record), FfiConverterTypeConflictChoiceTag.INSTANCE.Lower(@keep)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task SetCategories(SyncCategoriesArg @categories) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_set_categories(thisPtr, FfiConverterTypeSyncCategoriesArg.INSTANCE.Lower(@categories)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public SyncStatusInfo Status() { + return CallWithPointer(thisPtr => FfiConverterTypeSyncStatusInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_status(thisPtr, ref _status) +))); + } + + + /// + public async Task SyncNow(PassReasonTag @why) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_sync_now(thisPtr, FfiConverterTypePassReasonTag.INSTANCE.Lower(@why)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task UploadAgain() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_syncservice_upload_again(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), // Error FfiConverterTypeCoreError.INSTANCE ); @@ -16812,27 +21314,27 @@ public async Task Snapshot(string @connectionId) { } -class FfiConverterTypeSavedQueryStore: FfiConverter { - public static FfiConverterTypeSavedQueryStore INSTANCE = new FfiConverterTypeSavedQueryStore(); +class FfiConverterTypeSyncService: FfiConverter { + public static FfiConverterTypeSyncService INSTANCE = new FfiConverterTypeSyncService(); - public override ulong Lower(SavedQueryStore value) { + public override ulong Lower(SyncService value) { return value.CallWithPointer(thisPtr => thisPtr); } - public override SavedQueryStore Lift(ulong value) { - return new SavedQueryStore(value); + public override SyncService Lift(ulong value) { + return new SyncService(value); } - public override SavedQueryStore Read(BigEndianStream stream) { + public override SyncService Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(SavedQueryStore value) { + public override int AllocationSize(SyncService value) { return 8; } - public override void Write(SavedQueryStore value, BigEndianStream stream) { + public override void Write(SyncService value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -17770,6 +22272,56 @@ public override void Write(AccountConfig value, BigEndianStream stream) { +internal record AccountDeviceInfo ( + string KeyDevice, + string? Device, + string? Name, + string? Platform, + long? AddedAtUs, + bool ThisDevice, + bool Compared +) { +} + +class FfiConverterTypeAccountDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterTypeAccountDeviceInfo INSTANCE = new FfiConverterTypeAccountDeviceInfo(); + + public override AccountDeviceInfo Read(BigEndianStream stream) { + return new AccountDeviceInfo( + KeyDevice: FfiConverterString.INSTANCE.Read(stream), + Device: FfiConverterOptionalString.INSTANCE.Read(stream), + Name: FfiConverterOptionalString.INSTANCE.Read(stream), + Platform: FfiConverterOptionalString.INSTANCE.Read(stream), + AddedAtUs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + ThisDevice: FfiConverterBoolean.INSTANCE.Read(stream), + Compared: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(AccountDeviceInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.KeyDevice) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Device) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Platform) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.AddedAtUs) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.ThisDevice) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Compared); + } + + public override void Write(AccountDeviceInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.KeyDevice, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Device, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Platform, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.AddedAtUs, stream); + FfiConverterBoolean.INSTANCE.Write(value.ThisDevice, stream); + FfiConverterBoolean.INSTANCE.Write(value.Compared, stream); + } +} + + + internal record AccountStatusInfo ( AccountStateTag State, string? AccountId, @@ -18116,6 +22668,86 @@ public override void Write(AiSettingsArg value, BigEndianStream stream) { +internal record ApprovalRequestInfo ( + string Request, + string? Device, + string? DeviceName, + string? Platform, + long RequestedAtUs +) { +} + +class FfiConverterTypeApprovalRequestInfo: FfiConverterRustBuffer { + public static FfiConverterTypeApprovalRequestInfo INSTANCE = new FfiConverterTypeApprovalRequestInfo(); + + public override ApprovalRequestInfo Read(BigEndianStream stream) { + return new ApprovalRequestInfo( + Request: FfiConverterString.INSTANCE.Read(stream), + Device: FfiConverterOptionalString.INSTANCE.Read(stream), + DeviceName: FfiConverterOptionalString.INSTANCE.Read(stream), + Platform: FfiConverterOptionalString.INSTANCE.Read(stream), + RequestedAtUs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ApprovalRequestInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Request) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Device) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.DeviceName) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Platform) + + FfiConverterInt64.INSTANCE.AllocationSize(value.RequestedAtUs); + } + + public override void Write(ApprovalRequestInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Request, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Device, stream); + FfiConverterOptionalString.INSTANCE.Write(value.DeviceName, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Platform, stream); + FfiConverterInt64.INSTANCE.Write(value.RequestedAtUs, stream); + } +} + + + +internal record ApprovalSessionInfo ( + string Request, + SessionRoleTag Role, + SessionPhaseTag Phase, + long ExpiresAtUs +) { +} + +class FfiConverterTypeApprovalSessionInfo: FfiConverterRustBuffer { + public static FfiConverterTypeApprovalSessionInfo INSTANCE = new FfiConverterTypeApprovalSessionInfo(); + + public override ApprovalSessionInfo Read(BigEndianStream stream) { + return new ApprovalSessionInfo( + Request: FfiConverterString.INSTANCE.Read(stream), + Role: FfiConverterTypeSessionRoleTag.INSTANCE.Read(stream), + Phase: FfiConverterTypeSessionPhaseTag.INSTANCE.Read(stream), + ExpiresAtUs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ApprovalSessionInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Request) + + FfiConverterTypeSessionRoleTag.INSTANCE.AllocationSize(value.Role) + + FfiConverterTypeSessionPhaseTag.INSTANCE.AllocationSize(value.Phase) + + FfiConverterInt64.INSTANCE.AllocationSize(value.ExpiresAtUs); + } + + public override void Write(ApprovalSessionInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Request, stream); + FfiConverterTypeSessionRoleTag.INSTANCE.Write(value.Role, stream); + FfiConverterTypeSessionPhaseTag.INSTANCE.Write(value.Phase, stream); + FfiConverterInt64.INSTANCE.Write(value.ExpiresAtUs, stream); + } +} + + + internal record CatalogAbilities ( bool TruncateTable, bool TruncateCascade, @@ -18414,6 +23046,176 @@ public override void Write(CloudGroupFields value, BigEndianStream stream) { +internal record CloudKitAccount ( + string UserRecordName +) { +} + +class FfiConverterTypeCloudKitAccount: FfiConverterRustBuffer { + public static FfiConverterTypeCloudKitAccount INSTANCE = new FfiConverterTypeCloudKitAccount(); + + public override CloudKitAccount Read(BigEndianStream stream) { + return new CloudKitAccount( + UserRecordName: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudKitAccount value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.UserRecordName); + } + + public override void Write(CloudKitAccount value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.UserRecordName, stream); + } +} + + + +internal record CloudKitChanges ( + CloudKitRecord[] Changed, + CloudKitDeletion[] Deleted, + string[] Unfetched, + byte[] Token, + bool More +) { +} + +class FfiConverterTypeCloudKitChanges: FfiConverterRustBuffer { + public static FfiConverterTypeCloudKitChanges INSTANCE = new FfiConverterTypeCloudKitChanges(); + + public override CloudKitChanges Read(BigEndianStream stream) { + return new CloudKitChanges( + Changed: FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Read(stream), + Deleted: FfiConverterSequenceTypeCloudKitDeletion.INSTANCE.Read(stream), + Unfetched: FfiConverterSequenceString.INSTANCE.Read(stream), + Token: FfiConverterByteArray.INSTANCE.Read(stream), + More: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudKitChanges value) { + return 0 + + FfiConverterSequenceTypeCloudKitRecord.INSTANCE.AllocationSize(value.Changed) + + FfiConverterSequenceTypeCloudKitDeletion.INSTANCE.AllocationSize(value.Deleted) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Unfetched) + + FfiConverterByteArray.INSTANCE.AllocationSize(value.Token) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.More); + } + + public override void Write(CloudKitChanges value, BigEndianStream stream) { + FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Write(value.Changed, stream); + FfiConverterSequenceTypeCloudKitDeletion.INSTANCE.Write(value.Deleted, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Unfetched, stream); + FfiConverterByteArray.INSTANCE.Write(value.Token, stream); + FfiConverterBoolean.INSTANCE.Write(value.More, stream); + } +} + + + +internal record CloudKitDeletion ( + string Name, + string RecordType +) { +} + +class FfiConverterTypeCloudKitDeletion: FfiConverterRustBuffer { + public static FfiConverterTypeCloudKitDeletion INSTANCE = new FfiConverterTypeCloudKitDeletion(); + + public override CloudKitDeletion Read(BigEndianStream stream) { + return new CloudKitDeletion( + Name: FfiConverterString.INSTANCE.Read(stream), + RecordType: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudKitDeletion value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.RecordType); + } + + public override void Write(CloudKitDeletion value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.RecordType, stream); + } +} + + + +internal record CloudKitField ( + string Name, + CloudKitValue? Value +) { +} + +class FfiConverterTypeCloudKitField: FfiConverterRustBuffer { + public static FfiConverterTypeCloudKitField INSTANCE = new FfiConverterTypeCloudKitField(); + + public override CloudKitField Read(BigEndianStream stream) { + return new CloudKitField( + Name: FfiConverterString.INSTANCE.Read(stream), + Value: FfiConverterOptionalTypeCloudKitValue.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudKitField value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalTypeCloudKitValue.INSTANCE.AllocationSize(value.Value); + } + + public override void Write(CloudKitField value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalTypeCloudKitValue.INSTANCE.Write(value.Value, stream); + } +} + + + +internal record CloudKitRecord ( + string RecordType, + string Name, + byte[]? SystemFields, + long? CreatedMs, + CloudKitField[] Fields +) { +} + +class FfiConverterTypeCloudKitRecord: FfiConverterRustBuffer { + public static FfiConverterTypeCloudKitRecord INSTANCE = new FfiConverterTypeCloudKitRecord(); + + public override CloudKitRecord Read(BigEndianStream stream) { + return new CloudKitRecord( + RecordType: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + SystemFields: FfiConverterOptionalByteArray.INSTANCE.Read(stream), + CreatedMs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Fields: FfiConverterSequenceTypeCloudKitField.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CloudKitRecord value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.RecordType) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterOptionalByteArray.INSTANCE.AllocationSize(value.SystemFields) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.CreatedMs) + + FfiConverterSequenceTypeCloudKitField.INSTANCE.AllocationSize(value.Fields); + } + + public override void Write(CloudKitRecord value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.RecordType, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterOptionalByteArray.INSTANCE.Write(value.SystemFields, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.CreatedMs, stream); + FfiConverterSequenceTypeCloudKitField.INSTANCE.Write(value.Fields, stream); + } +} + + + internal record CloudLibraryPull ( CloudLibraryRecords Base, CloudLibraryRecords Changed, @@ -19637,7 +24439,8 @@ internal record ErrorInfo ( SecretKindTag? Secret, HostKeyFailure? HostKey, TlsFailureTag? TlsFailure, - AiFailureInfo? Ai = null + AiFailureInfo? Ai = null, + SyncFailureInfo? Sync = null ) { } @@ -19654,7 +24457,8 @@ public override ErrorInfo Read(BigEndianStream stream) { Secret: FfiConverterOptionalTypeSecretKindTag.INSTANCE.Read(stream), HostKey: FfiConverterOptionalTypeHostKeyFailure.INSTANCE.Read(stream), TlsFailure: FfiConverterOptionalTypeTlsFailureTag.INSTANCE.Read(stream), - Ai: FfiConverterOptionalTypeAiFailureInfo.INSTANCE.Read(stream) + Ai: FfiConverterOptionalTypeAiFailureInfo.INSTANCE.Read(stream), + Sync: FfiConverterOptionalTypeSyncFailureInfo.INSTANCE.Read(stream) ); } @@ -19668,7 +24472,8 @@ public override int AllocationSize(ErrorInfo value) { + FfiConverterOptionalTypeSecretKindTag.INSTANCE.AllocationSize(value.Secret) + FfiConverterOptionalTypeHostKeyFailure.INSTANCE.AllocationSize(value.HostKey) + FfiConverterOptionalTypeTlsFailureTag.INSTANCE.AllocationSize(value.TlsFailure) - + FfiConverterOptionalTypeAiFailureInfo.INSTANCE.AllocationSize(value.Ai); + + FfiConverterOptionalTypeAiFailureInfo.INSTANCE.AllocationSize(value.Ai) + + FfiConverterOptionalTypeSyncFailureInfo.INSTANCE.AllocationSize(value.Sync); } public override void Write(ErrorInfo value, BigEndianStream stream) { @@ -19681,6 +24486,7 @@ public override void Write(ErrorInfo value, BigEndianStream stream) { FfiConverterOptionalTypeHostKeyFailure.INSTANCE.Write(value.HostKey, stream); FfiConverterOptionalTypeTlsFailureTag.INSTANCE.Write(value.TlsFailure, stream); FfiConverterOptionalTypeAiFailureInfo.INSTANCE.Write(value.Ai, stream); + FfiConverterOptionalTypeSyncFailureInfo.INSTANCE.Write(value.Sync, stream); } } @@ -19916,6 +24722,36 @@ public override void Write(FilterRuleArg value, BigEndianStream stream) { +internal record FingerprintInfo ( + string[] Words, + string Qr +) { +} + +class FfiConverterTypeFingerprintInfo: FfiConverterRustBuffer { + public static FfiConverterTypeFingerprintInfo INSTANCE = new FfiConverterTypeFingerprintInfo(); + + public override FingerprintInfo Read(BigEndianStream stream) { + return new FingerprintInfo( + Words: FfiConverterSequenceString.INSTANCE.Read(stream), + Qr: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(FingerprintInfo value) { + return 0 + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Words) + + FfiConverterString.INSTANCE.AllocationSize(value.Qr); + } + + public override void Write(FingerprintInfo value, BigEndianStream stream) { + FfiConverterSequenceString.INSTANCE.Write(value.Words, stream); + FfiConverterString.INSTANCE.Write(value.Qr, stream); + } +} + + + internal record ForeignAppDirsArg ( string Home, string Config, @@ -20378,6 +25214,78 @@ public override void Write(GroupRecord value, BigEndianStream stream) { +internal record HeldRecordInfo ( + SyncRecordRef Record, + HeldReasonTag Reason +) { +} + +class FfiConverterTypeHeldRecordInfo: FfiConverterRustBuffer { + public static FfiConverterTypeHeldRecordInfo INSTANCE = new FfiConverterTypeHeldRecordInfo(); + + public override HeldRecordInfo Read(BigEndianStream stream) { + return new HeldRecordInfo( + Record: FfiConverterTypeSyncRecordRef.INSTANCE.Read(stream), + Reason: FfiConverterTypeHeldReasonTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(HeldRecordInfo value) { + return 0 + + FfiConverterTypeSyncRecordRef.INSTANCE.AllocationSize(value.Record) + + FfiConverterTypeHeldReasonTag.INSTANCE.AllocationSize(value.Reason); + } + + public override void Write(HeldRecordInfo value, BigEndianStream stream) { + FfiConverterTypeSyncRecordRef.INSTANCE.Write(value.Record, stream); + FfiConverterTypeHeldReasonTag.INSTANCE.Write(value.Reason, stream); + } +} + + + +internal record HeldRestartInfo ( + string Team, + uint Version, + string Signer, + string SignerIk, + FingerprintInfo Words +) { +} + +class FfiConverterTypeHeldRestartInfo: FfiConverterRustBuffer { + public static FfiConverterTypeHeldRestartInfo INSTANCE = new FfiConverterTypeHeldRestartInfo(); + + public override HeldRestartInfo Read(BigEndianStream stream) { + return new HeldRestartInfo( + Team: FfiConverterString.INSTANCE.Read(stream), + Version: FfiConverterUInt32.INSTANCE.Read(stream), + Signer: FfiConverterString.INSTANCE.Read(stream), + SignerIk: FfiConverterString.INSTANCE.Read(stream), + Words: FfiConverterTypeFingerprintInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(HeldRestartInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Team) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Version) + + FfiConverterString.INSTANCE.AllocationSize(value.Signer) + + FfiConverterString.INSTANCE.AllocationSize(value.SignerIk) + + FfiConverterTypeFingerprintInfo.INSTANCE.AllocationSize(value.Words); + } + + public override void Write(HeldRestartInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Team, stream); + FfiConverterUInt32.INSTANCE.Write(value.Version, stream); + FfiConverterString.INSTANCE.Write(value.Signer, stream); + FfiConverterString.INSTANCE.Write(value.SignerIk, stream); + FfiConverterTypeFingerprintInfo.INSTANCE.Write(value.Words, stream); + } +} + + + internal record HistoryCursorArg ( bool Pinned, long ExecutedAtSecs, @@ -20711,6 +25619,74 @@ public override void Write(ImportSummary value, BigEndianStream stream) { +internal record KeyChangeInfo ( + string Account, + FingerprintInfo Pinned, + FingerprintInfo Offered, + string OfferedIk +) { +} + +class FfiConverterTypeKeyChangeInfo: FfiConverterRustBuffer { + public static FfiConverterTypeKeyChangeInfo INSTANCE = new FfiConverterTypeKeyChangeInfo(); + + public override KeyChangeInfo Read(BigEndianStream stream) { + return new KeyChangeInfo( + Account: FfiConverterString.INSTANCE.Read(stream), + Pinned: FfiConverterTypeFingerprintInfo.INSTANCE.Read(stream), + Offered: FfiConverterTypeFingerprintInfo.INSTANCE.Read(stream), + OfferedIk: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(KeyChangeInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Account) + + FfiConverterTypeFingerprintInfo.INSTANCE.AllocationSize(value.Pinned) + + FfiConverterTypeFingerprintInfo.INSTANCE.AllocationSize(value.Offered) + + FfiConverterString.INSTANCE.AllocationSize(value.OfferedIk); + } + + public override void Write(KeyChangeInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Account, stream); + FfiConverterTypeFingerprintInfo.INSTANCE.Write(value.Pinned, stream); + FfiConverterTypeFingerprintInfo.INSTANCE.Write(value.Offered, stream); + FfiConverterString.INSTANCE.Write(value.OfferedIk, stream); + } +} + + + +internal record KeyNoticeInfo ( + string Id, + KeyNoticeKindTag Kind +) { +} + +class FfiConverterTypeKeyNoticeInfo: FfiConverterRustBuffer { + public static FfiConverterTypeKeyNoticeInfo INSTANCE = new FfiConverterTypeKeyNoticeInfo(); + + public override KeyNoticeInfo Read(BigEndianStream stream) { + return new KeyNoticeInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Kind: FfiConverterTypeKeyNoticeKindTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(KeyNoticeInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterTypeKeyNoticeKindTag.INSTANCE.AllocationSize(value.Kind); + } + + public override void Write(KeyNoticeInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterTypeKeyNoticeKindTag.INSTANCE.Write(value.Kind, stream); + } +} + + + internal record KeyWindowInfo ( KeyKindTag Kind, string TypeName, @@ -20845,6 +25821,174 @@ public override void Write(KeymapPresetInfo value, BigEndianStream stream) { +internal record LegacyMetadataArg ( + byte[]? Token, + LegacyRecordArg[] Dirty, + LegacyTombstoneArg[] Tombstones, + string[] DeferredDeletions, + string[] ChangesHeldForUnreadable, + string[] RemovalsPendingForUnreadable, + string[] DeletionsHeldForUnreadable, + string[] OwnersKeptOffSync, + LegacyStandingArg[] Standing, + string[] ReadableRecordTypes, + string? Account, + string? ZoneState, + CloudKitRecord[] Cache +) { +} + +class FfiConverterTypeLegacyMetadataArg: FfiConverterRustBuffer { + public static FfiConverterTypeLegacyMetadataArg INSTANCE = new FfiConverterTypeLegacyMetadataArg(); + + public override LegacyMetadataArg Read(BigEndianStream stream) { + return new LegacyMetadataArg( + Token: FfiConverterOptionalByteArray.INSTANCE.Read(stream), + Dirty: FfiConverterSequenceTypeLegacyRecordArg.INSTANCE.Read(stream), + Tombstones: FfiConverterSequenceTypeLegacyTombstoneArg.INSTANCE.Read(stream), + DeferredDeletions: FfiConverterSequenceString.INSTANCE.Read(stream), + ChangesHeldForUnreadable: FfiConverterSequenceString.INSTANCE.Read(stream), + RemovalsPendingForUnreadable: FfiConverterSequenceString.INSTANCE.Read(stream), + DeletionsHeldForUnreadable: FfiConverterSequenceString.INSTANCE.Read(stream), + OwnersKeptOffSync: FfiConverterSequenceString.INSTANCE.Read(stream), + Standing: FfiConverterSequenceTypeLegacyStandingArg.INSTANCE.Read(stream), + ReadableRecordTypes: FfiConverterSequenceString.INSTANCE.Read(stream), + Account: FfiConverterOptionalString.INSTANCE.Read(stream), + ZoneState: FfiConverterOptionalString.INSTANCE.Read(stream), + Cache: FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LegacyMetadataArg value) { + return 0 + + FfiConverterOptionalByteArray.INSTANCE.AllocationSize(value.Token) + + FfiConverterSequenceTypeLegacyRecordArg.INSTANCE.AllocationSize(value.Dirty) + + FfiConverterSequenceTypeLegacyTombstoneArg.INSTANCE.AllocationSize(value.Tombstones) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.DeferredDeletions) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.ChangesHeldForUnreadable) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.RemovalsPendingForUnreadable) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.DeletionsHeldForUnreadable) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.OwnersKeptOffSync) + + FfiConverterSequenceTypeLegacyStandingArg.INSTANCE.AllocationSize(value.Standing) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.ReadableRecordTypes) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Account) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ZoneState) + + FfiConverterSequenceTypeCloudKitRecord.INSTANCE.AllocationSize(value.Cache); + } + + public override void Write(LegacyMetadataArg value, BigEndianStream stream) { + FfiConverterOptionalByteArray.INSTANCE.Write(value.Token, stream); + FfiConverterSequenceTypeLegacyRecordArg.INSTANCE.Write(value.Dirty, stream); + FfiConverterSequenceTypeLegacyTombstoneArg.INSTANCE.Write(value.Tombstones, stream); + FfiConverterSequenceString.INSTANCE.Write(value.DeferredDeletions, stream); + FfiConverterSequenceString.INSTANCE.Write(value.ChangesHeldForUnreadable, stream); + FfiConverterSequenceString.INSTANCE.Write(value.RemovalsPendingForUnreadable, stream); + FfiConverterSequenceString.INSTANCE.Write(value.DeletionsHeldForUnreadable, stream); + FfiConverterSequenceString.INSTANCE.Write(value.OwnersKeptOffSync, stream); + FfiConverterSequenceTypeLegacyStandingArg.INSTANCE.Write(value.Standing, stream); + FfiConverterSequenceString.INSTANCE.Write(value.ReadableRecordTypes, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Account, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ZoneState, stream); + FfiConverterSequenceTypeCloudKitRecord.INSTANCE.Write(value.Cache, stream); + } +} + + + +internal record LegacyRecordArg ( + string RecordType, + string Id +) { +} + +class FfiConverterTypeLegacyRecordArg: FfiConverterRustBuffer { + public static FfiConverterTypeLegacyRecordArg INSTANCE = new FfiConverterTypeLegacyRecordArg(); + + public override LegacyRecordArg Read(BigEndianStream stream) { + return new LegacyRecordArg( + RecordType: FfiConverterString.INSTANCE.Read(stream), + Id: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LegacyRecordArg value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.RecordType) + + FfiConverterString.INSTANCE.AllocationSize(value.Id); + } + + public override void Write(LegacyRecordArg value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.RecordType, stream); + FfiConverterString.INSTANCE.Write(value.Id, stream); + } +} + + + +internal record LegacyStandingArg ( + string Connection, + LegacyStandingTag Standing +) { +} + +class FfiConverterTypeLegacyStandingArg: FfiConverterRustBuffer { + public static FfiConverterTypeLegacyStandingArg INSTANCE = new FfiConverterTypeLegacyStandingArg(); + + public override LegacyStandingArg Read(BigEndianStream stream) { + return new LegacyStandingArg( + Connection: FfiConverterString.INSTANCE.Read(stream), + Standing: FfiConverterTypeLegacyStandingTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LegacyStandingArg value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Connection) + + FfiConverterTypeLegacyStandingTag.INSTANCE.AllocationSize(value.Standing); + } + + public override void Write(LegacyStandingArg value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Connection, stream); + FfiConverterTypeLegacyStandingTag.INSTANCE.Write(value.Standing, stream); + } +} + + + +internal record LegacyTombstoneArg ( + LegacyRecordArg Record, + long DeletedAtMs, + string? Owner +) { +} + +class FfiConverterTypeLegacyTombstoneArg: FfiConverterRustBuffer { + public static FfiConverterTypeLegacyTombstoneArg INSTANCE = new FfiConverterTypeLegacyTombstoneArg(); + + public override LegacyTombstoneArg Read(BigEndianStream stream) { + return new LegacyTombstoneArg( + Record: FfiConverterTypeLegacyRecordArg.INSTANCE.Read(stream), + DeletedAtMs: FfiConverterInt64.INSTANCE.Read(stream), + Owner: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LegacyTombstoneArg value) { + return 0 + + FfiConverterTypeLegacyRecordArg.INSTANCE.AllocationSize(value.Record) + + FfiConverterInt64.INSTANCE.AllocationSize(value.DeletedAtMs) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Owner); + } + + public override void Write(LegacyTombstoneArg value, BigEndianStream stream) { + FfiConverterTypeLegacyRecordArg.INSTANCE.Write(value.Record, stream); + FfiConverterInt64.INSTANCE.Write(value.DeletedAtMs, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Owner, stream); + } +} + + + internal record LibrarySnapshot ( ConnectionRecord[] Connections, GroupRecord[] Groups, @@ -21127,6 +26271,40 @@ public override void Write(McpWriteRequest value, BigEndianStream stream) { +internal record MemberKeysInfo ( + string Account, + TeamRoleTag Role, + MemberKeyStatusTag Status +) { +} + +class FfiConverterTypeMemberKeysInfo: FfiConverterRustBuffer { + public static FfiConverterTypeMemberKeysInfo INSTANCE = new FfiConverterTypeMemberKeysInfo(); + + public override MemberKeysInfo Read(BigEndianStream stream) { + return new MemberKeysInfo( + Account: FfiConverterString.INSTANCE.Read(stream), + Role: FfiConverterTypeTeamRoleTag.INSTANCE.Read(stream), + Status: FfiConverterTypeMemberKeyStatusTag.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(MemberKeysInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Account) + + FfiConverterTypeTeamRoleTag.INSTANCE.AllocationSize(value.Role) + + FfiConverterTypeMemberKeyStatusTag.INSTANCE.AllocationSize(value.Status); + } + + public override void Write(MemberKeysInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Account, stream); + FfiConverterTypeTeamRoleTag.INSTANCE.Write(value.Role, stream); + FfiConverterTypeMemberKeyStatusTag.INSTANCE.Write(value.Status, stream); + } +} + + + internal record MembershipInfo ( TeamInfo Team, string Role, @@ -21161,6 +26339,66 @@ public override void Write(MembershipInfo value, BigEndianStream stream) { +internal record MoveBackPlanInfo ( + ulong IcloudDeletions +) { +} + +class FfiConverterTypeMoveBackPlanInfo: FfiConverterRustBuffer { + public static FfiConverterTypeMoveBackPlanInfo INSTANCE = new FfiConverterTypeMoveBackPlanInfo(); + + public override MoveBackPlanInfo Read(BigEndianStream stream) { + return new MoveBackPlanInfo( + IcloudDeletions: FfiConverterUInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(MoveBackPlanInfo value) { + return 0 + + FfiConverterUInt64.INSTANCE.AllocationSize(value.IcloudDeletions); + } + + public override void Write(MoveBackPlanInfo value, BigEndianStream stream) { + FfiConverterUInt64.INSTANCE.Write(value.IcloudDeletions, stream); + } +} + + + +internal record MovePlanInfo ( + ulong Records, + ulong StayingBehind, + ulong SecretsToSeal +) { +} + +class FfiConverterTypeMovePlanInfo: FfiConverterRustBuffer { + public static FfiConverterTypeMovePlanInfo INSTANCE = new FfiConverterTypeMovePlanInfo(); + + public override MovePlanInfo Read(BigEndianStream stream) { + return new MovePlanInfo( + Records: FfiConverterUInt64.INSTANCE.Read(stream), + StayingBehind: FfiConverterUInt64.INSTANCE.Read(stream), + SecretsToSeal: FfiConverterUInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(MovePlanInfo value) { + return 0 + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Records) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.StayingBehind) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.SecretsToSeal); + } + + public override void Write(MovePlanInfo value, BigEndianStream stream) { + FfiConverterUInt64.INSTANCE.Write(value.Records, stream); + FfiConverterUInt64.INSTANCE.Write(value.StayingBehind, stream); + FfiConverterUInt64.INSTANCE.Write(value.SecretsToSeal, stream); + } +} + + + /// /// The table a trigger fires on. /// @@ -21305,6 +26543,94 @@ public override void Write(ParsedConnectionUrl value, BigEndianStream stream) { +internal record PendingApprovalInfo ( + SyncRecordRef Record, + string Field, + string Pulled, + string? Current +) { +} + +class FfiConverterTypePendingApprovalInfo: FfiConverterRustBuffer { + public static FfiConverterTypePendingApprovalInfo INSTANCE = new FfiConverterTypePendingApprovalInfo(); + + public override PendingApprovalInfo Read(BigEndianStream stream) { + return new PendingApprovalInfo( + Record: FfiConverterTypeSyncRecordRef.INSTANCE.Read(stream), + Field: FfiConverterString.INSTANCE.Read(stream), + Pulled: FfiConverterString.INSTANCE.Read(stream), + Current: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(PendingApprovalInfo value) { + return 0 + + FfiConverterTypeSyncRecordRef.INSTANCE.AllocationSize(value.Record) + + FfiConverterString.INSTANCE.AllocationSize(value.Field) + + FfiConverterString.INSTANCE.AllocationSize(value.Pulled) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Current); + } + + public override void Write(PendingApprovalInfo value, BigEndianStream stream) { + FfiConverterTypeSyncRecordRef.INSTANCE.Write(value.Record, stream); + FfiConverterString.INSTANCE.Write(value.Field, stream); + FfiConverterString.INSTANCE.Write(value.Pulled, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Current, stream); + } +} + + + +internal record PendingResetInfo ( + string Reset, + ResetKindTag Kind, + ResetStateTag State, + bool Mine, + string? ProposedBy, + long TakenAtUs, + long HeldUntilUs +) { +} + +class FfiConverterTypePendingResetInfo: FfiConverterRustBuffer { + public static FfiConverterTypePendingResetInfo INSTANCE = new FfiConverterTypePendingResetInfo(); + + public override PendingResetInfo Read(BigEndianStream stream) { + return new PendingResetInfo( + Reset: FfiConverterString.INSTANCE.Read(stream), + Kind: FfiConverterTypeResetKindTag.INSTANCE.Read(stream), + State: FfiConverterTypeResetStateTag.INSTANCE.Read(stream), + Mine: FfiConverterBoolean.INSTANCE.Read(stream), + ProposedBy: FfiConverterOptionalString.INSTANCE.Read(stream), + TakenAtUs: FfiConverterInt64.INSTANCE.Read(stream), + HeldUntilUs: FfiConverterInt64.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(PendingResetInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Reset) + + FfiConverterTypeResetKindTag.INSTANCE.AllocationSize(value.Kind) + + FfiConverterTypeResetStateTag.INSTANCE.AllocationSize(value.State) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Mine) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ProposedBy) + + FfiConverterInt64.INSTANCE.AllocationSize(value.TakenAtUs) + + FfiConverterInt64.INSTANCE.AllocationSize(value.HeldUntilUs); + } + + public override void Write(PendingResetInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Reset, stream); + FfiConverterTypeResetKindTag.INSTANCE.Write(value.Kind, stream); + FfiConverterTypeResetStateTag.INSTANCE.Write(value.State, stream); + FfiConverterBoolean.INSTANCE.Write(value.Mine, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ProposedBy, stream); + FfiConverterInt64.INSTANCE.Write(value.TakenAtUs, stream); + FfiConverterInt64.INSTANCE.Write(value.HeldUntilUs, stream); + } +} + + + internal record PersonalDataHitInfo ( SensitiveKindTag Kind, uint Line @@ -21509,6 +26835,74 @@ public override void Write(PromptRequest value, BigEndianStream stream) { +internal record RecoveryKeyDraftInfo ( + string Draft, + SecretString Text, + byte[] Check +) { +} + +class FfiConverterTypeRecoveryKeyDraftInfo: FfiConverterRustBuffer { + public static FfiConverterTypeRecoveryKeyDraftInfo INSTANCE = new FfiConverterTypeRecoveryKeyDraftInfo(); + + public override RecoveryKeyDraftInfo Read(BigEndianStream stream) { + return new RecoveryKeyDraftInfo( + Draft: FfiConverterString.INSTANCE.Read(stream), + Text: FfiConverterTypeSecretString.INSTANCE.Read(stream), + Check: FfiConverterByteArray.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RecoveryKeyDraftInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Draft) + + FfiConverterTypeSecretString.INSTANCE.AllocationSize(value.Text) + + FfiConverterByteArray.INSTANCE.AllocationSize(value.Check); + } + + public override void Write(RecoveryKeyDraftInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Draft, stream); + FfiConverterTypeSecretString.INSTANCE.Write(value.Text, stream); + FfiConverterByteArray.INSTANCE.Write(value.Check, stream); + } +} + + + +internal record RemovalReviewInfo ( + string Review, + ReviewedDeviceInfo[] Devices, + ReviewedMemberInfo[] Members +) { +} + +class FfiConverterTypeRemovalReviewInfo: FfiConverterRustBuffer { + public static FfiConverterTypeRemovalReviewInfo INSTANCE = new FfiConverterTypeRemovalReviewInfo(); + + public override RemovalReviewInfo Read(BigEndianStream stream) { + return new RemovalReviewInfo( + Review: FfiConverterString.INSTANCE.Read(stream), + Devices: FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.Read(stream), + Members: FfiConverterSequenceTypeReviewedMemberInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RemovalReviewInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Review) + + FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.AllocationSize(value.Devices) + + FfiConverterSequenceTypeReviewedMemberInfo.INSTANCE.AllocationSize(value.Members); + } + + public override void Write(RemovalReviewInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Review, stream); + FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.Write(value.Devices, stream); + FfiConverterSequenceTypeReviewedMemberInfo.INSTANCE.Write(value.Members, stream); + } +} + + + internal record ResultColumnInfo ( string Name, string TypeName, @@ -21543,6 +26937,100 @@ public override void Write(ResultColumnInfo value, BigEndianStream stream) { +internal record ReviewedDeviceInfo ( + AccountDeviceInfo Device, + bool KeepByDefault +) { +} + +class FfiConverterTypeReviewedDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterTypeReviewedDeviceInfo INSTANCE = new FfiConverterTypeReviewedDeviceInfo(); + + public override ReviewedDeviceInfo Read(BigEndianStream stream) { + return new ReviewedDeviceInfo( + Device: FfiConverterTypeAccountDeviceInfo.INSTANCE.Read(stream), + KeepByDefault: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ReviewedDeviceInfo value) { + return 0 + + FfiConverterTypeAccountDeviceInfo.INSTANCE.AllocationSize(value.Device) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.KeepByDefault); + } + + public override void Write(ReviewedDeviceInfo value, BigEndianStream stream) { + FfiConverterTypeAccountDeviceInfo.INSTANCE.Write(value.Device, stream); + FfiConverterBoolean.INSTANCE.Write(value.KeepByDefault, stream); + } +} + + + +internal record ReviewedMemberInfo ( + string Team, + string Account, + uint ConfirmedUnderAv +) { +} + +class FfiConverterTypeReviewedMemberInfo: FfiConverterRustBuffer { + public static FfiConverterTypeReviewedMemberInfo INSTANCE = new FfiConverterTypeReviewedMemberInfo(); + + public override ReviewedMemberInfo Read(BigEndianStream stream) { + return new ReviewedMemberInfo( + Team: FfiConverterString.INSTANCE.Read(stream), + Account: FfiConverterString.INSTANCE.Read(stream), + ConfirmedUnderAv: FfiConverterUInt32.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ReviewedMemberInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Team) + + FfiConverterString.INSTANCE.AllocationSize(value.Account) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.ConfirmedUnderAv); + } + + public override void Write(ReviewedMemberInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Team, stream); + FfiConverterString.INSTANCE.Write(value.Account, stream); + FfiConverterUInt32.INSTANCE.Write(value.ConfirmedUnderAv, stream); + } +} + + + +internal record RotationDraftInfo ( + RecoveryKeyDraftInfo Recovery, + ReviewedDeviceInfo[] Devices +) { +} + +class FfiConverterTypeRotationDraftInfo: FfiConverterRustBuffer { + public static FfiConverterTypeRotationDraftInfo INSTANCE = new FfiConverterTypeRotationDraftInfo(); + + public override RotationDraftInfo Read(BigEndianStream stream) { + return new RotationDraftInfo( + Recovery: FfiConverterTypeRecoveryKeyDraftInfo.INSTANCE.Read(stream), + Devices: FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(RotationDraftInfo value) { + return 0 + + FfiConverterTypeRecoveryKeyDraftInfo.INSTANCE.AllocationSize(value.Recovery) + + FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.AllocationSize(value.Devices); + } + + public override void Write(RotationDraftInfo value, BigEndianStream stream) { + FfiConverterTypeRecoveryKeyDraftInfo.INSTANCE.Write(value.Recovery, stream); + FfiConverterSequenceTypeReviewedDeviceInfo.INSTANCE.Write(value.Devices, stream); + } +} + + + internal record RowReferenceChoice ( uint Key, bool Referencing, @@ -22088,6 +27576,36 @@ public override void Write(ServerMessage value, BigEndianStream stream) { +internal record SettingsCategoryArg ( + string Category, + string Document +) { +} + +class FfiConverterTypeSettingsCategoryArg: FfiConverterRustBuffer { + public static FfiConverterTypeSettingsCategoryArg INSTANCE = new FfiConverterTypeSettingsCategoryArg(); + + public override SettingsCategoryArg Read(BigEndianStream stream) { + return new SettingsCategoryArg( + Category: FfiConverterString.INSTANCE.Read(stream), + Document: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SettingsCategoryArg value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Category) + + FfiConverterString.INSTANCE.AllocationSize(value.Document); + } + + public override void Write(SettingsCategoryArg value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Category, stream); + FfiConverterString.INSTANCE.Write(value.Document, stream); + } +} + + + internal record ShareColumnMasking ( string Name, MaskSuggestionInfo? Suggestion @@ -22810,6 +28328,44 @@ public override void Write(StatementSpan value, BigEndianStream stream) { +internal record StoppedDeviceInfo ( + string Account, + string Device, + uint Version, + bool CanReconfirm +) { +} + +class FfiConverterTypeStoppedDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterTypeStoppedDeviceInfo INSTANCE = new FfiConverterTypeStoppedDeviceInfo(); + + public override StoppedDeviceInfo Read(BigEndianStream stream) { + return new StoppedDeviceInfo( + Account: FfiConverterString.INSTANCE.Read(stream), + Device: FfiConverterString.INSTANCE.Read(stream), + Version: FfiConverterUInt32.INSTANCE.Read(stream), + CanReconfirm: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(StoppedDeviceInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Account) + + FfiConverterString.INSTANCE.AllocationSize(value.Device) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Version) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.CanReconfirm); + } + + public override void Write(StoppedDeviceInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Account, stream); + FfiConverterString.INSTANCE.Write(value.Device, stream); + FfiConverterUInt32.INSTANCE.Write(value.Version, stream); + FfiConverterBoolean.INSTANCE.Write(value.CanReconfirm, stream); + } +} + + + internal record StructureColumn ( string Name, string TypeName, @@ -22914,43 +28470,191 @@ public override void Write(StructureForeignKey value, BigEndianStream stream) { -internal record StructureIndex ( - string Name, - string[] Keys, - bool Unique, - bool Primary, - string? Predicate +internal record StructureIndex ( + string Name, + string[] Keys, + bool Unique, + bool Primary, + string? Predicate +) { +} + +class FfiConverterTypeStructureIndex: FfiConverterRustBuffer { + public static FfiConverterTypeStructureIndex INSTANCE = new FfiConverterTypeStructureIndex(); + + public override StructureIndex Read(BigEndianStream stream) { + return new StructureIndex( + Name: FfiConverterString.INSTANCE.Read(stream), + Keys: FfiConverterSequenceString.INSTANCE.Read(stream), + Unique: FfiConverterBoolean.INSTANCE.Read(stream), + Primary: FfiConverterBoolean.INSTANCE.Read(stream), + Predicate: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(StructureIndex value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Keys) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Unique) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Primary) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Predicate); + } + + public override void Write(StructureIndex value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Keys, stream); + FfiConverterBoolean.INSTANCE.Write(value.Unique, stream); + FfiConverterBoolean.INSTANCE.Write(value.Primary, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Predicate, stream); + } +} + + + +internal record SyncCategoriesArg ( + string[] OffKinds, + bool Passwords +) { +} + +class FfiConverterTypeSyncCategoriesArg: FfiConverterRustBuffer { + public static FfiConverterTypeSyncCategoriesArg INSTANCE = new FfiConverterTypeSyncCategoriesArg(); + + public override SyncCategoriesArg Read(BigEndianStream stream) { + return new SyncCategoriesArg( + OffKinds: FfiConverterSequenceString.INSTANCE.Read(stream), + Passwords: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SyncCategoriesArg value) { + return 0 + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.OffKinds) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Passwords); + } + + public override void Write(SyncCategoriesArg value, BigEndianStream stream) { + FfiConverterSequenceString.INSTANCE.Write(value.OffKinds, stream); + FfiConverterBoolean.INSTANCE.Write(value.Passwords, stream); + } +} + + + +internal record SyncConfig ( + SyncPlatformTag Platform, + SyncCategoriesArg Categories +) { +} + +class FfiConverterTypeSyncConfig: FfiConverterRustBuffer { + public static FfiConverterTypeSyncConfig INSTANCE = new FfiConverterTypeSyncConfig(); + + public override SyncConfig Read(BigEndianStream stream) { + return new SyncConfig( + Platform: FfiConverterTypeSyncPlatformTag.INSTANCE.Read(stream), + Categories: FfiConverterTypeSyncCategoriesArg.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SyncConfig value) { + return 0 + + FfiConverterTypeSyncPlatformTag.INSTANCE.AllocationSize(value.Platform) + + FfiConverterTypeSyncCategoriesArg.INSTANCE.AllocationSize(value.Categories); + } + + public override void Write(SyncConfig value, BigEndianStream stream) { + FfiConverterTypeSyncPlatformTag.INSTANCE.Write(value.Platform, stream); + FfiConverterTypeSyncCategoriesArg.INSTANCE.Write(value.Categories, stream); + } +} + + + +internal record SyncRecordRef ( + string Scope, + string Kind, + string RecordId +) { +} + +class FfiConverterTypeSyncRecordRef: FfiConverterRustBuffer { + public static FfiConverterTypeSyncRecordRef INSTANCE = new FfiConverterTypeSyncRecordRef(); + + public override SyncRecordRef Read(BigEndianStream stream) { + return new SyncRecordRef( + Scope: FfiConverterString.INSTANCE.Read(stream), + Kind: FfiConverterString.INSTANCE.Read(stream), + RecordId: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SyncRecordRef value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Scope) + + FfiConverterString.INSTANCE.AllocationSize(value.Kind) + + FfiConverterString.INSTANCE.AllocationSize(value.RecordId); + } + + public override void Write(SyncRecordRef value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Scope, stream); + FfiConverterString.INSTANCE.Write(value.Kind, stream); + FfiConverterString.INSTANCE.Write(value.RecordId, stream); + } +} + + + +internal record SyncStatusInfo ( + SyncProviderTag? Provider, + SyncPhaseTag Phase, + long? LastPassMs, + string? Problem, + uint WaitingApprovals, + uint Conflicts, + uint Held, + uint QueuedChanges ) { } -class FfiConverterTypeStructureIndex: FfiConverterRustBuffer { - public static FfiConverterTypeStructureIndex INSTANCE = new FfiConverterTypeStructureIndex(); +class FfiConverterTypeSyncStatusInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSyncStatusInfo INSTANCE = new FfiConverterTypeSyncStatusInfo(); - public override StructureIndex Read(BigEndianStream stream) { - return new StructureIndex( - Name: FfiConverterString.INSTANCE.Read(stream), - Keys: FfiConverterSequenceString.INSTANCE.Read(stream), - Unique: FfiConverterBoolean.INSTANCE.Read(stream), - Primary: FfiConverterBoolean.INSTANCE.Read(stream), - Predicate: FfiConverterOptionalString.INSTANCE.Read(stream) + public override SyncStatusInfo Read(BigEndianStream stream) { + return new SyncStatusInfo( + Provider: FfiConverterOptionalTypeSyncProviderTag.INSTANCE.Read(stream), + Phase: FfiConverterTypeSyncPhaseTag.INSTANCE.Read(stream), + LastPassMs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Problem: FfiConverterOptionalString.INSTANCE.Read(stream), + WaitingApprovals: FfiConverterUInt32.INSTANCE.Read(stream), + Conflicts: FfiConverterUInt32.INSTANCE.Read(stream), + Held: FfiConverterUInt32.INSTANCE.Read(stream), + QueuedChanges: FfiConverterUInt32.INSTANCE.Read(stream) ); } - public override int AllocationSize(StructureIndex value) { + public override int AllocationSize(SyncStatusInfo value) { return 0 - + FfiConverterString.INSTANCE.AllocationSize(value.Name) - + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Keys) - + FfiConverterBoolean.INSTANCE.AllocationSize(value.Unique) - + FfiConverterBoolean.INSTANCE.AllocationSize(value.Primary) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Predicate); + + FfiConverterOptionalTypeSyncProviderTag.INSTANCE.AllocationSize(value.Provider) + + FfiConverterTypeSyncPhaseTag.INSTANCE.AllocationSize(value.Phase) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.LastPassMs) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Problem) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.WaitingApprovals) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Conflicts) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Held) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.QueuedChanges); } - public override void Write(StructureIndex value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.Name, stream); - FfiConverterSequenceString.INSTANCE.Write(value.Keys, stream); - FfiConverterBoolean.INSTANCE.Write(value.Unique, stream); - FfiConverterBoolean.INSTANCE.Write(value.Primary, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Predicate, stream); + public override void Write(SyncStatusInfo value, BigEndianStream stream) { + FfiConverterOptionalTypeSyncProviderTag.INSTANCE.Write(value.Provider, stream); + FfiConverterTypeSyncPhaseTag.INSTANCE.Write(value.Phase, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.LastPassMs, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Problem, stream); + FfiConverterUInt32.INSTANCE.Write(value.WaitingApprovals, stream); + FfiConverterUInt32.INSTANCE.Write(value.Conflicts, stream); + FfiConverterUInt32.INSTANCE.Write(value.Held, stream); + FfiConverterUInt32.INSTANCE.Write(value.QueuedChanges, stream); } } @@ -23252,6 +28956,44 @@ public override void Write(TagRecord value, BigEndianStream stream) { +internal record TeamConflictInfo ( + SyncRecordRef Record, + string[] Fields, + string? Mine, + string? Theirs +) { +} + +class FfiConverterTypeTeamConflictInfo: FfiConverterRustBuffer { + public static FfiConverterTypeTeamConflictInfo INSTANCE = new FfiConverterTypeTeamConflictInfo(); + + public override TeamConflictInfo Read(BigEndianStream stream) { + return new TeamConflictInfo( + Record: FfiConverterTypeSyncRecordRef.INSTANCE.Read(stream), + Fields: FfiConverterSequenceString.INSTANCE.Read(stream), + Mine: FfiConverterOptionalString.INSTANCE.Read(stream), + Theirs: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TeamConflictInfo value) { + return 0 + + FfiConverterTypeSyncRecordRef.INSTANCE.AllocationSize(value.Record) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Fields) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Mine) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Theirs); + } + + public override void Write(TeamConflictInfo value, BigEndianStream stream) { + FfiConverterTypeSyncRecordRef.INSTANCE.Write(value.Record, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Fields, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Mine, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Theirs, stream); + } +} + + + internal record TeamInfo ( string Id, string Name @@ -23282,6 +29024,60 @@ public override void Write(TeamInfo value, BigEndianStream stream) { +internal record TeamKeysInfo ( + string Team, + uint? Version, + KeyVersionStateTag State, + StopCauseTag? StoppedCause, + bool RotationDue, + bool Holder, + MemberKeysInfo[] Members, + StoppedDeviceInfo[] Stopped +) { +} + +class FfiConverterTypeTeamKeysInfo: FfiConverterRustBuffer { + public static FfiConverterTypeTeamKeysInfo INSTANCE = new FfiConverterTypeTeamKeysInfo(); + + public override TeamKeysInfo Read(BigEndianStream stream) { + return new TeamKeysInfo( + Team: FfiConverterString.INSTANCE.Read(stream), + Version: FfiConverterOptionalUInt32.INSTANCE.Read(stream), + State: FfiConverterTypeKeyVersionStateTag.INSTANCE.Read(stream), + StoppedCause: FfiConverterOptionalTypeStopCauseTag.INSTANCE.Read(stream), + RotationDue: FfiConverterBoolean.INSTANCE.Read(stream), + Holder: FfiConverterBoolean.INSTANCE.Read(stream), + Members: FfiConverterSequenceTypeMemberKeysInfo.INSTANCE.Read(stream), + Stopped: FfiConverterSequenceTypeStoppedDeviceInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TeamKeysInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Team) + + FfiConverterOptionalUInt32.INSTANCE.AllocationSize(value.Version) + + FfiConverterTypeKeyVersionStateTag.INSTANCE.AllocationSize(value.State) + + FfiConverterOptionalTypeStopCauseTag.INSTANCE.AllocationSize(value.StoppedCause) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.RotationDue) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Holder) + + FfiConverterSequenceTypeMemberKeysInfo.INSTANCE.AllocationSize(value.Members) + + FfiConverterSequenceTypeStoppedDeviceInfo.INSTANCE.AllocationSize(value.Stopped); + } + + public override void Write(TeamKeysInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Team, stream); + FfiConverterOptionalUInt32.INSTANCE.Write(value.Version, stream); + FfiConverterTypeKeyVersionStateTag.INSTANCE.Write(value.State, stream); + FfiConverterOptionalTypeStopCauseTag.INSTANCE.Write(value.StoppedCause, stream); + FfiConverterBoolean.INSTANCE.Write(value.RotationDue, stream); + FfiConverterBoolean.INSTANCE.Write(value.Holder, stream); + FfiConverterSequenceTypeMemberKeysInfo.INSTANCE.Write(value.Members, stream); + FfiConverterSequenceTypeStoppedDeviceInfo.INSTANCE.Write(value.Stopped, stream); + } +} + + + internal record TlsSettings ( TlsModeTag Mode, string? CaFile, @@ -23784,99 +29580,635 @@ public record OpenSettings ( string? Pane ) : AppLinkInfo {} - public record StartMcpServer: AppLinkInfo {} + public record StartMcpServer: AppLinkInfo {} + + + + +} + +class FfiConverterTypeAppLinkInfo : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeAppLinkInfo(); + + public override AppLinkInfo Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new AppLinkInfo.OpenConnection( + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new AppLinkInfo.OpenTable( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterOptionalString.INSTANCE.Read(stream), + FfiConverterOptionalString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 3: + return new AppLinkInfo.OpenQuery( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new AppLinkInfo.OpenSettings( + FfiConverterOptionalString.INSTANCE.Read(stream) + ); + case 5: + return new AppLinkInfo.StartMcpServer( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.Read()", value)); + } + } + + public override int AllocationSize(AppLinkInfo value) { + switch (value) { + case AppLinkInfo.OpenConnection variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId); + case AppLinkInfo.OpenTable variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId) + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Database) + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Schema) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Table); + case AppLinkInfo.OpenQuery variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Sql); + case AppLinkInfo.OpenSettings variant_value: + return 4 + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Pane); + case AppLinkInfo.StartMcpServer variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.AllocationSize()", value)); + } + } + + public override void Write(AppLinkInfo value, BigEndianStream stream) { + switch (value) { + case AppLinkInfo.OpenConnection variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); + break; + case AppLinkInfo.OpenTable variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Database, stream); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Schema, stream); + FfiConverterString.INSTANCE.Write(variant_value.Table, stream); + break; + case AppLinkInfo.OpenQuery variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); + FfiConverterString.INSTANCE.Write(variant_value.Sql, stream); + break; + case AppLinkInfo.OpenSettings variant_value: + stream.WriteInt(4); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Pane, stream); + break; + case AppLinkInfo.StartMcpServer variant_value: + stream.WriteInt(5); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.Write()", value)); + } + } +} + + + + + + + +internal record CatalogChangeOutcome { + + public record Done: CatalogChangeOutcome {} + + + public record Failed ( + BoxedErrorInfo Error + ) : CatalogChangeOutcome {} + + public record Unknown ( + BoxedErrorInfo Error + ) : CatalogChangeOutcome {} + + + +} + +class FfiConverterTypeCatalogChangeOutcome : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCatalogChangeOutcome(); + + public override CatalogChangeOutcome Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CatalogChangeOutcome.Done( + ); + case 2: + return new CatalogChangeOutcome.Failed( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) + ); + case 3: + return new CatalogChangeOutcome.Unknown( + FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.Read()", value)); + } + } + + public override int AllocationSize(CatalogChangeOutcome value) { + switch (value) { + case CatalogChangeOutcome.Done variant_value: + return 4; + case CatalogChangeOutcome.Failed variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); + case CatalogChangeOutcome.Unknown variant_value: + return 4 + + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.AllocationSize()", value)); + } + } + + public override void Write(CatalogChangeOutcome value, BigEndianStream stream) { + switch (value) { + case CatalogChangeOutcome.Done variant_value: + stream.WriteInt(1); + break; + case CatalogChangeOutcome.Failed variant_value: + stream.WriteInt(2); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + break; + case CatalogChangeOutcome.Unknown variant_value: + stream.WriteInt(3); + FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.Write()", value)); + } + } +} + + + + + + + +internal record CatalogOperation { + + public record TruncateTable ( + TableName Table, + bool Cascade, + bool RestartIdentity, + string? Cluster + ) : CatalogOperation {} + + public record DropTable ( + TableName Table, + bool Cascade + ) : CatalogOperation {} + + public record CreateSchema ( + string Name, + string? Owner + ) : CatalogOperation {} + + public record DropSchema ( + string Name, + bool Cascade + ) : CatalogOperation {} + + public record CreateDatabase ( + DatabaseDraftArg Draft + ) : CatalogOperation {} + + public record DropDatabase ( + string Name, + bool Force, + string? Cluster + ) : CatalogOperation {} + + + +} + +class FfiConverterTypeCatalogOperation : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCatalogOperation(); + + public override CatalogOperation Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CatalogOperation.TruncateTable( + FfiConverterTypeTableName.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream), + FfiConverterOptionalString.INSTANCE.Read(stream) + ); + case 2: + return new CatalogOperation.DropTable( + FfiConverterTypeTableName.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream) + ); + case 3: + return new CatalogOperation.CreateSchema( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterOptionalString.INSTANCE.Read(stream) + ); + case 4: + return new CatalogOperation.DropSchema( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream) + ); + case 5: + return new CatalogOperation.CreateDatabase( + FfiConverterTypeDatabaseDraftArg.INSTANCE.Read(stream) + ); + case 6: + return new CatalogOperation.DropDatabase( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterBoolean.INSTANCE.Read(stream), + FfiConverterOptionalString.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.Read()", value)); + } + } + + public override int AllocationSize(CatalogOperation value) { + switch (value) { + case CatalogOperation.TruncateTable variant_value: + return 4 + + FfiConverterTypeTableName.INSTANCE.AllocationSize(variant_value.Table) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.RestartIdentity) + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Cluster); + case CatalogOperation.DropTable variant_value: + return 4 + + FfiConverterTypeTableName.INSTANCE.AllocationSize(variant_value.Table) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade); + case CatalogOperation.CreateSchema variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Owner); + case CatalogOperation.DropSchema variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade); + case CatalogOperation.CreateDatabase variant_value: + return 4 + + FfiConverterTypeDatabaseDraftArg.INSTANCE.AllocationSize(variant_value.Draft); + case CatalogOperation.DropDatabase variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) + + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Force) + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Cluster); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.AllocationSize()", value)); + } + } + + public override void Write(CatalogOperation value, BigEndianStream stream) { + switch (value) { + case CatalogOperation.TruncateTable variant_value: + stream.WriteInt(1); + FfiConverterTypeTableName.INSTANCE.Write(variant_value.Table, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.RestartIdentity, stream); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Cluster, stream); + break; + case CatalogOperation.DropTable variant_value: + stream.WriteInt(2); + FfiConverterTypeTableName.INSTANCE.Write(variant_value.Table, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); + break; + case CatalogOperation.CreateSchema variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Owner, stream); + break; + case CatalogOperation.DropSchema variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); + break; + case CatalogOperation.CreateDatabase variant_value: + stream.WriteInt(5); + FfiConverterTypeDatabaseDraftArg.INSTANCE.Write(variant_value.Draft, stream); + break; + case CatalogOperation.DropDatabase variant_value: + stream.WriteInt(6); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); + FfiConverterBoolean.INSTANCE.Write(variant_value.Force, stream); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Cluster, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.Write()", value)); + } + } +} + + + + + + + +internal record CellEdit { + + public record Text ( + string TextValue + ) : CellEdit {} + + public record Null: CellEdit {} + + + public record Default: CellEdit {} + + + + +} + +class FfiConverterTypeCellEdit : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCellEdit(); + + public override CellEdit Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new CellEdit.Text( + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new CellEdit.Null( + ); + case 3: + return new CellEdit.Default( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Read()", value)); + } + } + + public override int AllocationSize(CellEdit value) { + switch (value) { + case CellEdit.Text variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.TextValue); + case CellEdit.Null variant_value: + return 4; + case CellEdit.Default variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.AllocationSize()", value)); + } + } + + public override void Write(CellEdit value, BigEndianStream stream) { + switch (value) { + case CellEdit.Text variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.TextValue, stream); + break; + case CellEdit.Null variant_value: + stream.WriteInt(2); + break; + case CellEdit.Default variant_value: + stream.WriteInt(3); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Write()", value)); + } + } +} + + + + + + + +internal class CloudKitFailure: UniffiException { + CloudKitFailure() : base() {} + CloudKitFailure(String @Message) : base(@Message) {} + + // Each variant is a nested class + + public class NoAccount : CloudKitFailure { + public NoAccount() : base() {} + } + + + public class Restricted : CloudKitFailure { + public Restricted() : base() {} + } + + + public class AccountTemporarilyUnavailable : CloudKitFailure { + public AccountTemporarilyUnavailable() : base() {} + } + + + public class AccountChanged : CloudKitFailure { + public AccountChanged() : base() {} + } + + + public class TokenExpired : CloudKitFailure { + public TokenExpired() : base() {} + } + + + public class ZoneNotFound : CloudKitFailure { + public ZoneNotFound() : base() {} + } + + + public class ZoneDeletedByUser : CloudKitFailure { + public ZoneDeletedByUser() : base() {} + } + + + public class LimitExceeded : CloudKitFailure { + public LimitExceeded() : base() {} + } + + + public class QuotaExceeded : CloudKitFailure { + public QuotaExceeded() : base() {} + } + + + public class Network : CloudKitFailure { + public Network() : base() {} + } + + + + public class Throttled : CloudKitFailure { + // Members + public ulong? @retryAfterMs; + + // Constructor + public Throttled( + ulong? @retryAfterMs) : base( + "@retryAfterMs" + "=" + @retryAfterMs) { + + this.@retryAfterMs = @retryAfterMs; + } + } + + public class Other : CloudKitFailure { + // Members + public long @code; + + // Constructor + public Other( + long @code) : base( + "@code" + "=" + @code) { + + this.@code = @code; + } + } } -class FfiConverterTypeAppLinkInfo : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeAppLinkInfo(); +class FfiConverterTypeCloudKitFailure : FfiConverterRustBuffer, CallStatusErrorHandler { + public static FfiConverterTypeCloudKitFailure INSTANCE = new FfiConverterTypeCloudKitFailure(); - public override AppLinkInfo Read(BigEndianStream stream) { + public override CloudKitFailure Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new AppLinkInfo.OpenConnection( - FfiConverterString.INSTANCE.Read(stream) - ); + return new CloudKitFailure.NoAccount(); case 2: - return new AppLinkInfo.OpenTable( - FfiConverterString.INSTANCE.Read(stream), - FfiConverterOptionalString.INSTANCE.Read(stream), - FfiConverterOptionalString.INSTANCE.Read(stream), - FfiConverterString.INSTANCE.Read(stream) - ); + return new CloudKitFailure.Restricted(); case 3: - return new AppLinkInfo.OpenQuery( - FfiConverterString.INSTANCE.Read(stream), - FfiConverterString.INSTANCE.Read(stream) - ); + return new CloudKitFailure.AccountTemporarilyUnavailable(); case 4: - return new AppLinkInfo.OpenSettings( - FfiConverterOptionalString.INSTANCE.Read(stream) - ); + return new CloudKitFailure.AccountChanged(); case 5: - return new AppLinkInfo.StartMcpServer( - ); + return new CloudKitFailure.TokenExpired(); + case 6: + return new CloudKitFailure.ZoneNotFound(); + case 7: + return new CloudKitFailure.ZoneDeletedByUser(); + case 8: + return new CloudKitFailure.LimitExceeded(); + case 9: + return new CloudKitFailure.QuotaExceeded(); + case 10: + return new CloudKitFailure.Network(); + case 11: + return new CloudKitFailure.Throttled( + FfiConverterOptionalUInt64.INSTANCE.Read(stream)); + case 12: + return new CloudKitFailure.Other( + FfiConverterInt64.INSTANCE.Read(stream)); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.Read()", value)); + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCloudKitFailure.Read()", value)); } } - public override int AllocationSize(AppLinkInfo value) { + public override int AllocationSize(CloudKitFailure value) { switch (value) { - case AppLinkInfo.OpenConnection variant_value: - return 4 - + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId); - case AppLinkInfo.OpenTable variant_value: - return 4 - + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId) - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Database) - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Schema) - + FfiConverterString.INSTANCE.AllocationSize(variant_value.Table); - case AppLinkInfo.OpenQuery variant_value: + + case CloudKitFailure.NoAccount variant_value: + return 4; + + case CloudKitFailure.Restricted variant_value: + return 4; + + case CloudKitFailure.AccountTemporarilyUnavailable variant_value: + return 4; + + case CloudKitFailure.AccountChanged variant_value: + return 4; + + case CloudKitFailure.TokenExpired variant_value: + return 4; + + case CloudKitFailure.ZoneNotFound variant_value: + return 4; + + case CloudKitFailure.ZoneDeletedByUser variant_value: + return 4; + + case CloudKitFailure.LimitExceeded variant_value: + return 4; + + case CloudKitFailure.QuotaExceeded variant_value: + return 4; + + case CloudKitFailure.Network variant_value: + return 4; + + case CloudKitFailure.Throttled variant_value: return 4 - + FfiConverterString.INSTANCE.AllocationSize(variant_value.ConnectionId) - + FfiConverterString.INSTANCE.AllocationSize(variant_value.Sql); - case AppLinkInfo.OpenSettings variant_value: + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(variant_value.@retryAfterMs); + + case CloudKitFailure.Other variant_value: return 4 - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Pane); - case AppLinkInfo.StartMcpServer variant_value: - return 4; + + FfiConverterInt64.INSTANCE.AllocationSize(variant_value.@code); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.AllocationSize()", value)); + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCloudKitFailure.AllocationSize()", value)); } } - public override void Write(AppLinkInfo value, BigEndianStream stream) { + public override void Write(CloudKitFailure value, BigEndianStream stream) { switch (value) { - case AppLinkInfo.OpenConnection variant_value: + case CloudKitFailure.NoAccount variant_value: stream.WriteInt(1); - FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); break; - case AppLinkInfo.OpenTable variant_value: + case CloudKitFailure.Restricted variant_value: stream.WriteInt(2); - FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Database, stream); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Schema, stream); - FfiConverterString.INSTANCE.Write(variant_value.Table, stream); break; - case AppLinkInfo.OpenQuery variant_value: + case CloudKitFailure.AccountTemporarilyUnavailable variant_value: stream.WriteInt(3); - FfiConverterString.INSTANCE.Write(variant_value.ConnectionId, stream); - FfiConverterString.INSTANCE.Write(variant_value.Sql, stream); break; - case AppLinkInfo.OpenSettings variant_value: + case CloudKitFailure.AccountChanged variant_value: stream.WriteInt(4); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Pane, stream); break; - case AppLinkInfo.StartMcpServer variant_value: + case CloudKitFailure.TokenExpired variant_value: stream.WriteInt(5); break; + case CloudKitFailure.ZoneNotFound variant_value: + stream.WriteInt(6); + break; + case CloudKitFailure.ZoneDeletedByUser variant_value: + stream.WriteInt(7); + break; + case CloudKitFailure.LimitExceeded variant_value: + stream.WriteInt(8); + break; + case CloudKitFailure.QuotaExceeded variant_value: + stream.WriteInt(9); + break; + case CloudKitFailure.Network variant_value: + stream.WriteInt(10); + break; + case CloudKitFailure.Throttled variant_value: + stream.WriteInt(11); + FfiConverterOptionalUInt64.INSTANCE.Write(variant_value.@retryAfterMs, stream); + break; + case CloudKitFailure.Other variant_value: + stream.WriteInt(12); + FfiConverterInt64.INSTANCE.Write(variant_value.@code, stream); + break; default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppLinkInfo.Write()", value)); + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeCloudKitFailure.Write()", value)); } } } @@ -23885,77 +30217,87 @@ public override void Write(AppLinkInfo value, BigEndianStream stream) { - - -internal record CatalogChangeOutcome { +internal record CloudKitFetched { - public record Done: CatalogChangeOutcome {} + public record Found ( + CloudKitRecord Record + ) : CloudKitFetched {} + public record Missing ( + string Name + ) : CloudKitFetched {} public record Failed ( - BoxedErrorInfo Error - ) : CatalogChangeOutcome {} - - public record Unknown ( - BoxedErrorInfo Error - ) : CatalogChangeOutcome {} + string Name, + long Code, + ulong? RetryAfterMs + ) : CloudKitFetched {} } -class FfiConverterTypeCatalogChangeOutcome : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCatalogChangeOutcome(); +class FfiConverterTypeCloudKitFetched : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCloudKitFetched(); - public override CatalogChangeOutcome Read(BigEndianStream stream) { + public override CloudKitFetched Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new CatalogChangeOutcome.Done( + return new CloudKitFetched.Found( + FfiConverterTypeCloudKitRecord.INSTANCE.Read(stream) ); case 2: - return new CatalogChangeOutcome.Failed( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) + return new CloudKitFetched.Missing( + FfiConverterString.INSTANCE.Read(stream) ); case 3: - return new CatalogChangeOutcome.Unknown( - FfiConverterTypeBoxedErrorInfo.INSTANCE.Read(stream) + return new CloudKitFetched.Failed( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterInt64.INSTANCE.Read(stream), + FfiConverterOptionalUInt64.INSTANCE.Read(stream) ); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.Read()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitFetched.Read()", value)); } } - public override int AllocationSize(CatalogChangeOutcome value) { + public override int AllocationSize(CloudKitFetched value) { switch (value) { - case CatalogChangeOutcome.Done variant_value: - return 4; - case CatalogChangeOutcome.Failed variant_value: + case CloudKitFetched.Found variant_value: return 4 - + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); - case CatalogChangeOutcome.Unknown variant_value: + + FfiConverterTypeCloudKitRecord.INSTANCE.AllocationSize(variant_value.Record); + case CloudKitFetched.Missing variant_value: return 4 - + FfiConverterTypeBoxedErrorInfo.INSTANCE.AllocationSize(variant_value.Error); + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name); + case CloudKitFetched.Failed variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) + + FfiConverterInt64.INSTANCE.AllocationSize(variant_value.Code) + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(variant_value.RetryAfterMs); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.AllocationSize()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitFetched.AllocationSize()", value)); } } - public override void Write(CatalogChangeOutcome value, BigEndianStream stream) { + public override void Write(CloudKitFetched value, BigEndianStream stream) { switch (value) { - case CatalogChangeOutcome.Done variant_value: + case CloudKitFetched.Found variant_value: stream.WriteInt(1); + FfiConverterTypeCloudKitRecord.INSTANCE.Write(variant_value.Record, stream); break; - case CatalogChangeOutcome.Failed variant_value: + case CloudKitFetched.Missing variant_value: stream.WriteInt(2); - FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); break; - case CatalogChangeOutcome.Unknown variant_value: + case CloudKitFetched.Failed variant_value: stream.WriteInt(3); - FfiConverterTypeBoxedErrorInfo.INSTANCE.Write(variant_value.Error, stream); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); + FfiConverterInt64.INSTANCE.Write(variant_value.Code, stream); + FfiConverterOptionalUInt64.INSTANCE.Write(variant_value.RetryAfterMs, stream); break; default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogChangeOutcome.Write()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitFetched.Write()", value)); } } } @@ -23966,156 +30308,125 @@ public override void Write(CatalogChangeOutcome value, BigEndianStream stream) { -internal record CatalogOperation { - - public record TruncateTable ( - TableName Table, - bool Cascade, - bool RestartIdentity, - string? Cluster - ) : CatalogOperation {} +internal record CloudKitOutcome { - public record DropTable ( - TableName Table, - bool Cascade - ) : CatalogOperation {} - - public record CreateSchema ( + public record Saved ( string Name, - string? Owner - ) : CatalogOperation {} + byte[] SystemFields + ) : CloudKitOutcome {} - public record DropSchema ( + public record Deleted ( + string Name + ) : CloudKitOutcome {} + + public record ServerChanged ( string Name, - bool Cascade - ) : CatalogOperation {} + CloudKitRecord? Server + ) : CloudKitOutcome {} - public record CreateDatabase ( - DatabaseDraftArg Draft - ) : CatalogOperation {} + public record UnknownItem ( + string Name + ) : CloudKitOutcome {} - public record DropDatabase ( + public record Failed ( string Name, - bool Force, - string? Cluster - ) : CatalogOperation {} + long Code, + ulong? RetryAfterMs + ) : CloudKitOutcome {} } -class FfiConverterTypeCatalogOperation : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCatalogOperation(); +class FfiConverterTypeCloudKitOutcome : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCloudKitOutcome(); - public override CatalogOperation Read(BigEndianStream stream) { + public override CloudKitOutcome Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new CatalogOperation.TruncateTable( - FfiConverterTypeTableName.INSTANCE.Read(stream), - FfiConverterBoolean.INSTANCE.Read(stream), - FfiConverterBoolean.INSTANCE.Read(stream), - FfiConverterOptionalString.INSTANCE.Read(stream) + return new CloudKitOutcome.Saved( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterByteArray.INSTANCE.Read(stream) ); case 2: - return new CatalogOperation.DropTable( - FfiConverterTypeTableName.INSTANCE.Read(stream), - FfiConverterBoolean.INSTANCE.Read(stream) + return new CloudKitOutcome.Deleted( + FfiConverterString.INSTANCE.Read(stream) ); case 3: - return new CatalogOperation.CreateSchema( + return new CloudKitOutcome.ServerChanged( FfiConverterString.INSTANCE.Read(stream), - FfiConverterOptionalString.INSTANCE.Read(stream) + FfiConverterOptionalTypeCloudKitRecord.INSTANCE.Read(stream) ); case 4: - return new CatalogOperation.DropSchema( - FfiConverterString.INSTANCE.Read(stream), - FfiConverterBoolean.INSTANCE.Read(stream) + return new CloudKitOutcome.UnknownItem( + FfiConverterString.INSTANCE.Read(stream) ); case 5: - return new CatalogOperation.CreateDatabase( - FfiConverterTypeDatabaseDraftArg.INSTANCE.Read(stream) - ); - case 6: - return new CatalogOperation.DropDatabase( + return new CloudKitOutcome.Failed( FfiConverterString.INSTANCE.Read(stream), - FfiConverterBoolean.INSTANCE.Read(stream), - FfiConverterOptionalString.INSTANCE.Read(stream) + FfiConverterInt64.INSTANCE.Read(stream), + FfiConverterOptionalUInt64.INSTANCE.Read(stream) ); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.Read()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitOutcome.Read()", value)); } } - public override int AllocationSize(CatalogOperation value) { + public override int AllocationSize(CloudKitOutcome value) { switch (value) { - case CatalogOperation.TruncateTable variant_value: - return 4 - + FfiConverterTypeTableName.INSTANCE.AllocationSize(variant_value.Table) - + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade) - + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.RestartIdentity) - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Cluster); - case CatalogOperation.DropTable variant_value: - return 4 - + FfiConverterTypeTableName.INSTANCE.AllocationSize(variant_value.Table) - + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade); - case CatalogOperation.CreateSchema variant_value: + case CloudKitOutcome.Saved variant_value: return 4 + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Owner); - case CatalogOperation.DropSchema variant_value: + + FfiConverterByteArray.INSTANCE.AllocationSize(variant_value.SystemFields); + case CloudKitOutcome.Deleted variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name); + case CloudKitOutcome.ServerChanged variant_value: return 4 + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) - + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Cascade); - case CatalogOperation.CreateDatabase variant_value: + + FfiConverterOptionalTypeCloudKitRecord.INSTANCE.AllocationSize(variant_value.Server); + case CloudKitOutcome.UnknownItem variant_value: return 4 - + FfiConverterTypeDatabaseDraftArg.INSTANCE.AllocationSize(variant_value.Draft); - case CatalogOperation.DropDatabase variant_value: + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name); + case CloudKitOutcome.Failed variant_value: return 4 + FfiConverterString.INSTANCE.AllocationSize(variant_value.Name) - + FfiConverterBoolean.INSTANCE.AllocationSize(variant_value.Force) - + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Cluster); + + FfiConverterInt64.INSTANCE.AllocationSize(variant_value.Code) + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(variant_value.RetryAfterMs); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.AllocationSize()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitOutcome.AllocationSize()", value)); } } - public override void Write(CatalogOperation value, BigEndianStream stream) { + public override void Write(CloudKitOutcome value, BigEndianStream stream) { switch (value) { - case CatalogOperation.TruncateTable variant_value: + case CloudKitOutcome.Saved variant_value: stream.WriteInt(1); - FfiConverterTypeTableName.INSTANCE.Write(variant_value.Table, stream); - FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); - FfiConverterBoolean.INSTANCE.Write(variant_value.RestartIdentity, stream); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Cluster, stream); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); + FfiConverterByteArray.INSTANCE.Write(variant_value.SystemFields, stream); break; - case CatalogOperation.DropTable variant_value: + case CloudKitOutcome.Deleted variant_value: stream.WriteInt(2); - FfiConverterTypeTableName.INSTANCE.Write(variant_value.Table, stream); - FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); + FfiConverterString.INSTANCE.Write(variant_value.Name, stream); break; - case CatalogOperation.CreateSchema variant_value: + case CloudKitOutcome.ServerChanged variant_value: stream.WriteInt(3); FfiConverterString.INSTANCE.Write(variant_value.Name, stream); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Owner, stream); + FfiConverterOptionalTypeCloudKitRecord.INSTANCE.Write(variant_value.Server, stream); break; - case CatalogOperation.DropSchema variant_value: + case CloudKitOutcome.UnknownItem variant_value: stream.WriteInt(4); FfiConverterString.INSTANCE.Write(variant_value.Name, stream); - FfiConverterBoolean.INSTANCE.Write(variant_value.Cascade, stream); break; - case CatalogOperation.CreateDatabase variant_value: + case CloudKitOutcome.Failed variant_value: stream.WriteInt(5); - FfiConverterTypeDatabaseDraftArg.INSTANCE.Write(variant_value.Draft, stream); - break; - case CatalogOperation.DropDatabase variant_value: - stream.WriteInt(6); FfiConverterString.INSTANCE.Write(variant_value.Name, stream); - FfiConverterBoolean.INSTANCE.Write(variant_value.Force, stream); - FfiConverterOptionalString.INSTANCE.Write(variant_value.Cluster, stream); + FfiConverterInt64.INSTANCE.Write(variant_value.Code, stream); + FfiConverterOptionalUInt64.INSTANCE.Write(variant_value.RetryAfterMs, stream); break; default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCatalogOperation.Write()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitOutcome.Write()", value)); } } } @@ -24126,71 +30437,124 @@ public override void Write(CatalogOperation value, BigEndianStream stream) { -internal record CellEdit { +internal record CloudKitValue { public record Text ( - string TextValue - ) : CellEdit {} + string Value + ) : CloudKitValue {} - public record Null: CellEdit {} + public record Int64 ( + long Value + ) : CloudKitValue {} + public record Double ( + double Value + ) : CloudKitValue {} - public record Default: CellEdit {} + public record Timestamp ( + long Value + ) : CloudKitValue {} + public record Bytes ( + byte[] Value + ) : CloudKitValue {} + + public record TextList ( + string[] Value + ) : CloudKitValue {} } -class FfiConverterTypeCellEdit : FfiConverterRustBuffer{ - public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCellEdit(); +class FfiConverterTypeCloudKitValue : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeCloudKitValue(); - public override CellEdit Read(BigEndianStream stream) { + public override CloudKitValue Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { case 1: - return new CellEdit.Text( + return new CloudKitValue.Text( FfiConverterString.INSTANCE.Read(stream) ); case 2: - return new CellEdit.Null( + return new CloudKitValue.Int64( + FfiConverterInt64.INSTANCE.Read(stream) ); case 3: - return new CellEdit.Default( + return new CloudKitValue.Double( + FfiConverterDouble.INSTANCE.Read(stream) + ); + case 4: + return new CloudKitValue.Timestamp( + FfiConverterInt64.INSTANCE.Read(stream) + ); + case 5: + return new CloudKitValue.Bytes( + FfiConverterByteArray.INSTANCE.Read(stream) + ); + case 6: + return new CloudKitValue.TextList( + FfiConverterSequenceString.INSTANCE.Read(stream) ); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Read()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitValue.Read()", value)); } } - public override int AllocationSize(CellEdit value) { + public override int AllocationSize(CloudKitValue value) { switch (value) { - case CellEdit.Text variant_value: + case CloudKitValue.Text variant_value: return 4 - + FfiConverterString.INSTANCE.AllocationSize(variant_value.TextValue); - case CellEdit.Null variant_value: - return 4; - case CellEdit.Default variant_value: - return 4; + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Value); + case CloudKitValue.Int64 variant_value: + return 4 + + FfiConverterInt64.INSTANCE.AllocationSize(variant_value.Value); + case CloudKitValue.Double variant_value: + return 4 + + FfiConverterDouble.INSTANCE.AllocationSize(variant_value.Value); + case CloudKitValue.Timestamp variant_value: + return 4 + + FfiConverterInt64.INSTANCE.AllocationSize(variant_value.Value); + case CloudKitValue.Bytes variant_value: + return 4 + + FfiConverterByteArray.INSTANCE.AllocationSize(variant_value.Value); + case CloudKitValue.TextList variant_value: + return 4 + + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.Value); default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.AllocationSize()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitValue.AllocationSize()", value)); } } - public override void Write(CellEdit value, BigEndianStream stream) { + public override void Write(CloudKitValue value, BigEndianStream stream) { switch (value) { - case CellEdit.Text variant_value: + case CloudKitValue.Text variant_value: stream.WriteInt(1); - FfiConverterString.INSTANCE.Write(variant_value.TextValue, stream); + FfiConverterString.INSTANCE.Write(variant_value.Value, stream); break; - case CellEdit.Null variant_value: + case CloudKitValue.Int64 variant_value: stream.WriteInt(2); + FfiConverterInt64.INSTANCE.Write(variant_value.Value, stream); break; - case CellEdit.Default variant_value: + case CloudKitValue.Double variant_value: stream.WriteInt(3); + FfiConverterDouble.INSTANCE.Write(variant_value.Value, stream); + break; + case CloudKitValue.Timestamp variant_value: + stream.WriteInt(4); + FfiConverterInt64.INSTANCE.Write(variant_value.Value, stream); + break; + case CloudKitValue.Bytes variant_value: + stream.WriteInt(5); + FfiConverterByteArray.INSTANCE.Write(variant_value.Value, stream); + break; + case CloudKitValue.TextList variant_value: + stream.WriteInt(6); + FfiConverterSequenceString.INSTANCE.Write(variant_value.Value, stream); break; default: - throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCellEdit.Write()", value)); + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeCloudKitValue.Write()", value)); } } } @@ -24360,6 +30724,42 @@ public override void Write(CompletionKindTag value, BigEndianStream stream) { +internal enum ConflictChoiceTag: int { + KeepMine, + KeepTheirs +} + +class FfiConverterTypeConflictChoiceTag: FfiConverterRustBuffer { + public static FfiConverterTypeConflictChoiceTag INSTANCE = new FfiConverterTypeConflictChoiceTag(); + + public override ConflictChoiceTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ConflictChoiceTag.KeepMine; + case 2: return ConflictChoiceTag.KeepTheirs; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeConflictChoiceTag.Read()", value)); + } + } + + public override int AllocationSize(ConflictChoiceTag value) { + return 4; + } + + public override void Write(ConflictChoiceTag value, BigEndianStream stream) { + switch (value) { + case ConflictChoiceTag.KeepMine: stream.WriteInt(1); break; + case ConflictChoiceTag.KeepTheirs: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeConflictChoiceTag.Write()", value)); + } + } +} + + + + + + + /// /// Why a call produced no value. A cancel is its own variant, so a /// binding can turn it into its language's cancellation. @@ -25020,6 +31420,202 @@ public override void Write(DatabaseLayoutTag value, BigEndianStream stream) { +internal enum DeviceItemClassTag: int { + Keys, + Anchor +} + +class FfiConverterTypeDeviceItemClassTag: FfiConverterRustBuffer { + public static FfiConverterTypeDeviceItemClassTag INSTANCE = new FfiConverterTypeDeviceItemClassTag(); + + public override DeviceItemClassTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return DeviceItemClassTag.Keys; + case 2: return DeviceItemClassTag.Anchor; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDeviceItemClassTag.Read()", value)); + } + } + + public override int AllocationSize(DeviceItemClassTag value) { + return 4; + } + + public override void Write(DeviceItemClassTag value, BigEndianStream stream) { + switch (value) { + case DeviceItemClassTag.Keys: stream.WriteInt(1); break; + case DeviceItemClassTag.Anchor: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDeviceItemClassTag.Write()", value)); + } + } +} + + + + + + + +internal record DeviceItemTag { + + public record DeviceKeys ( + string Origin, + string Account, + string DeviceRow + ) : DeviceItemTag {} + + public record AccountKeys ( + string Origin, + string Account, + uint Av + ) : DeviceItemTag {} + + public record ResetKeys ( + string Origin, + string Account, + string Reset + ) : DeviceItemTag {} + + public record StateMacKey ( + string State + ) : DeviceItemTag {} + + public record AnchorRoot ( + string State + ) : DeviceItemTag {} + + public record AnchorCheckpoint ( + string State, + string Checkpoint, + uint Part + ) : DeviceItemTag {} + + + +} + +class FfiConverterTypeDeviceItemTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeDeviceItemTag(); + + public override DeviceItemTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new DeviceItemTag.DeviceKeys( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new DeviceItemTag.AccountKeys( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream), + FfiConverterUInt32.INSTANCE.Read(stream) + ); + case 3: + return new DeviceItemTag.ResetKeys( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new DeviceItemTag.StateMacKey( + FfiConverterString.INSTANCE.Read(stream) + ); + case 5: + return new DeviceItemTag.AnchorRoot( + FfiConverterString.INSTANCE.Read(stream) + ); + case 6: + return new DeviceItemTag.AnchorCheckpoint( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream), + FfiConverterUInt32.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDeviceItemTag.Read()", value)); + } + } + + public override int AllocationSize(DeviceItemTag value) { + switch (value) { + case DeviceItemTag.DeviceKeys variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Origin) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Account) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.DeviceRow); + case DeviceItemTag.AccountKeys variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Origin) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Account) + + FfiConverterUInt32.INSTANCE.AllocationSize(variant_value.Av); + case DeviceItemTag.ResetKeys variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Origin) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Account) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Reset); + case DeviceItemTag.StateMacKey variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.State); + case DeviceItemTag.AnchorRoot variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.State); + case DeviceItemTag.AnchorCheckpoint variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.State) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Checkpoint) + + FfiConverterUInt32.INSTANCE.AllocationSize(variant_value.Part); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDeviceItemTag.AllocationSize()", value)); + } + } + + public override void Write(DeviceItemTag value, BigEndianStream stream) { + switch (value) { + case DeviceItemTag.DeviceKeys variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.Origin, stream); + FfiConverterString.INSTANCE.Write(variant_value.Account, stream); + FfiConverterString.INSTANCE.Write(variant_value.DeviceRow, stream); + break; + case DeviceItemTag.AccountKeys variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.Origin, stream); + FfiConverterString.INSTANCE.Write(variant_value.Account, stream); + FfiConverterUInt32.INSTANCE.Write(variant_value.Av, stream); + break; + case DeviceItemTag.ResetKeys variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Origin, stream); + FfiConverterString.INSTANCE.Write(variant_value.Account, stream); + FfiConverterString.INSTANCE.Write(variant_value.Reset, stream); + break; + case DeviceItemTag.StateMacKey variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.State, stream); + break; + case DeviceItemTag.AnchorRoot variant_value: + stream.WriteInt(5); + FfiConverterString.INSTANCE.Write(variant_value.State, stream); + break; + case DeviceItemTag.AnchorCheckpoint variant_value: + stream.WriteInt(6); + FfiConverterString.INSTANCE.Write(variant_value.State, stream); + FfiConverterString.INSTANCE.Write(variant_value.Checkpoint, stream); + FfiConverterUInt32.INSTANCE.Write(variant_value.Part, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeDeviceItemTag.Write()", value)); + } + } +} + + + + + + + internal record EditLock { public record ReadOnlyConnection: EditLock {} @@ -25945,6 +32541,128 @@ public override void Write(ForeignSslModeTag value, BigEndianStream stream) { +internal enum GenesisOutcomeTag: int { + Created, + AnotherDeviceWon +} + +class FfiConverterTypeGenesisOutcomeTag: FfiConverterRustBuffer { + public static FfiConverterTypeGenesisOutcomeTag INSTANCE = new FfiConverterTypeGenesisOutcomeTag(); + + public override GenesisOutcomeTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return GenesisOutcomeTag.Created; + case 2: return GenesisOutcomeTag.AnotherDeviceWon; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeGenesisOutcomeTag.Read()", value)); + } + } + + public override int AllocationSize(GenesisOutcomeTag value) { + return 4; + } + + public override void Write(GenesisOutcomeTag value, BigEndianStream stream) { + switch (value) { + case GenesisOutcomeTag.Created: stream.WriteInt(1); break; + case GenesisOutcomeTag.AnotherDeviceWon: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeGenesisOutcomeTag.Write()", value)); + } + } +} + + + + + + + +internal record HeldReasonTag { + + public record Unreadable: HeldReasonTag {} + + + public record UnknownKind: HeldReasonTag {} + + + public record AwaitingApproval: HeldReasonTag {} + + + public record Refused ( + string Code + ) : HeldReasonTag {} + + + +} + +class FfiConverterTypeHeldReasonTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeHeldReasonTag(); + + public override HeldReasonTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new HeldReasonTag.Unreadable( + ); + case 2: + return new HeldReasonTag.UnknownKind( + ); + case 3: + return new HeldReasonTag.AwaitingApproval( + ); + case 4: + return new HeldReasonTag.Refused( + FfiConverterString.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHeldReasonTag.Read()", value)); + } + } + + public override int AllocationSize(HeldReasonTag value) { + switch (value) { + case HeldReasonTag.Unreadable variant_value: + return 4; + case HeldReasonTag.UnknownKind variant_value: + return 4; + case HeldReasonTag.AwaitingApproval variant_value: + return 4; + case HeldReasonTag.Refused variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Code); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHeldReasonTag.AllocationSize()", value)); + } + } + + public override void Write(HeldReasonTag value, BigEndianStream stream) { + switch (value) { + case HeldReasonTag.Unreadable variant_value: + stream.WriteInt(1); + break; + case HeldReasonTag.UnknownKind variant_value: + stream.WriteInt(2); + break; + case HeldReasonTag.AwaitingApproval variant_value: + stream.WriteInt(3); + break; + case HeldReasonTag.Refused variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Code, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeHeldReasonTag.Write()", value)); + } + } +} + + + + + + + internal enum HistoryExportFormat: int { Sql, Csv @@ -26301,6 +33019,356 @@ public override void Write(KeyKindTag value, BigEndianStream stream) { +internal record KeyNoticeKindTag { + + public record RecoveryKeyReplaced ( + string Account + ) : KeyNoticeKindTag {} + + public record KeysChanged ( + string Account + ) : KeyNoticeKindTag {} + + public record TeamKeyRestarted ( + string Team + ) : KeyNoticeKindTag {} + + public record RestartHeld ( + string Team, + string Signer + ) : KeyNoticeKindTag {} + + public record ResetPending ( + string Reset + ) : KeyNoticeKindTag {} + + public record ResetEnded ( + string Reset, + ResetStateTag State + ) : KeyNoticeKindTag {} + + public record DeviceRemoved ( + string Device + ) : KeyNoticeKindTag {} + + public record SupersededWrap ( + string Team + ) : KeyNoticeKindTag {} + + public record Conflict ( + string Scope + ) : KeyNoticeKindTag {} + + public record ScopeStopped ( + string Scope, + StopCauseTag Cause + ) : KeyNoticeKindTag {} + + public record ScopeEnded ( + string Scope + ) : KeyNoticeKindTag {} + + public record Locked ( + LockCauseTag Cause + ) : KeyNoticeKindTag {} + + + +} + +class FfiConverterTypeKeyNoticeKindTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeKeyNoticeKindTag(); + + public override KeyNoticeKindTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new KeyNoticeKindTag.RecoveryKeyReplaced( + FfiConverterString.INSTANCE.Read(stream) + ); + case 2: + return new KeyNoticeKindTag.KeysChanged( + FfiConverterString.INSTANCE.Read(stream) + ); + case 3: + return new KeyNoticeKindTag.TeamKeyRestarted( + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new KeyNoticeKindTag.RestartHeld( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 5: + return new KeyNoticeKindTag.ResetPending( + FfiConverterString.INSTANCE.Read(stream) + ); + case 6: + return new KeyNoticeKindTag.ResetEnded( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterTypeResetStateTag.INSTANCE.Read(stream) + ); + case 7: + return new KeyNoticeKindTag.DeviceRemoved( + FfiConverterString.INSTANCE.Read(stream) + ); + case 8: + return new KeyNoticeKindTag.SupersededWrap( + FfiConverterString.INSTANCE.Read(stream) + ); + case 9: + return new KeyNoticeKindTag.Conflict( + FfiConverterString.INSTANCE.Read(stream) + ); + case 10: + return new KeyNoticeKindTag.ScopeStopped( + FfiConverterString.INSTANCE.Read(stream), + FfiConverterTypeStopCauseTag.INSTANCE.Read(stream) + ); + case 11: + return new KeyNoticeKindTag.ScopeEnded( + FfiConverterString.INSTANCE.Read(stream) + ); + case 12: + return new KeyNoticeKindTag.Locked( + FfiConverterTypeLockCauseTag.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyNoticeKindTag.Read()", value)); + } + } + + public override int AllocationSize(KeyNoticeKindTag value) { + switch (value) { + case KeyNoticeKindTag.RecoveryKeyReplaced variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Account); + case KeyNoticeKindTag.KeysChanged variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Account); + case KeyNoticeKindTag.TeamKeyRestarted variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Team); + case KeyNoticeKindTag.RestartHeld variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Team) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Signer); + case KeyNoticeKindTag.ResetPending variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Reset); + case KeyNoticeKindTag.ResetEnded variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Reset) + + FfiConverterTypeResetStateTag.INSTANCE.AllocationSize(variant_value.State); + case KeyNoticeKindTag.DeviceRemoved variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Device); + case KeyNoticeKindTag.SupersededWrap variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Team); + case KeyNoticeKindTag.Conflict variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Scope); + case KeyNoticeKindTag.ScopeStopped variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Scope) + + FfiConverterTypeStopCauseTag.INSTANCE.AllocationSize(variant_value.Cause); + case KeyNoticeKindTag.ScopeEnded variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Scope); + case KeyNoticeKindTag.Locked variant_value: + return 4 + + FfiConverterTypeLockCauseTag.INSTANCE.AllocationSize(variant_value.Cause); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyNoticeKindTag.AllocationSize()", value)); + } + } + + public override void Write(KeyNoticeKindTag value, BigEndianStream stream) { + switch (value) { + case KeyNoticeKindTag.RecoveryKeyReplaced variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.Account, stream); + break; + case KeyNoticeKindTag.KeysChanged variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.Account, stream); + break; + case KeyNoticeKindTag.TeamKeyRestarted variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Team, stream); + break; + case KeyNoticeKindTag.RestartHeld variant_value: + stream.WriteInt(4); + FfiConverterString.INSTANCE.Write(variant_value.Team, stream); + FfiConverterString.INSTANCE.Write(variant_value.Signer, stream); + break; + case KeyNoticeKindTag.ResetPending variant_value: + stream.WriteInt(5); + FfiConverterString.INSTANCE.Write(variant_value.Reset, stream); + break; + case KeyNoticeKindTag.ResetEnded variant_value: + stream.WriteInt(6); + FfiConverterString.INSTANCE.Write(variant_value.Reset, stream); + FfiConverterTypeResetStateTag.INSTANCE.Write(variant_value.State, stream); + break; + case KeyNoticeKindTag.DeviceRemoved variant_value: + stream.WriteInt(7); + FfiConverterString.INSTANCE.Write(variant_value.Device, stream); + break; + case KeyNoticeKindTag.SupersededWrap variant_value: + stream.WriteInt(8); + FfiConverterString.INSTANCE.Write(variant_value.Team, stream); + break; + case KeyNoticeKindTag.Conflict variant_value: + stream.WriteInt(9); + FfiConverterString.INSTANCE.Write(variant_value.Scope, stream); + break; + case KeyNoticeKindTag.ScopeStopped variant_value: + stream.WriteInt(10); + FfiConverterString.INSTANCE.Write(variant_value.Scope, stream); + FfiConverterTypeStopCauseTag.INSTANCE.Write(variant_value.Cause, stream); + break; + case KeyNoticeKindTag.ScopeEnded variant_value: + stream.WriteInt(11); + FfiConverterString.INSTANCE.Write(variant_value.Scope, stream); + break; + case KeyNoticeKindTag.Locked variant_value: + stream.WriteInt(12); + FfiConverterTypeLockCauseTag.INSTANCE.Write(variant_value.Cause, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyNoticeKindTag.Write()", value)); + } + } +} + + + + + + + +internal record KeyStateInfo { + + public record NoDeviceStore: KeyStateInfo {} + + + public record Unknown: KeyStateInfo {} + + + public record NoKeys: KeyStateInfo {} + + + public record NeedsApproval ( + string? Request + ) : KeyStateInfo {} + + public record Approved ( + uint Av, + string KeyDevice + ) : KeyStateInfo {} + + public record Locked ( + LockCauseTag Cause + ) : KeyStateInfo {} + + + +} + +class FfiConverterTypeKeyStateInfo : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeKeyStateInfo(); + + public override KeyStateInfo Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new KeyStateInfo.NoDeviceStore( + ); + case 2: + return new KeyStateInfo.Unknown( + ); + case 3: + return new KeyStateInfo.NoKeys( + ); + case 4: + return new KeyStateInfo.NeedsApproval( + FfiConverterOptionalString.INSTANCE.Read(stream) + ); + case 5: + return new KeyStateInfo.Approved( + FfiConverterUInt32.INSTANCE.Read(stream), + FfiConverterString.INSTANCE.Read(stream) + ); + case 6: + return new KeyStateInfo.Locked( + FfiConverterTypeLockCauseTag.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyStateInfo.Read()", value)); + } + } + + public override int AllocationSize(KeyStateInfo value) { + switch (value) { + case KeyStateInfo.NoDeviceStore variant_value: + return 4; + case KeyStateInfo.Unknown variant_value: + return 4; + case KeyStateInfo.NoKeys variant_value: + return 4; + case KeyStateInfo.NeedsApproval variant_value: + return 4 + + FfiConverterOptionalString.INSTANCE.AllocationSize(variant_value.Request); + case KeyStateInfo.Approved variant_value: + return 4 + + FfiConverterUInt32.INSTANCE.AllocationSize(variant_value.Av) + + FfiConverterString.INSTANCE.AllocationSize(variant_value.KeyDevice); + case KeyStateInfo.Locked variant_value: + return 4 + + FfiConverterTypeLockCauseTag.INSTANCE.AllocationSize(variant_value.Cause); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyStateInfo.AllocationSize()", value)); + } + } + + public override void Write(KeyStateInfo value, BigEndianStream stream) { + switch (value) { + case KeyStateInfo.NoDeviceStore variant_value: + stream.WriteInt(1); + break; + case KeyStateInfo.Unknown variant_value: + stream.WriteInt(2); + break; + case KeyStateInfo.NoKeys variant_value: + stream.WriteInt(3); + break; + case KeyStateInfo.NeedsApproval variant_value: + stream.WriteInt(4); + FfiConverterOptionalString.INSTANCE.Write(variant_value.Request, stream); + break; + case KeyStateInfo.Approved variant_value: + stream.WriteInt(5); + FfiConverterUInt32.INSTANCE.Write(variant_value.Av, stream); + FfiConverterString.INSTANCE.Write(variant_value.KeyDevice, stream); + break; + case KeyStateInfo.Locked variant_value: + stream.WriteInt(6); + FfiConverterTypeLockCauseTag.INSTANCE.Write(variant_value.Cause, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyStateInfo.Write()", value)); + } + } +} + + + + + + + internal record KeyTtlTag { public record Persistent: KeyTtlTag {} @@ -26376,6 +33444,45 @@ public override void Write(KeyTtlTag value, BigEndianStream stream) { +internal enum KeyVersionStateTag: int { + Ok, + Stopped, + Ended +} + +class FfiConverterTypeKeyVersionStateTag: FfiConverterRustBuffer { + public static FfiConverterTypeKeyVersionStateTag INSTANCE = new FfiConverterTypeKeyVersionStateTag(); + + public override KeyVersionStateTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return KeyVersionStateTag.Ok; + case 2: return KeyVersionStateTag.Stopped; + case 3: return KeyVersionStateTag.Ended; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyVersionStateTag.Read()", value)); + } + } + + public override int AllocationSize(KeyVersionStateTag value) { + return 4; + } + + public override void Write(KeyVersionStateTag value, BigEndianStream stream) { + switch (value) { + case KeyVersionStateTag.Ok: stream.WriteInt(1); break; + case KeyVersionStateTag.Stopped: stream.WriteInt(2); break; + case KeyVersionStateTag.Ended: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeKeyVersionStateTag.Write()", value)); + } + } +} + + + + + + + internal enum KeymapPlatformTag: int { MacOs, Linux, @@ -26415,6 +33522,45 @@ public override void Write(KeymapPlatformTag value, BigEndianStream stream) { +internal enum LegacyStandingTag: int { + Syncs, + LocalOnly, + Unknown +} + +class FfiConverterTypeLegacyStandingTag: FfiConverterRustBuffer { + public static FfiConverterTypeLegacyStandingTag INSTANCE = new FfiConverterTypeLegacyStandingTag(); + + public override LegacyStandingTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return LegacyStandingTag.Syncs; + case 2: return LegacyStandingTag.LocalOnly; + case 3: return LegacyStandingTag.Unknown; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeLegacyStandingTag.Read()", value)); + } + } + + public override int AllocationSize(LegacyStandingTag value) { + return 4; + } + + public override void Write(LegacyStandingTag value, BigEndianStream stream) { + switch (value) { + case LegacyStandingTag.Syncs: stream.WriteInt(1); break; + case LegacyStandingTag.LocalOnly: stream.WriteInt(2); break; + case LegacyStandingTag.Unknown: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeLegacyStandingTag.Write()", value)); + } + } +} + + + + + + + internal enum LicenseStateTag: int { Active, Grace, @@ -26526,6 +33672,54 @@ public override void Write(LocalPasswordSourceRecord value, BigEndianStream stre +internal enum LockCauseTag: int { + DeviceRemoved, + LeftOutOfRotation, + OwnAccountReset, + AccountEnded, + Unanchored, + PersonalStopped +} + +class FfiConverterTypeLockCauseTag: FfiConverterRustBuffer { + public static FfiConverterTypeLockCauseTag INSTANCE = new FfiConverterTypeLockCauseTag(); + + public override LockCauseTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return LockCauseTag.DeviceRemoved; + case 2: return LockCauseTag.LeftOutOfRotation; + case 3: return LockCauseTag.OwnAccountReset; + case 4: return LockCauseTag.AccountEnded; + case 5: return LockCauseTag.Unanchored; + case 6: return LockCauseTag.PersonalStopped; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeLockCauseTag.Read()", value)); + } + } + + public override int AllocationSize(LockCauseTag value) { + return 4; + } + + public override void Write(LockCauseTag value, BigEndianStream stream) { + switch (value) { + case LockCauseTag.DeviceRemoved: stream.WriteInt(1); break; + case LockCauseTag.LeftOutOfRotation: stream.WriteInt(2); break; + case LockCauseTag.OwnAccountReset: stream.WriteInt(3); break; + case LockCauseTag.AccountEnded: stream.WriteInt(4); break; + case LockCauseTag.Unanchored: stream.WriteInt(5); break; + case LockCauseTag.PersonalStopped: stream.WriteInt(6); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeLockCauseTag.Write()", value)); + } + } +} + + + + + + + internal record ManagedPolicyArg { public record Read ( @@ -26801,6 +33995,84 @@ public override void Write(McpStatusTag value, BigEndianStream stream) { +internal enum MemberKeyStatusTag: int { + NoKeys, + AwaitingConfirmation, + Holder, + Alert +} + +class FfiConverterTypeMemberKeyStatusTag: FfiConverterRustBuffer { + public static FfiConverterTypeMemberKeyStatusTag INSTANCE = new FfiConverterTypeMemberKeyStatusTag(); + + public override MemberKeyStatusTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return MemberKeyStatusTag.NoKeys; + case 2: return MemberKeyStatusTag.AwaitingConfirmation; + case 3: return MemberKeyStatusTag.Holder; + case 4: return MemberKeyStatusTag.Alert; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeMemberKeyStatusTag.Read()", value)); + } + } + + public override int AllocationSize(MemberKeyStatusTag value) { + return 4; + } + + public override void Write(MemberKeyStatusTag value, BigEndianStream stream) { + switch (value) { + case MemberKeyStatusTag.NoKeys: stream.WriteInt(1); break; + case MemberKeyStatusTag.AwaitingConfirmation: stream.WriteInt(2); break; + case MemberKeyStatusTag.Holder: stream.WriteInt(3); break; + case MemberKeyStatusTag.Alert: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeMemberKeyStatusTag.Write()", value)); + } + } +} + + + + + + + +internal enum NewIdentityChoiceTag: int { + MoveMyData, + StartEmpty +} + +class FfiConverterTypeNewIdentityChoiceTag: FfiConverterRustBuffer { + public static FfiConverterTypeNewIdentityChoiceTag INSTANCE = new FfiConverterTypeNewIdentityChoiceTag(); + + public override NewIdentityChoiceTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return NewIdentityChoiceTag.MoveMyData; + case 2: return NewIdentityChoiceTag.StartEmpty; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeNewIdentityChoiceTag.Read()", value)); + } + } + + public override int AllocationSize(NewIdentityChoiceTag value) { + return 4; + } + + public override void Write(NewIdentityChoiceTag value, BigEndianStream stream) { + switch (value) { + case NewIdentityChoiceTag.MoveMyData: stream.WriteInt(1); break; + case NewIdentityChoiceTag.StartEmpty: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeNewIdentityChoiceTag.Write()", value)); + } + } +} + + + + + + + internal enum ObjectKindTag: int { Table, PartitionedTable, @@ -26948,6 +34220,57 @@ public override void Write(ObjectScopeArg value, BigEndianStream stream) { +internal enum PassReasonTag: int { + Journal, + AccountChanged, + Launch, + Foreground, + NetworkBack, + CloudKitPush, + Person +} + +class FfiConverterTypePassReasonTag: FfiConverterRustBuffer { + public static FfiConverterTypePassReasonTag INSTANCE = new FfiConverterTypePassReasonTag(); + + public override PassReasonTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return PassReasonTag.Journal; + case 2: return PassReasonTag.AccountChanged; + case 3: return PassReasonTag.Launch; + case 4: return PassReasonTag.Foreground; + case 5: return PassReasonTag.NetworkBack; + case 6: return PassReasonTag.CloudKitPush; + case 7: return PassReasonTag.Person; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePassReasonTag.Read()", value)); + } + } + + public override int AllocationSize(PassReasonTag value) { + return 4; + } + + public override void Write(PassReasonTag value, BigEndianStream stream) { + switch (value) { + case PassReasonTag.Journal: stream.WriteInt(1); break; + case PassReasonTag.AccountChanged: stream.WriteInt(2); break; + case PassReasonTag.Launch: stream.WriteInt(3); break; + case PassReasonTag.Foreground: stream.WriteInt(4); break; + case PassReasonTag.NetworkBack: stream.WriteInt(5); break; + case PassReasonTag.CloudKitPush: stream.WriteInt(6); break; + case PassReasonTag.Person: stream.WriteInt(7); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypePassReasonTag.Write()", value)); + } + } +} + + + + + + + internal enum PasswordOfferTag: int { DecryptedWhileReading, PasswordFile, @@ -27580,6 +34903,84 @@ public override void Write(ReplicationArg value, BigEndianStream stream) { +internal enum ResetKindTag: int { + KeepScopeKeys, + StartEmpty +} + +class FfiConverterTypeResetKindTag: FfiConverterRustBuffer { + public static FfiConverterTypeResetKindTag INSTANCE = new FfiConverterTypeResetKindTag(); + + public override ResetKindTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ResetKindTag.KeepScopeKeys; + case 2: return ResetKindTag.StartEmpty; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResetKindTag.Read()", value)); + } + } + + public override int AllocationSize(ResetKindTag value) { + return 4; + } + + public override void Write(ResetKindTag value, BigEndianStream stream) { + switch (value) { + case ResetKindTag.KeepScopeKeys: stream.WriteInt(1); break; + case ResetKindTag.StartEmpty: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResetKindTag.Write()", value)); + } + } +} + + + + + + + +internal enum ResetStateTag: int { + Pending, + Cancelled, + Superseded, + Active +} + +class FfiConverterTypeResetStateTag: FfiConverterRustBuffer { + public static FfiConverterTypeResetStateTag INSTANCE = new FfiConverterTypeResetStateTag(); + + public override ResetStateTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ResetStateTag.Pending; + case 2: return ResetStateTag.Cancelled; + case 3: return ResetStateTag.Superseded; + case 4: return ResetStateTag.Active; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResetStateTag.Read()", value)); + } + } + + public override int AllocationSize(ResetStateTag value) { + return 4; + } + + public override void Write(ResetStateTag value, BigEndianStream stream) { + switch (value) { + case ResetStateTag.Pending: stream.WriteInt(1); break; + case ResetStateTag.Cancelled: stream.WriteInt(2); break; + case ResetStateTag.Superseded: stream.WriteInt(3); break; + case ResetStateTag.Active: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeResetStateTag.Write()", value)); + } + } +} + + + + + + + internal record ResolutionTag { public record Add: ResolutionTag {} @@ -29046,6 +36447,45 @@ public override void Write(ServerNameOverrideTag value, BigEndianStream stream) +internal enum SessionEndTag: int { + User, + Mismatch, + Commitment +} + +class FfiConverterTypeSessionEndTag: FfiConverterRustBuffer { + public static FfiConverterTypeSessionEndTag INSTANCE = new FfiConverterTypeSessionEndTag(); + + public override SessionEndTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SessionEndTag.User; + case 2: return SessionEndTag.Mismatch; + case 3: return SessionEndTag.Commitment; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionEndTag.Read()", value)); + } + } + + public override int AllocationSize(SessionEndTag value) { + return 4; + } + + public override void Write(SessionEndTag value, BigEndianStream stream) { + switch (value) { + case SessionEndTag.User: stream.WriteInt(1); break; + case SessionEndTag.Mismatch: stream.WriteInt(2); break; + case SessionEndTag.Commitment: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionEndTag.Write()", value)); + } + } +} + + + + + + + internal record SessionHealthTag { public record Online: SessionHealthTag {} @@ -29140,6 +36580,176 @@ public override void Write(SessionHealthTag value, BigEndianStream stream) { +internal record SessionPhaseTag { + + public record Open: SessionPhaseTag {} + + + public record Chosen: SessionPhaseTag {} + + + public record Compare ( + string[] Words + ) : SessionPhaseTag {} + + public record Confirmed: SessionPhaseTag {} + + + public record Approved: SessionPhaseTag {} + + + public record TakenElsewhere: SessionPhaseTag {} + + + public record Cancelled ( + SessionEndTag Reason + ) : SessionPhaseTag {} + + public record Expired: SessionPhaseTag {} + + + + +} + +class FfiConverterTypeSessionPhaseTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeSessionPhaseTag(); + + public override SessionPhaseTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new SessionPhaseTag.Open( + ); + case 2: + return new SessionPhaseTag.Chosen( + ); + case 3: + return new SessionPhaseTag.Compare( + FfiConverterSequenceString.INSTANCE.Read(stream) + ); + case 4: + return new SessionPhaseTag.Confirmed( + ); + case 5: + return new SessionPhaseTag.Approved( + ); + case 6: + return new SessionPhaseTag.TakenElsewhere( + ); + case 7: + return new SessionPhaseTag.Cancelled( + FfiConverterTypeSessionEndTag.INSTANCE.Read(stream) + ); + case 8: + return new SessionPhaseTag.Expired( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionPhaseTag.Read()", value)); + } + } + + public override int AllocationSize(SessionPhaseTag value) { + switch (value) { + case SessionPhaseTag.Open variant_value: + return 4; + case SessionPhaseTag.Chosen variant_value: + return 4; + case SessionPhaseTag.Compare variant_value: + return 4 + + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.Words); + case SessionPhaseTag.Confirmed variant_value: + return 4; + case SessionPhaseTag.Approved variant_value: + return 4; + case SessionPhaseTag.TakenElsewhere variant_value: + return 4; + case SessionPhaseTag.Cancelled variant_value: + return 4 + + FfiConverterTypeSessionEndTag.INSTANCE.AllocationSize(variant_value.Reason); + case SessionPhaseTag.Expired variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionPhaseTag.AllocationSize()", value)); + } + } + + public override void Write(SessionPhaseTag value, BigEndianStream stream) { + switch (value) { + case SessionPhaseTag.Open variant_value: + stream.WriteInt(1); + break; + case SessionPhaseTag.Chosen variant_value: + stream.WriteInt(2); + break; + case SessionPhaseTag.Compare variant_value: + stream.WriteInt(3); + FfiConverterSequenceString.INSTANCE.Write(variant_value.Words, stream); + break; + case SessionPhaseTag.Confirmed variant_value: + stream.WriteInt(4); + break; + case SessionPhaseTag.Approved variant_value: + stream.WriteInt(5); + break; + case SessionPhaseTag.TakenElsewhere variant_value: + stream.WriteInt(6); + break; + case SessionPhaseTag.Cancelled variant_value: + stream.WriteInt(7); + FfiConverterTypeSessionEndTag.INSTANCE.Write(variant_value.Reason, stream); + break; + case SessionPhaseTag.Expired variant_value: + stream.WriteInt(8); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionPhaseTag.Write()", value)); + } + } +} + + + + + + + +internal enum SessionRoleTag: int { + NewDevice, + Approver +} + +class FfiConverterTypeSessionRoleTag: FfiConverterRustBuffer { + public static FfiConverterTypeSessionRoleTag INSTANCE = new FfiConverterTypeSessionRoleTag(); + + public override SessionRoleTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SessionRoleTag.NewDevice; + case 2: return SessionRoleTag.Approver; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionRoleTag.Read()", value)); + } + } + + public override int AllocationSize(SessionRoleTag value) { + return 4; + } + + public override void Write(SessionRoleTag value, BigEndianStream stream) { + switch (value) { + case SessionRoleTag.NewDevice: stream.WriteInt(1); break; + case SessionRoleTag.Approver: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSessionRoleTag.Write()", value)); + } + } +} + + + + + + + internal record ShareColumnChoice { public record Keep: ShareColumnChoice {} @@ -29410,6 +37020,42 @@ public override void Write(SignOutCauseTag value, BigEndianStream stream) { +internal enum SignOutOutcomeTag: int { + Revoked, + ErasedOffline +} + +class FfiConverterTypeSignOutOutcomeTag: FfiConverterRustBuffer { + public static FfiConverterTypeSignOutOutcomeTag INSTANCE = new FfiConverterTypeSignOutOutcomeTag(); + + public override SignOutOutcomeTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SignOutOutcomeTag.Revoked; + case 2: return SignOutOutcomeTag.ErasedOffline; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSignOutOutcomeTag.Read()", value)); + } + } + + public override int AllocationSize(SignOutOutcomeTag value) { + return 4; + } + + public override void Write(SignOutOutcomeTag value, BigEndianStream stream) { + switch (value) { + case SignOutOutcomeTag.Revoked: stream.WriteInt(1); break; + case SignOutOutcomeTag.ErasedOffline: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSignOutOutcomeTag.Write()", value)); + } + } +} + + + + + + + internal record SourceAvailabilityTag { public record Available: SourceAvailabilityTag {} @@ -29636,6 +37282,319 @@ public override void Write(SshAuthTag value, BigEndianStream stream) { +internal enum StopCauseTag: int { + CatchUp, + RestoreWait, + RestartHeld +} + +class FfiConverterTypeStopCauseTag: FfiConverterRustBuffer { + public static FfiConverterTypeStopCauseTag INSTANCE = new FfiConverterTypeStopCauseTag(); + + public override StopCauseTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return StopCauseTag.CatchUp; + case 2: return StopCauseTag.RestoreWait; + case 3: return StopCauseTag.RestartHeld; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeStopCauseTag.Read()", value)); + } + } + + public override int AllocationSize(StopCauseTag value) { + return 4; + } + + public override void Write(StopCauseTag value, BigEndianStream stream) { + switch (value) { + case StopCauseTag.CatchUp: stream.WriteInt(1); break; + case StopCauseTag.RestoreWait: stream.WriteInt(2); break; + case StopCauseTag.RestartHeld: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeStopCauseTag.Write()", value)); + } + } +} + + + + + + + +internal record SyncFailureInfo { + + public record StepUp ( + string[] AcrValues, + ulong MaxAgeSecs + ) : SyncFailureInfo {} + + public record RetryAfter ( + ulong Ms + ) : SyncFailureInfo {} + + public record Rejected ( + string Code + ) : SyncFailureInfo {} + + public record Locked ( + LockCauseTag Cause + ) : SyncFailureInfo {} + + + +} + +class FfiConverterTypeSyncFailureInfo : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeSyncFailureInfo(); + + public override SyncFailureInfo Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new SyncFailureInfo.StepUp( + FfiConverterSequenceString.INSTANCE.Read(stream), + FfiConverterUInt64.INSTANCE.Read(stream) + ); + case 2: + return new SyncFailureInfo.RetryAfter( + FfiConverterUInt64.INSTANCE.Read(stream) + ); + case 3: + return new SyncFailureInfo.Rejected( + FfiConverterString.INSTANCE.Read(stream) + ); + case 4: + return new SyncFailureInfo.Locked( + FfiConverterTypeLockCauseTag.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncFailureInfo.Read()", value)); + } + } + + public override int AllocationSize(SyncFailureInfo value) { + switch (value) { + case SyncFailureInfo.StepUp variant_value: + return 4 + + FfiConverterSequenceString.INSTANCE.AllocationSize(variant_value.AcrValues) + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.MaxAgeSecs); + case SyncFailureInfo.RetryAfter variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.Ms); + case SyncFailureInfo.Rejected variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Code); + case SyncFailureInfo.Locked variant_value: + return 4 + + FfiConverterTypeLockCauseTag.INSTANCE.AllocationSize(variant_value.Cause); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncFailureInfo.AllocationSize()", value)); + } + } + + public override void Write(SyncFailureInfo value, BigEndianStream stream) { + switch (value) { + case SyncFailureInfo.StepUp variant_value: + stream.WriteInt(1); + FfiConverterSequenceString.INSTANCE.Write(variant_value.AcrValues, stream); + FfiConverterUInt64.INSTANCE.Write(variant_value.MaxAgeSecs, stream); + break; + case SyncFailureInfo.RetryAfter variant_value: + stream.WriteInt(2); + FfiConverterUInt64.INSTANCE.Write(variant_value.Ms, stream); + break; + case SyncFailureInfo.Rejected variant_value: + stream.WriteInt(3); + FfiConverterString.INSTANCE.Write(variant_value.Code, stream); + break; + case SyncFailureInfo.Locked variant_value: + stream.WriteInt(4); + FfiConverterTypeLockCauseTag.INSTANCE.Write(variant_value.Cause, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncFailureInfo.Write()", value)); + } + } +} + + + + + + + +internal record SyncPhaseTag { + + public record Off: SyncPhaseTag {} + + + public record Unavailable: SyncPhaseTag {} + + + public record Idle: SyncPhaseTag {} + + + public record Syncing: SyncPhaseTag {} + + + public record Waiting ( + ulong RetryInMs + ) : SyncPhaseTag {} + + public record PullOnly: SyncPhaseTag {} + + + public record ZoneRemoved: SyncPhaseTag {} + + + public record NewIdentity: SyncPhaseTag {} + + + + +} + +class FfiConverterTypeSyncPhaseTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeSyncPhaseTag(); + + public override SyncPhaseTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new SyncPhaseTag.Off( + ); + case 2: + return new SyncPhaseTag.Unavailable( + ); + case 3: + return new SyncPhaseTag.Idle( + ); + case 4: + return new SyncPhaseTag.Syncing( + ); + case 5: + return new SyncPhaseTag.Waiting( + FfiConverterUInt64.INSTANCE.Read(stream) + ); + case 6: + return new SyncPhaseTag.PullOnly( + ); + case 7: + return new SyncPhaseTag.ZoneRemoved( + ); + case 8: + return new SyncPhaseTag.NewIdentity( + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncPhaseTag.Read()", value)); + } + } + + public override int AllocationSize(SyncPhaseTag value) { + switch (value) { + case SyncPhaseTag.Off variant_value: + return 4; + case SyncPhaseTag.Unavailable variant_value: + return 4; + case SyncPhaseTag.Idle variant_value: + return 4; + case SyncPhaseTag.Syncing variant_value: + return 4; + case SyncPhaseTag.Waiting variant_value: + return 4 + + FfiConverterUInt64.INSTANCE.AllocationSize(variant_value.RetryInMs); + case SyncPhaseTag.PullOnly variant_value: + return 4; + case SyncPhaseTag.ZoneRemoved variant_value: + return 4; + case SyncPhaseTag.NewIdentity variant_value: + return 4; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncPhaseTag.AllocationSize()", value)); + } + } + + public override void Write(SyncPhaseTag value, BigEndianStream stream) { + switch (value) { + case SyncPhaseTag.Off variant_value: + stream.WriteInt(1); + break; + case SyncPhaseTag.Unavailable variant_value: + stream.WriteInt(2); + break; + case SyncPhaseTag.Idle variant_value: + stream.WriteInt(3); + break; + case SyncPhaseTag.Syncing variant_value: + stream.WriteInt(4); + break; + case SyncPhaseTag.Waiting variant_value: + stream.WriteInt(5); + FfiConverterUInt64.INSTANCE.Write(variant_value.RetryInMs, stream); + break; + case SyncPhaseTag.PullOnly variant_value: + stream.WriteInt(6); + break; + case SyncPhaseTag.ZoneRemoved variant_value: + stream.WriteInt(7); + break; + case SyncPhaseTag.NewIdentity variant_value: + stream.WriteInt(8); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncPhaseTag.Write()", value)); + } + } +} + + + + + + + +internal enum SyncPlatformTag: int { + Macos, + Ios, + Linux, + Windows +} + +class FfiConverterTypeSyncPlatformTag: FfiConverterRustBuffer { + public static FfiConverterTypeSyncPlatformTag INSTANCE = new FfiConverterTypeSyncPlatformTag(); + + public override SyncPlatformTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SyncPlatformTag.Macos; + case 2: return SyncPlatformTag.Ios; + case 3: return SyncPlatformTag.Linux; + case 4: return SyncPlatformTag.Windows; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncPlatformTag.Read()", value)); + } + } + + public override int AllocationSize(SyncPlatformTag value) { + return 4; + } + + public override void Write(SyncPlatformTag value, BigEndianStream stream) { + switch (value) { + case SyncPlatformTag.Macos: stream.WriteInt(1); break; + case SyncPlatformTag.Ios: stream.WriteInt(2); break; + case SyncPlatformTag.Linux: stream.WriteInt(3); break; + case SyncPlatformTag.Windows: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSyncPlatformTag.Write()", value)); + } + } +} + + + + + + + internal enum SyncProviderTag: int { Off, Icloud, @@ -29675,6 +37634,48 @@ public override void Write(SyncProviderTag value, BigEndianStream stream) { +internal enum TeamRoleTag: int { + Owner, + Admin, + Editor, + Member +} + +class FfiConverterTypeTeamRoleTag: FfiConverterRustBuffer { + public static FfiConverterTypeTeamRoleTag INSTANCE = new FfiConverterTypeTeamRoleTag(); + + public override TeamRoleTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return TeamRoleTag.Owner; + case 2: return TeamRoleTag.Admin; + case 3: return TeamRoleTag.Editor; + case 4: return TeamRoleTag.Member; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeTeamRoleTag.Read()", value)); + } + } + + public override int AllocationSize(TeamRoleTag value) { + return 4; + } + + public override void Write(TeamRoleTag value, BigEndianStream stream) { + switch (value) { + case TeamRoleTag.Owner: stream.WriteInt(1); break; + case TeamRoleTag.Admin: stream.WriteInt(2); break; + case TeamRoleTag.Editor: stream.WriteInt(3); break; + case TeamRoleTag.Member: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeTeamRoleTag.Write()", value)); + } + } +} + + + + + + + internal enum TlsFailureTag: int { UnknownIssuer, NameMismatch, @@ -30298,49 +38299,6 @@ public static void Register() { -class ConcurrentHandleMap where T: notnull { - readonly ConcurrentDictionary _map = new(); - - // Handles are odd numbers (1, 3, 5, ...) — the lowest bit must always be set. - // Rust uses (handle & 1) to distinguish foreign-language handles from Rust Arc - // pointers, which are always even due to memory alignment. See uniffi_core/src/ffi/handle.rs. - const long HANDLE_INITIAL = 1; - const long HANDLE_DELTA = 2; - long _currentHandle = HANDLE_INITIAL - HANDLE_DELTA; - - public ulong Insert(T obj) { - var handle = (ulong)Interlocked.Add(ref _currentHandle, HANDLE_DELTA); - if (!_map.TryAdd(handle, obj)) { - throw new InternalException("ConcurrentHandleMap: Duplicate handle"); - } - return handle; - } - - public bool TryGet(ulong handle, [NotNullWhen(true)] out T? result) { - return _map.TryGetValue(handle, out result); - } - - public T Get(ulong handle) { - if (_map.TryGetValue(handle, out var result)) { - return result; - } else { - throw new InternalException("ConcurrentHandleMap: Invalid handle"); - } - } - - public bool Remove(ulong handle) { - return _map.TryRemove(handle, out _); - } - - public bool Remove(ulong handle, [NotNullWhen(true)] out T? result) { - return _map.TryRemove(handle, out result); - } -} -static class UniffiCallbackResponseStatus { - public static sbyte SUCCESS = 0; - public static sbyte ERROR = 1; - public static sbyte UNEXPECTED_ERROR = 2; -} // The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. class FfiConverterTypeAccountListener: FfiConverter { @@ -30577,6 +38535,355 @@ public override void Write(HostBrowser value, BigEndianStream stream) { +internal interface HostDeviceStore { + /// + byte[]? Load(DeviceItemTag @item); + /// + void Store(DeviceItemTag @item, byte[] @value); + /// + void Delete(DeviceItemTag @item); +} + +class UniffiCallbackInterfaceHostDeviceStore { + static void Load(ulong @uniffiHandle,RustBuffer @item,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + var result = + uniffiObject.Load( + FfiConverterTypeDeviceItemTag.INSTANCE.Lift(@item)); + unsafe { + *(RustBuffer*)uniffiOutReturn = FfiConverterOptionalByteArray.INSTANCE.Lower(result); + } + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void Store(ulong @uniffiHandle,RustBuffer @item,RustBuffer @value,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.Store( + FfiConverterTypeDeviceItemTag.INSTANCE.Lift(@item), + FfiConverterByteArray.INSTANCE.Lift(@value)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void Delete(ulong @uniffiHandle,RustBuffer @item,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.Delete( + FfiConverterTypeDeviceItemTag.INSTANCE.Lift(@item)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.Remove(@handle); + } + + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeHostDeviceStore.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } + } + static _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod0(Load); + static _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod1(Store); + static _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod2 _m2 = new _UniFFILib.UniffiCallbackInterfaceHostDeviceStoreMethod2(Delete); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); + + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceHostDeviceStore _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostDeviceStore { + @load = Marshal.GetFunctionPointerForDelegate(_m0), + @store = Marshal.GetFunctionPointerForDelegate(_m1), + @delete = Marshal.GetFunctionPointerForDelegate(_m2), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostdevicestore(_vtablePin.Value.AddrOfPinnedObject()); + } +} + + + + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeHostDeviceStore: FfiConverter { + public static FfiConverterTypeHostDeviceStore INSTANCE = new FfiConverterTypeHostDeviceStore(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(HostDeviceStore value) { + return handleMap.Insert(value); + } + + public override HostDeviceStore Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } + + public override HostDeviceStore Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(HostDeviceStore value) { + return 8; + } + + public override void Write(HostDeviceStore value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface HostLegacyMirror { + /// + LegacyMetadataArg Read(); + /// + void Write(LegacyMetadataArg @metadata); + /// + void Mark(LegacyRecordArg[] @dirty, LegacyTombstoneArg[] @tombstones); +} + +class UniffiCallbackInterfaceHostLegacyMirror { + static void Read(ulong @uniffiHandle,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + var result = + uniffiObject.Read(); + unsafe { + *(RustBuffer*)uniffiOutReturn = FfiConverterTypeLegacyMetadataArg.INSTANCE.Lower(result); + } + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void Write(ulong @uniffiHandle,RustBuffer @metadata,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.Write( + FfiConverterTypeLegacyMetadataArg.INSTANCE.Lift(@metadata)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void Mark(ulong @uniffiHandle,RustBuffer @dirty,RustBuffer @tombstones,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.Mark( + FfiConverterSequenceTypeLegacyRecordArg.INSTANCE.Lift(@dirty), + FfiConverterSequenceTypeLegacyTombstoneArg.INSTANCE.Lift(@tombstones)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.Remove(@handle); + } + + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeHostLegacyMirror.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } + } + static _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod0(Read); + static _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod1(Write); + static _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod2 _m2 = new _UniFFILib.UniffiCallbackInterfaceHostLegacyMirrorMethod2(Mark); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); + + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceHostLegacyMirror _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostLegacyMirror { + @read = Marshal.GetFunctionPointerForDelegate(_m0), + @write = Marshal.GetFunctionPointerForDelegate(_m1), + @mark = Marshal.GetFunctionPointerForDelegate(_m2), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostlegacymirror(_vtablePin.Value.AddrOfPinnedObject()); + } +} + + + + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeHostLegacyMirror: FfiConverter { + public static FfiConverterTypeHostLegacyMirror INSTANCE = new FfiConverterTypeHostLegacyMirror(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(HostLegacyMirror value) { + return handleMap.Insert(value); + } + + public override HostLegacyMirror Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } + + public override HostLegacyMirror Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(HostLegacyMirror value) { + return 8; + } + + public override void Write(HostLegacyMirror value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + internal interface HostPrompter { PromptAnswer Prompt(PromptRequest @prompt); } @@ -30948,27 +39255,175 @@ static void DeleteItem(ulong @uniffiHandle,RustBuffer @item,IntPtr @uniffiOutRet } static void UniffiFree(ulong @handle) { - FfiConverterTypeHostSecrets.INSTANCE.handleMap.Remove(@handle); + FfiConverterTypeHostSecrets.INSTANCE.handleMap.Remove(@handle); + } + + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeHostSecrets.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeHostSecrets.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } + } + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod0(Load); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod1(Store); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod2 _m2 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod2(Relabel); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod3 _m3 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod3(Delete); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod4 _m4 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod4(DeleteConnection); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod5 _m5 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod5(LoadItem); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod6 _m6 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod6(StoreItem); + static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod7 _m7 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod7(DeleteItem); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); + + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceHostSecrets _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostSecrets { + @load = Marshal.GetFunctionPointerForDelegate(_m0), + @store = Marshal.GetFunctionPointerForDelegate(_m1), + @relabel = Marshal.GetFunctionPointerForDelegate(_m2), + @delete = Marshal.GetFunctionPointerForDelegate(_m3), + @deleteConnection = Marshal.GetFunctionPointerForDelegate(_m4), + @loadItem = Marshal.GetFunctionPointerForDelegate(_m5), + @storeItem = Marshal.GetFunctionPointerForDelegate(_m6), + @deleteItem = Marshal.GetFunctionPointerForDelegate(_m7), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(_vtablePin.Value.AddrOfPinnedObject()); + } +} + + + + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeHostSecrets: FfiConverter { + public static FfiConverterTypeHostSecrets INSTANCE = new FfiConverterTypeHostSecrets(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(HostSecrets value) { + return handleMap.Insert(value); + } + + public override HostSecrets Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } + + public override HostSecrets Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(HostSecrets value) { + return 8; + } + + public override void Write(HostSecrets value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface HostSettings { + /// + SettingsCategoryArg[] Categories(); + /// + void Apply(string @category, string? @document); +} + +class UniffiCallbackInterfaceHostSettings { + static void Categories(ulong @uniffiHandle,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostSettings.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + var result = + uniffiObject.Categories(); + unsafe { + *(RustBuffer*)uniffiOutReturn = FfiConverterSequenceTypeSettingsCategoryArg.INSTANCE.Lower(result); + } + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void Apply(ulong @uniffiHandle,RustBuffer @category,RustBuffer @document,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostSettings.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.Apply( + FfiConverterString.INSTANCE.Lift(@category), + FfiConverterOptionalString.INSTANCE.Lift(@document)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostSecretException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostSecretError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeHostSettings.INSTANCE.handleMap.Remove(@handle); } static ulong UniffiClone(ulong @handle) { try { - if (!FfiConverterTypeHostSecrets.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + if (!FfiConverterTypeHostSettings.INSTANCE.handleMap.TryGet(@handle, out var obj)) { throw new InternalException($"No callback in handlemap '{@handle}'"); } - return FfiConverterTypeHostSecrets.INSTANCE.handleMap.Insert(obj); + return FfiConverterTypeHostSettings.INSTANCE.handleMap.Insert(obj); } catch (System.Exception) { return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 } } - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod0(Load); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod1(Store); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod2 _m2 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod2(Relabel); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod3 _m3 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod3(Delete); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod4 _m4 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod4(DeleteConnection); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod5 _m5 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod5(LoadItem); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod6 _m6 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod6(StoreItem); - static _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod7 _m7 = new _UniFFILib.UniffiCallbackInterfaceHostSecretsMethod7(DeleteItem); + static _UniFFILib.UniffiCallbackInterfaceHostSettingsMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostSettingsMethod0(Categories); + static _UniFFILib.UniffiCallbackInterfaceHostSettingsMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceHostSettingsMethod1(Apply); static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); @@ -30976,15 +39431,9 @@ static ulong UniffiClone(ulong @handle) { public static void Register() { if (_vtablePin.HasValue) return; - _UniFFILib.UniffiVTableCallbackInterfaceHostSecrets _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostSecrets { - @load = Marshal.GetFunctionPointerForDelegate(_m0), - @store = Marshal.GetFunctionPointerForDelegate(_m1), - @relabel = Marshal.GetFunctionPointerForDelegate(_m2), - @delete = Marshal.GetFunctionPointerForDelegate(_m3), - @deleteConnection = Marshal.GetFunctionPointerForDelegate(_m4), - @loadItem = Marshal.GetFunctionPointerForDelegate(_m5), - @storeItem = Marshal.GetFunctionPointerForDelegate(_m6), - @deleteItem = Marshal.GetFunctionPointerForDelegate(_m7), + _UniFFILib.UniffiVTableCallbackInterfaceHostSettings _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostSettings { + @categories = Marshal.GetFunctionPointerForDelegate(_m0), + @apply = Marshal.GetFunctionPointerForDelegate(_m1), @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), }; @@ -30992,7 +39441,7 @@ public static void Register() { // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — // this pin must remain valid for the process lifetime. _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); - _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(_vtablePin.Value.AddrOfPinnedObject()); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostsettings(_vtablePin.Value.AddrOfPinnedObject()); } } @@ -31000,16 +39449,16 @@ public static void Register() { // The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. -class FfiConverterTypeHostSecrets: FfiConverter { - public static FfiConverterTypeHostSecrets INSTANCE = new FfiConverterTypeHostSecrets(); +class FfiConverterTypeHostSettings: FfiConverter { + public static FfiConverterTypeHostSettings INSTANCE = new FfiConverterTypeHostSettings(); - public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); - public override ulong Lower(HostSecrets value) { + public override ulong Lower(HostSettings value) { return handleMap.Insert(value); } - public override HostSecrets Lift(ulong value) { + public override HostSettings Lift(ulong value) { if (handleMap.TryGet(value, out var uniffiCallback)) { return uniffiCallback; } else { @@ -31017,15 +39466,15 @@ public override HostSecrets Lift(ulong value) { } } - public override HostSecrets Read(BigEndianStream stream) { + public override HostSettings Read(BigEndianStream stream) { return Lift(stream.ReadULong()); } - public override int AllocationSize(HostSecrets value) { + public override int AllocationSize(HostSettings value) { return 8; } - public override void Write(HostSecrets value, BigEndianStream stream) { + public override void Write(HostSettings value, BigEndianStream stream) { stream.WriteULong(Lower(value)); } } @@ -31539,6 +39988,124 @@ public override void Write(RunListener value, BigEndianStream stream) { +internal interface SyncListener { + void StatusChanged(); + void KeysChanged(); +} + +class UniffiCallbackInterfaceSyncListener { + static void StatusChanged(ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeSyncListener.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.StatusChanged(); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + static void KeysChanged(ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeSyncListener.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.KeysChanged(); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeSyncListener.INSTANCE.handleMap.Remove(@handle); + } + + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeSyncListener.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeSyncListener.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } + } + static _UniFFILib.UniffiCallbackInterfaceSyncListenerMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceSyncListenerMethod0(StatusChanged); + static _UniFFILib.UniffiCallbackInterfaceSyncListenerMethod1 _m1 = new _UniFFILib.UniffiCallbackInterfaceSyncListenerMethod1(KeysChanged); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); + + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceSyncListener _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceSyncListener { + @statusChanged = Marshal.GetFunctionPointerForDelegate(_m0), + @keysChanged = Marshal.GetFunctionPointerForDelegate(_m1), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_synclistener(_vtablePin.Value.AddrOfPinnedObject()); + } +} + + + + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeSyncListener: FfiConverter { + public static FfiConverterTypeSyncListener INSTANCE = new FfiConverterTypeSyncListener(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(SyncListener value) { + return handleMap.Insert(value); + } + + public override SyncListener Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } + + public override SyncListener Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(SyncListener value) { + return 8; + } + + public override void Write(SyncListener value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + class FfiConverterOptionalUInt16: FfiConverterRustBuffer { public static FfiConverterOptionalUInt16 INSTANCE = new FfiConverterOptionalUInt16(); @@ -31726,6 +40293,37 @@ public override void Write(string? value, BigEndianStream stream) { +class FfiConverterOptionalByteArray: FfiConverterRustBuffer { + public static FfiConverterOptionalByteArray INSTANCE = new FfiConverterOptionalByteArray(); + + public override byte[]? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterByteArray.INSTANCE.Read(stream); + } + + public override int AllocationSize(byte[]? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterByteArray.INSTANCE.AllocationSize((byte[])value); + } + } + + public override void Write(byte[]? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterByteArray.INSTANCE.Write((byte[])value, stream); + } + } +} + + + + class FfiConverterOptionalTypeCancelToken: FfiConverterRustBuffer { public static FfiConverterOptionalTypeCancelToken INSTANCE = new FfiConverterOptionalTypeCancelToken(); @@ -31757,6 +40355,37 @@ public override void Write(CancelToken? value, BigEndianStream stream) { +class FfiConverterOptionalTypeCloudKitTransport: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCloudKitTransport INSTANCE = new FfiConverterOptionalTypeCloudKitTransport(); + + public override CloudKitTransport? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeCloudKitTransport.INSTANCE.Read(stream); + } + + public override int AllocationSize(CloudKitTransport? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeCloudKitTransport.INSTANCE.AllocationSize((CloudKitTransport)value); + } + } + + public override void Write(CloudKitTransport? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeCloudKitTransport.INSTANCE.Write((CloudKitTransport)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeCompletionList: FfiConverterRustBuffer { public static FfiConverterOptionalTypeCompletionList INSTANCE = new FfiConverterOptionalTypeCompletionList(); @@ -31974,6 +40603,37 @@ public override void Write(CellTextHead? value, BigEndianStream stream) { +class FfiConverterOptionalTypeCloudKitRecord: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCloudKitRecord INSTANCE = new FfiConverterOptionalTypeCloudKitRecord(); + + public override CloudKitRecord? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeCloudKitRecord.INSTANCE.Read(stream); + } + + public override int AllocationSize(CloudKitRecord? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeCloudKitRecord.INSTANCE.AllocationSize((CloudKitRecord)value); + } + } + + public override void Write(CloudKitRecord? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeCloudKitRecord.INSTANCE.Write((CloudKitRecord)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeCloudSqlProxyRecord: FfiConverterRustBuffer { public static FfiConverterOptionalTypeCloudSqlProxyRecord INSTANCE = new FfiConverterOptionalTypeCloudSqlProxyRecord(); @@ -32129,6 +40789,37 @@ public override void Write(ExistingConnectionInfo? value, BigEndianStream stream +class FfiConverterOptionalTypeHeldRestartInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeHeldRestartInfo INSTANCE = new FfiConverterOptionalTypeHeldRestartInfo(); + + public override HeldRestartInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeHeldRestartInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(HeldRestartInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeHeldRestartInfo.INSTANCE.AllocationSize((HeldRestartInfo)value); + } + } + + public override void Write(HeldRestartInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeHeldRestartInfo.INSTANCE.Write((HeldRestartInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeHistoryCursorArg: FfiConverterRustBuffer { public static FfiConverterOptionalTypeHistoryCursorArg INSTANCE = new FfiConverterOptionalTypeHistoryCursorArg(); @@ -32191,6 +40882,37 @@ public override void Write(HostKeyFailure? value, BigEndianStream stream) { +class FfiConverterOptionalTypeKeyChangeInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeKeyChangeInfo INSTANCE = new FfiConverterOptionalTypeKeyChangeInfo(); + + public override KeyChangeInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeKeyChangeInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(KeyChangeInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeKeyChangeInfo.INSTANCE.AllocationSize((KeyChangeInfo)value); + } + } + + public override void Write(KeyChangeInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeKeyChangeInfo.INSTANCE.Write((KeyChangeInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeKeyWindowInfo: FfiConverterRustBuffer { public static FfiConverterOptionalTypeKeyWindowInfo INSTANCE = new FfiConverterOptionalTypeKeyWindowInfo(); @@ -32315,6 +41037,37 @@ public override void Write(ObjectSource? value, BigEndianStream stream) { +class FfiConverterOptionalTypePendingResetInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypePendingResetInfo INSTANCE = new FfiConverterOptionalTypePendingResetInfo(); + + public override PendingResetInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypePendingResetInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(PendingResetInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypePendingResetInfo.INSTANCE.AllocationSize((PendingResetInfo)value); + } + } + + public override void Write(PendingResetInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypePendingResetInfo.INSTANCE.Write((PendingResetInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeServerLicenseInfo: FfiConverterRustBuffer { public static FfiConverterOptionalTypeServerLicenseInfo INSTANCE = new FfiConverterOptionalTypeServerLicenseInfo(); @@ -32687,6 +41440,37 @@ public override void Write(AiProviderTag? value, BigEndianStream stream) { +class FfiConverterOptionalTypeCloudKitValue: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeCloudKitValue INSTANCE = new FfiConverterOptionalTypeCloudKitValue(); + + public override CloudKitValue? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeCloudKitValue.INSTANCE.Read(stream); + } + + public override int AllocationSize(CloudKitValue? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeCloudKitValue.INSTANCE.AllocationSize((CloudKitValue)value); + } + } + + public override void Write(CloudKitValue? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeCloudKitValue.INSTANCE.Write((CloudKitValue)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeCredentialReferenceRecord: FfiConverterRustBuffer { public static FfiConverterOptionalTypeCredentialReferenceRecord INSTANCE = new FfiConverterOptionalTypeCredentialReferenceRecord(); @@ -33028,6 +41812,68 @@ public override void Write(ShareRefusal? value, BigEndianStream stream) { +class FfiConverterOptionalTypeStopCauseTag: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeStopCauseTag INSTANCE = new FfiConverterOptionalTypeStopCauseTag(); + + public override StopCauseTag? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeStopCauseTag.INSTANCE.Read(stream); + } + + public override int AllocationSize(StopCauseTag? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeStopCauseTag.INSTANCE.AllocationSize((StopCauseTag)value); + } + } + + public override void Write(StopCauseTag? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeStopCauseTag.INSTANCE.Write((StopCauseTag)value, stream); + } + } +} + + + + +class FfiConverterOptionalTypeSyncFailureInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeSyncFailureInfo INSTANCE = new FfiConverterOptionalTypeSyncFailureInfo(); + + public override SyncFailureInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeSyncFailureInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(SyncFailureInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeSyncFailureInfo.INSTANCE.AllocationSize((SyncFailureInfo)value); + } + } + + public override void Write(SyncFailureInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeSyncFailureInfo.INSTANCE.Write((SyncFailureInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeSyncProviderTag: FfiConverterRustBuffer { public static FfiConverterOptionalTypeSyncProviderTag INSTANCE = new FfiConverterOptionalTypeSyncProviderTag(); @@ -33121,6 +41967,68 @@ public override void Write(TlsModeTag? value, BigEndianStream stream) { +class FfiConverterOptionalTypeHostDeviceStore: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeHostDeviceStore INSTANCE = new FfiConverterOptionalTypeHostDeviceStore(); + + public override HostDeviceStore? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeHostDeviceStore.INSTANCE.Read(stream); + } + + public override int AllocationSize(HostDeviceStore? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeHostDeviceStore.INSTANCE.AllocationSize((HostDeviceStore)value); + } + } + + public override void Write(HostDeviceStore? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeHostDeviceStore.INSTANCE.Write((HostDeviceStore)value, stream); + } + } +} + + + + +class FfiConverterOptionalTypeHostLegacyMirror: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeHostLegacyMirror INSTANCE = new FfiConverterOptionalTypeHostLegacyMirror(); + + public override HostLegacyMirror? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeHostLegacyMirror.INSTANCE.Read(stream); + } + + public override int AllocationSize(HostLegacyMirror? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeHostLegacyMirror.INSTANCE.AllocationSize((HostLegacyMirror)value); + } + } + + public override void Write(HostLegacyMirror? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeHostLegacyMirror.INSTANCE.Write((HostLegacyMirror)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeHostPrompter: FfiConverterRustBuffer { public static FfiConverterOptionalTypeHostPrompter INSTANCE = new FfiConverterOptionalTypeHostPrompter(); @@ -33152,6 +42060,37 @@ public override void Write(HostPrompter? value, BigEndianStream stream) { +class FfiConverterOptionalTypeHostSettings: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeHostSettings INSTANCE = new FfiConverterOptionalTypeHostSettings(); + + public override HostSettings? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeHostSettings.INSTANCE.Read(stream); + } + + public override int AllocationSize(HostSettings? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeHostSettings.INSTANCE.AllocationSize((HostSettings)value); + } + } + + public override void Write(HostSettings? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeHostSettings.INSTANCE.Write((HostSettings)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeHostWebAuthenticator: FfiConverterRustBuffer { public static FfiConverterOptionalTypeHostWebAuthenticator INSTANCE = new FfiConverterOptionalTypeHostWebAuthenticator(); @@ -33414,6 +42353,52 @@ public override void Write(string[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeAccountDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeAccountDeviceInfo INSTANCE = new FfiConverterSequenceTypeAccountDeviceInfo(); + + public override AccountDeviceInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new AccountDeviceInfo[length]; + var readFn = FfiConverterTypeAccountDeviceInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(AccountDeviceInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeAccountDeviceInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(AccountDeviceInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeAccountDeviceInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeAiMessageArg: FfiConverterRustBuffer { public static FfiConverterSequenceTypeAiMessageArg INSTANCE = new FfiConverterSequenceTypeAiMessageArg(); @@ -33552,6 +42537,52 @@ public override void Write(AiProviderInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeApprovalRequestInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeApprovalRequestInfo INSTANCE = new FfiConverterSequenceTypeApprovalRequestInfo(); + + public override ApprovalRequestInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ApprovalRequestInfo[length]; + var readFn = FfiConverterTypeApprovalRequestInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ApprovalRequestInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeApprovalRequestInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ApprovalRequestInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeApprovalRequestInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeCellChange: FfiConverterRustBuffer { public static FfiConverterSequenceTypeCellChange INSTANCE = new FfiConverterSequenceTypeCellChange(); @@ -33736,6 +42767,144 @@ public override void Write(CloudGroupFields[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeCloudKitDeletion: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudKitDeletion INSTANCE = new FfiConverterSequenceTypeCloudKitDeletion(); + + public override CloudKitDeletion[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudKitDeletion[length]; + var readFn = FfiConverterTypeCloudKitDeletion.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudKitDeletion[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudKitDeletion.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudKitDeletion[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeCloudKitDeletion.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeCloudKitField: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudKitField INSTANCE = new FfiConverterSequenceTypeCloudKitField(); + + public override CloudKitField[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudKitField[length]; + var readFn = FfiConverterTypeCloudKitField.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudKitField[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudKitField.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudKitField[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeCloudKitField.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeCloudKitRecord: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudKitRecord INSTANCE = new FfiConverterSequenceTypeCloudKitRecord(); + + public override CloudKitRecord[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudKitRecord[length]; + var readFn = FfiConverterTypeCloudKitRecord.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudKitRecord[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudKitRecord.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudKitRecord[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeCloudKitRecord.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeColumnEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeColumnEntry INSTANCE = new FfiConverterSequenceTypeColumnEntry(); @@ -34564,6 +43733,52 @@ public override void Write(GroupRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeHeldRecordInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeHeldRecordInfo INSTANCE = new FfiConverterSequenceTypeHeldRecordInfo(); + + public override HeldRecordInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new HeldRecordInfo[length]; + var readFn = FfiConverterTypeHeldRecordInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(HeldRecordInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeHeldRecordInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(HeldRecordInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeHeldRecordInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeHistoryEntryInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeHistoryEntryInfo INSTANCE = new FfiConverterSequenceTypeHistoryEntryInfo(); @@ -34656,6 +43871,52 @@ public override void Write(ImportColumnInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeKeyNoticeInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeKeyNoticeInfo INSTANCE = new FfiConverterSequenceTypeKeyNoticeInfo(); + + public override KeyNoticeInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new KeyNoticeInfo[length]; + var readFn = FfiConverterTypeKeyNoticeInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(KeyNoticeInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeKeyNoticeInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(KeyNoticeInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeKeyNoticeInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeKeymapBindingInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeKeymapBindingInfo INSTANCE = new FfiConverterSequenceTypeKeymapBindingInfo(); @@ -34748,6 +44009,144 @@ public override void Write(KeymapPresetInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeLegacyRecordArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeLegacyRecordArg INSTANCE = new FfiConverterSequenceTypeLegacyRecordArg(); + + public override LegacyRecordArg[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new LegacyRecordArg[length]; + var readFn = FfiConverterTypeLegacyRecordArg.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(LegacyRecordArg[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeLegacyRecordArg.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(LegacyRecordArg[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeLegacyRecordArg.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeLegacyStandingArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeLegacyStandingArg INSTANCE = new FfiConverterSequenceTypeLegacyStandingArg(); + + public override LegacyStandingArg[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new LegacyStandingArg[length]; + var readFn = FfiConverterTypeLegacyStandingArg.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(LegacyStandingArg[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeLegacyStandingArg.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(LegacyStandingArg[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeLegacyStandingArg.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeLegacyTombstoneArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeLegacyTombstoneArg INSTANCE = new FfiConverterSequenceTypeLegacyTombstoneArg(); + + public override LegacyTombstoneArg[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new LegacyTombstoneArg[length]; + var readFn = FfiConverterTypeLegacyTombstoneArg.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(LegacyTombstoneArg[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeLegacyTombstoneArg.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(LegacyTombstoneArg[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeLegacyTombstoneArg.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeLicenseInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeLicenseInfo INSTANCE = new FfiConverterSequenceTypeLicenseInfo(); @@ -34840,6 +44239,52 @@ public override void Write(MatchedSpan[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeMemberKeysInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeMemberKeysInfo INSTANCE = new FfiConverterSequenceTypeMemberKeysInfo(); + + public override MemberKeysInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new MemberKeysInfo[length]; + var readFn = FfiConverterTypeMemberKeysInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(MemberKeysInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeMemberKeysInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(MemberKeysInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeMemberKeysInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeMembershipInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeMembershipInfo INSTANCE = new FfiConverterSequenceTypeMembershipInfo(); @@ -34932,6 +44377,52 @@ public override void Write(ObjectEntry[] value, BigEndianStream stream) { +class FfiConverterSequenceTypePendingApprovalInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypePendingApprovalInfo INSTANCE = new FfiConverterSequenceTypePendingApprovalInfo(); + + public override PendingApprovalInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new PendingApprovalInfo[length]; + var readFn = FfiConverterTypePendingApprovalInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(PendingApprovalInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypePendingApprovalInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(PendingApprovalInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypePendingApprovalInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypePersonalDataHitInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypePersonalDataHitInfo INSTANCE = new FfiConverterSequenceTypePersonalDataHitInfo(); @@ -35116,6 +44607,98 @@ public override void Write(ResultColumnInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeReviewedDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeReviewedDeviceInfo INSTANCE = new FfiConverterSequenceTypeReviewedDeviceInfo(); + + public override ReviewedDeviceInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ReviewedDeviceInfo[length]; + var readFn = FfiConverterTypeReviewedDeviceInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ReviewedDeviceInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeReviewedDeviceInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ReviewedDeviceInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeReviewedDeviceInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeReviewedMemberInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeReviewedMemberInfo INSTANCE = new FfiConverterSequenceTypeReviewedMemberInfo(); + + public override ReviewedMemberInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ReviewedMemberInfo[length]; + var readFn = FfiConverterTypeReviewedMemberInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ReviewedMemberInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeReviewedMemberInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ReviewedMemberInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeReviewedMemberInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeRowReferenceChoice: FfiConverterRustBuffer { public static FfiConverterSequenceTypeRowReferenceChoice INSTANCE = new FfiConverterSequenceTypeRowReferenceChoice(); @@ -35392,6 +44975,52 @@ public override void Write(SeenClientInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeSettingsCategoryArg: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSettingsCategoryArg INSTANCE = new FfiConverterSequenceTypeSettingsCategoryArg(); + + public override SettingsCategoryArg[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SettingsCategoryArg[length]; + var readFn = FfiConverterTypeSettingsCategoryArg.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SettingsCategoryArg[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSettingsCategoryArg.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SettingsCategoryArg[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeSettingsCategoryArg.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeShareColumnMasking: FfiConverterRustBuffer { public static FfiConverterSequenceTypeShareColumnMasking INSTANCE = new FfiConverterSequenceTypeShareColumnMasking(); @@ -35622,6 +45251,52 @@ public override void Write(SshRouteHopRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeStoppedDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeStoppedDeviceInfo INSTANCE = new FfiConverterSequenceTypeStoppedDeviceInfo(); + + public override StoppedDeviceInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new StoppedDeviceInfo[length]; + var readFn = FfiConverterTypeStoppedDeviceInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(StoppedDeviceInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeStoppedDeviceInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(StoppedDeviceInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeStoppedDeviceInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeStructureColumn: FfiConverterRustBuffer { public static FfiConverterSequenceTypeStructureColumn INSTANCE = new FfiConverterSequenceTypeStructureColumn(); @@ -35990,6 +45665,52 @@ public override void Write(TagRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeTeamConflictInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeTeamConflictInfo INSTANCE = new FfiConverterSequenceTypeTeamConflictInfo(); + + public override TeamConflictInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new TeamConflictInfo[length]; + var readFn = FfiConverterTypeTeamConflictInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(TeamConflictInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeTeamConflictInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(TeamConflictInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeTeamConflictInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeAiReplyEvent: FfiConverterRustBuffer { public static FfiConverterSequenceTypeAiReplyEvent INSTANCE = new FfiConverterSequenceTypeAiReplyEvent(); @@ -36082,6 +45803,98 @@ public override void Write(CellEdit[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeCloudKitFetched: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudKitFetched INSTANCE = new FfiConverterSequenceTypeCloudKitFetched(); + + public override CloudKitFetched[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudKitFetched[length]; + var readFn = FfiConverterTypeCloudKitFetched.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudKitFetched[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudKitFetched.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudKitFetched[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeCloudKitFetched.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeCloudKitOutcome: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeCloudKitOutcome INSTANCE = new FfiConverterSequenceTypeCloudKitOutcome(); + + public override CloudKitOutcome[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new CloudKitOutcome[length]; + var readFn = FfiConverterTypeCloudKitOutcome.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(CloudKitOutcome[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeCloudKitOutcome.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(CloudKitOutcome[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeCloudKitOutcome.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeCombinatorTag: FfiConverterRustBuffer { public static FfiConverterSequenceTypeCombinatorTag INSTANCE = new FfiConverterSequenceTypeCombinatorTag(); @@ -37035,5 +46848,13 @@ public static ushort McpDefaultPort() { } + public static DeviceItemClassTag DeviceItemClass(DeviceItemTag @item) { + return FfiConverterTypeDeviceItemClassTag.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_func_device_item_class(FfiConverterTypeDeviceItemTag.INSTANCE.Lower(@item), ref _status) +)); + } + + }