From e68d422c590f6f4af1d30ddbfd74d0dc87b4635e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonasz=20Ma=C5=82ecki?= Date: Thu, 19 Nov 2026 11:18:09 +0100 Subject: [PATCH] feat(proto)!: keep unknown fields on every message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0.5.0 keeps unknown fields on State and Resource alone. Every field Crossplane has added since the function API went v1 is on another message, where prost still discards it, so a function that forwards a request or returns a response it did not build loses such a field. protobuf-go keeps unknown fields on every message. Codegen now replaces prost's Message derive. prost-build writes every struct as before, and codegen/src/messages.rs gives each one an unknown_fields field and the impls the derive would have written: the fallback arm of merge_field keeps a field's bytes and encode_raw writes them back. It reads the field kinds the function proto uses from the #[prost(...)] attributes and refuses one it does not know. State and Resource are generated again, and sdk/src/proto/state.rs is gone. Codegen also writes the messages as prost derives them to sdk/tests/generated/prost_v1.rs. sdk/tests/generated_messages.rs holds every message to that reference: the same bytes, the same verdict and error on malformed input, the same Debug, defaults and accessors. The codegen-drift check covers the new file. BREAKING CHANGE: every message has a new public unknown_fields field. Struct literals and patterns that list every field of a message no longer compile; add ..Default::default() or `..`. The Debug output of every message includes unknown_fields. Fixes #69 Signed-off-by: Jonasz MaƂecki --- .github/workflows/ci.yml | 5 +- AGENTS.md | 13 +- CONTRIBUTING.md | 43 +- Cargo.lock | 4 + README.md | 18 +- codegen/Cargo.toml | 6 + codegen/src/main.rs | 130 ++- codegen/src/messages.rs | 739 ++++++++++++ sdk/src/generated/v1.rs | 1879 ++++++++++++++++++++++++++++++- sdk/src/generated/v1.serde.rs | 14 + sdk/src/proto.rs | 9 +- sdk/src/proto/state.rs | 323 ------ sdk/src/proto/unknown.rs | 88 ++ sdk/src/response.rs | 12 +- sdk/tests/generated/prost_v1.rs | 594 ++++++++++ sdk/tests/generated_messages.rs | 507 +++++++++ sdk/tests/serve.rs | 1 + sdk/tests/unknown_fields.rs | 233 ++-- 18 files changed, 4022 insertions(+), 596 deletions(-) create mode 100644 codegen/src/messages.rs delete mode 100644 sdk/src/proto/state.rs create mode 100644 sdk/src/proto/unknown.rs create mode 100644 sdk/tests/generated/prost_v1.rs create mode 100644 sdk/tests/generated_messages.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ddd628..6ea365d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,8 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 - run: cargo test --workspace - # The generated code in sdk/src/generated is checked in. Verify it matches + # The generated code in sdk/src/generated and the reference the tests + # compare it with, in sdk/tests/generated, are checked in. Verify they match # what the codegen tool produces from the vendored proto. Only the .rs # outputs are compared; the encoded descriptor set may differ byte-wise # between protoc versions. @@ -50,4 +51,4 @@ jobs: with: repo-token: ${{ secrets.GITHUB_TOKEN }} - run: cargo run -p codegen - - run: git diff --exit-code -- 'sdk/src/generated/*.rs' + - run: git diff --exit-code -- 'sdk/src/generated/*.rs' 'sdk/tests/generated/*.rs' diff --git a/AGENTS.md b/AGENTS.md index 3d5b965..c1a9b9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,16 +18,17 @@ Run all of these before you call a change done. CI requires them. cargo fmt --all --check cargo clippy --workspace --tests -- -D warnings cargo test --workspace -cargo run -p codegen # needs protoc; must leave sdk/src/generated unchanged +cargo run -p codegen # needs protoc; must leave the generated files unchanged ``` ## Rules -- Never edit `sdk/src/generated` by hand. Change the proto or `codegen/` and - regenerate. -- `State` and `Resource` are written by hand in `sdk/src/proto/state.rs`. - When the proto changes either message, update that file and - `sdk/tests/unknown_fields.rs` as CONTRIBUTING.md describes. +- Never edit `sdk/src/generated` or `sdk/tests/generated` by hand. Change the + proto or `codegen/` and regenerate. +- Every message keeps unknown fields: `codegen/src/messages.rs` writes the + `prost::Message` impls in place of prost's derive. When codegen refuses a + field kind, or a test in `sdk/tests/generated_messages.rs` fails, follow + CONTRIBUTING.md. - A new public field on a message struct is a breaking change. Say so in the commit and the pull request. - Don't change the crate version outside a release pull request. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3fbac2..8ebf2d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,18 +33,22 @@ cargo run -p codegen CI runs four checks on every pull request, and all four must pass before it can merge: `fmt`, `clippy`, `test` and `codegen-drift`. The last one runs -codegen and fails when the `.rs` files in `sdk/src/generated` differ from -what's checked in. +codegen and fails when the `.rs` files in `sdk/src/generated` or +`sdk/tests/generated` differ from what's checked in. -### Generated and hand-written protocol code +### Generated protocol code -Don't edit `sdk/src/generated` by hand. Change the proto or `codegen/`, then -run codegen and commit the result. +Don't edit `sdk/src/generated` or `sdk/tests/generated` by hand. Change the +proto or `codegen/`, then run codegen and commit the result. -Two messages aren't generated. `State` and `Resource` are written by hand in -`sdk/src/proto/state.rs` so that they keep fields this SDK doesn't know, -which prost-generated messages discard. Codegen skips both and adds -`unknown_fields` to their generated serde constructors. +prost discards a field it doesn't know, so codegen replaces prost's `Message` +derive. `codegen/src/messages.rs` gives every message an `unknown_fields` +field and writes the impls the derive would have written, with the unknown +fields kept and encoded again. Codegen also writes the messages as prost +derives them to `sdk/tests/generated/prost_v1.rs`. +`sdk/tests/generated_messages.rs` compares the two for every message: the +bytes, the errors on malformed input, `Debug`, the defaults and the +accessors. ### Updating the vendored proto @@ -58,14 +62,15 @@ Finish it on its branch: 1. Replace the file with the one from the release tag, and put the `Vendored from crossplane/crossplane` comment back above `syntax` with the new version. -2. Run `cargo run -p codegen` and commit the changes in `sdk/src/generated`. - New fields on generated messages need nothing else. -3. If the update changes `State` or `Resource`, the build fails in the - generated serde code and a test in `sdk/tests/unknown_fields.rs` fails. - Update `sdk/src/proto/state.rs` to match: the struct field, `encode_raw`, - `merge_field`, `encoded_len`, and `Debug` for `Resource`. Then update the - prost-derived copies and the expected field list in that test file. -4. Run the checks above. +2. Run `cargo run -p codegen` and commit the changes in `sdk/src/generated` + and `sdk/tests/generated`. A new field needs nothing else. +3. If codegen stops at a field kind it doesn't write yet, its error gives + the field and the `#[prost(...)]` attribute. Add the kind to + `codegen/src/messages.rs`, following what prost's derive generates for it. +4. If the update adds a message, `the_checks_cover_every_message_of_the_proto` + fails. Add the message to `for_every_message` and to `sample` in + `sdk/tests/generated_messages.rs`, and set new fields in the samples. +5. Run the checks above. A new field on any message is a breaking change for this crate, because the message structs are public and can be built with a struct literal. Say so in @@ -81,6 +86,10 @@ change the generated code, and its pull request then fails `codegen-drift`. Check out the branch, run `cargo run -p codegen`, and push the result to the same branch. +A new version of `prost` can change what its `Message` derive does. Its pull +request then fails in `sdk/tests/generated_messages.rs`, and +`codegen/src/messages.rs` has to follow the derive before it merges. + ## Submitting changes * Open an issue first for anything beyond a small fix, so we can agree on the diff --git a/Cargo.lock b/Cargo.lock index e039fd4..6e484b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -264,7 +264,11 @@ name = "codegen" version = "0.1.0" dependencies = [ "pbjson-build", + "prettyplease 0.3.0", + "proc-macro2", "prost-build", + "quote", + "syn 3.0.10", "tempfile", "tonic-prost-build", ] diff --git a/README.md b/README.md index 4e0a3b4..6e7cd87 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,10 @@ for working with requests and responses. encoded file descriptor set used for gRPC server reflection. - `src/{server,request,response,resource,logging}.rs` - the hand-written SDK: runtime and helpers. -- `codegen/` - maintainer tool that regenerates `sdk/src/generated`. + - `tests/generated/` - the messages as prost derives them, which the tests + compare the generated ones with. +- `codegen/` - maintainer tool that regenerates `sdk/src/generated` and + `sdk/tests/generated`. - `example/` - an example function, the starting point for new functions. ## Writing a function @@ -105,12 +108,13 @@ with a few deliberate differences: `Server::ready`: until it completes, the server reports NOT_SERVING and answers RunFunction with UNAVAILABLE, and if it fails, the server stops with `Error::NotReady`. -- **Unknown fields are kept on `State` and `Resource` only.** protobuf-go - keeps fields it does not know on every message. This SDK keeps them on the - two messages `response::to` copies from the request, so a field a newer - Crossplane adds to them passes through a function unchanged. - As in Go, replacing a desired resource instead of modifying it in place - drops that resource's unknown fields. +- **Every message keeps unknown fields.** Like protobuf-go, this SDK keeps + the fields it doesn't know, in `unknown_fields`, and writes them back when + it encodes the message. A field a newer Crossplane adds to a request passes + through a function unchanged, and so does a field on a response the + function forwards. A function can't read or change such a field, and it has + no JSON form. As in Go, replacing a desired resource instead of modifying + it in place drops that resource's unknown fields. - **Graceful shutdown is built in.** The server drains in-flight requests on SIGTERM and SIGINT. - **Metrics are Go-compatible, served as OpenMetrics first.** Like diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index d69240d..09e6c6a 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -11,3 +11,9 @@ prost-build = "0.14" tonic-prost-build = "0.14" pbjson-build = "0.9" tempfile = "3" +# The rewrite of the generated messages (src/messages.rs): prost-build's own +# parser and formatter. +syn = { version = "3", features = ["full"] } +quote = "1" +proc-macro2 = "1" +prettyplease = "0.3" diff --git a/codegen/src/main.rs b/codegen/src/main.rs index 60fa7c2..ba6d559 100644 --- a/codegen/src/main.rs +++ b/codegen/src/main.rs @@ -2,18 +2,23 @@ //! //! Maintainer tool: requires `protoc` on PATH. SDK users never run this //! because the generated code is committed. +//! +//! prost-build, tonic and pbjson generate the code. `messages` then rewrites +//! the messages so that they keep unknown fields, and what prost wrote for +//! them is kept beside the tests as the reference the rewrite is held to. + +mod messages; use std::error::Error; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; const PROTO: &str = "sdk/proto/v1/run_function.proto"; const INCLUDE: &str = "sdk/proto"; const OUT: &str = "sdk/src/generated"; - -/// Messages written by hand in `sdk/src/proto/state.rs` so that they keep -/// unknown fields, which prost-generated messages discard. -const HAND_WRITTEN: [&str; 2] = ["State", "Resource"]; +/// The messages as prost-build derives them, which discard unknown fields: +/// what `sdk/tests/generated_messages.rs` compares the rewritten ones with. +const REFERENCE: &str = "sdk/tests/generated/prost_v1.rs"; const UNKNOWN_FIELDS_INIT: &str = "unknown_fields: Default::default(),"; fn main() -> Result<(), Box> { @@ -26,12 +31,6 @@ fn main() -> Result<(), Box> { .file_descriptor_set_path(&descriptor) .compile_well_known_types() .extern_path(".google.protobuf", "::pbjson_types"); - for message in HAND_WRITTEN { - config.extern_path( - format!(".apiextensions.fn.proto.v1.{message}"), - format!("crate::proto::state::{message}"), - ); - } tonic_prost_build::configure() .build_client(true) @@ -44,8 +43,9 @@ fn main() -> Result<(), Box> { .out_dir(tmp.path()) .build(&[".apiextensions"])?; - let out = root.join(OUT); - fs::create_dir_all(&out)?; + // prost-build names its file after the proto package, a keyword in it + // escaped, and pbjson adds `.serde` to that name. + let (mut prost, mut serde) = (None, None); for entry in fs::read_dir(tmp.path())? { let path = entry?.path(); let name = path @@ -53,31 +53,82 @@ fn main() -> Result<(), Box> { .unwrap_or_default() .to_string_lossy() .into_owned(); - let target = if name.ends_with(".serde.rs") { - "v1.serde.rs" + if name.ends_with(".serde.rs") { + serde = Some(fs::read_to_string(&path)?); } else if name.ends_with(".rs") { - "v1.rs" - } else { - continue; - }; - if target == "v1.serde.rs" { - let serde = init_unknown_fields(&fs::read_to_string(&path)?)?; - fs::write(out.join(target), serde)?; - } else { - fs::copy(&path, out.join(target))?; + prost = Some(fs::read_to_string(&path)?); } - println!("wrote {}", out.join(target).display()); } + let prost = prost.ok_or("prost-build wrote no .rs file")?; + let serde = serde.ok_or("pbjson-build wrote no .serde.rs file")?; + + let (header, types, services) = split(&prost); + let rewritten = messages::rewrite(types)?; + + let out = root.join(OUT); + fs::create_dir_all(&out)?; + write( + &out.join("v1.rs"), + &format!("{header}{}{services}", rewritten.source), + )?; + write( + &out.join("v1.serde.rs"), + &init_unknown_fields(&serde, &rewritten.messages)?, + )?; + let reference = root.join(REFERENCE); + fs::create_dir_all(reference.parent().expect("the reference is in a directory"))?; + write(&reference, &format!("{header}{types}"))?; fs::copy(&descriptor, out.join("fileset.bin"))?; println!("wrote {}", out.join("fileset.bin").display()); Ok(()) } -/// Makes the generated serde constructors of the hand-written messages -/// initialize `unknown_fields`, a field the descriptor does not have. -fn init_unknown_fields(serde: &str) -> Result> { +fn write(path: &Path, content: &str) -> Result<(), Box> { + fs::write(path, content)?; + println!("wrote {}", path.display()); + Ok(()) +} + +/// Splits what prost-build wrote into its leading comment, the messages and +/// enumerations, and the gRPC client and server modules tonic appends. Only +/// the middle part is rewritten: a parser keeps no plain comment, and the +/// service code has no message in it. +fn split(prost: &str) -> (&str, &str, &str) { + let header: usize = prost + .split_inclusive('\n') + .take_while(|line| line.starts_with("//") && !line.starts_with("///")) + .map(str::len) + .sum(); + let mut services = prost.len(); + let mut offset = 0; + let mut docs = None; + for line in prost.split_inclusive('\n') { + if line.starts_with("///") { + docs.get_or_insert(offset); + } else { + let service = line.starts_with("pub mod ") + && (line.trim_end().ends_with("_client {") + || line.trim_end().ends_with("_server {")); + if service { + services = docs.unwrap_or(offset); + break; + } + docs = None; + } + offset += line.len(); + } + ( + &prost[..header], + &prost[header..services], + &prost[services..], + ) +} + +/// Makes the generated serde constructor of every message initialize +/// `unknown_fields`, a field the descriptor does not have. +fn init_unknown_fields(serde: &str, messages: &[String]) -> Result> { let mut patched = serde.to_owned(); - for message in HAND_WRITTEN { + for message in messages { let constructor = format!("Ok({message} {{\n"); if patched.matches(&constructor).count() != 1 { return Err(format!("expected one serde constructor for {message}").into()); @@ -115,6 +166,20 @@ mod tests { }) "; + fn both() -> Vec { + vec!["State".to_string(), "Resource".to_string()] + } + + #[test] + fn split_cuts_at_the_comment_and_at_the_services() { + let prost = "// This file is @generated by prost-build.\n/// A message.\npub struct M {}\n/// Generated client implementations.\npub mod m_client {\n}\n/// Generated server implementations.\npub mod m_server {\n}\n"; + let (header, types, services) = split(prost); + assert_eq!(header, "// This file is @generated by prost-build.\n"); + assert_eq!(types, "/// A message.\npub struct M {}\n"); + assert!(services.starts_with("/// Generated client implementations.\npub mod m_client {")); + assert_eq!(split("pub struct M {}\n"), ("", "pub struct M {}\n", "")); + } + #[test] fn init_unknown_fields_extends_both_constructors() { let want = "\ @@ -127,11 +192,14 @@ mod tests { unknown_fields: Default::default(), }) "; - assert_eq!(init_unknown_fields(GENERATED).expect("patches"), want); + assert_eq!( + init_unknown_fields(GENERATED, &both()).expect("patches"), + want + ); } #[test] fn init_unknown_fields_fails_without_a_constructor() { - assert!(init_unknown_fields("Ok(State {\n})").is_err()); + assert!(init_unknown_fields("Ok(State {\n})", &both()).is_err()); } } diff --git a/codegen/src/messages.rs b/codegen/src/messages.rs new file mode 100644 index 0000000..f63b9d9 --- /dev/null +++ b/codegen/src/messages.rs @@ -0,0 +1,739 @@ +//! Rewrites the messages prost-build generates so that they keep unknown +//! fields. +//! +//! prost's `Message` derive skips a field it does not know, and nothing in +//! prost-build changes that (tokio-rs/prost#2). So prost-build still writes +//! every struct, with its names, types, docs and derives, and this pass +//! replaces the derive: each message gets an `unknown_fields` field and the +//! impls the derive would have produced, except that the fallback arm of +//! `merge_field` keeps the field's bytes and `encode_raw` writes them back. +//! +//! The pass reads the `#[prost(...)]` attribute of every field and knows the +//! kinds the function proto uses. A kind it does not know is an error naming +//! the field, never a guess: add the kind here and let +//! `sdk/tests/generated_messages.rs` hold it to prost's own derive. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::punctuated::Punctuated; +use syn::{Attribute, Expr, Fields, Ident, Item, ItemStruct, Lit, Meta, Path, Token}; + +/// The messages of a generated file, rewritten, and their names as the +/// generated serde code spells them. +pub struct Rewritten { + pub source: String, + pub messages: Vec, +} + +/// Rewrites every struct that derives `::prost::Message` in `prost`, the +/// part of prost-build's output that holds the messages and enumerations. +pub fn rewrite(prost: &str) -> Result { + let mut file = + syn::parse_file(prost).map_err(|e| format!("cannot parse prost's output: {e}"))?; + let mut messages = Vec::new(); + file.items = rewrite_items(std::mem::take(&mut file.items), "", &mut messages)?; + Ok(Rewritten { + source: prettyplease::unparse(&file), + messages, + }) +} + +fn rewrite_items( + items: Vec, + module: &str, + messages: &mut Vec, +) -> Result, String> { + let mut out = Vec::with_capacity(items.len()); + for item in items { + match item { + Item::Struct(mut message) if derives_message(&message) => { + let impls = rewrite_message(&mut message)?; + messages.push(format!("{module}{}", message.ident)); + out.push(Item::Struct(message)); + let impls: syn::File = syn::parse2(impls) + .map_err(|e| format!("the impls written for a message do not parse: {e}"))?; + out.extend(impls.items); + } + Item::Mod(mut nested) => { + if let Some((brace, items)) = nested.content.take() { + let path = format!("{module}{}::", nested.ident); + nested.content = Some((brace, rewrite_items(items, &path, messages)?)); + } + out.push(Item::Mod(nested)); + } + other => out.push(other), + } + } + Ok(out) +} + +fn derives_message(item: &ItemStruct) -> bool { + derives(item).iter().any(is_prost_message) +} + +fn derives(item: &ItemStruct) -> Vec { + item.attrs + .iter() + .filter(|attr| attr.path().is_ident("derive")) + .filter_map(|attr| { + attr.parse_args_with(Punctuated::::parse_terminated) + .ok() + }) + .flatten() + .collect() +} + +fn is_prost_message(path: &Path) -> bool { + let segments: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + segments == ["prost", "Message"] +} + +/// How often a field occurs. +#[derive(Clone, Copy, PartialEq)] +enum Label { + Plain, + Optional, + Repeated, +} + +/// The value of a map with string keys. +#[derive(Clone, Copy)] +enum MapValue { + String, + Bytes, + Message, +} + +/// The field kinds this pass writes code for. +enum Kind { + String(Label), + /// The field is an `i32`, with the enumeration it holds. + Enumeration(Path, Label), + Message(Label), + Map(MapValue), + /// The field is an `Option` of the enum prost derives `Oneof` for. + Oneof(Path), +} + +struct Field { + ident: Ident, + kind: Kind, + tags: Vec, +} + +/// Replaces the `Message` derive of one struct: strips what belongs to the +/// derive, adds `unknown_fields`, and returns the impls to put after it. +fn rewrite_message(message: &mut ItemStruct) -> Result { + let name = message.ident.clone(); + let Fields::Named(named) = &mut message.fields else { + return Err(format!("{name}: a message is a struct with named fields")); + }; + + let mut fields = Vec::new(); + for field in &mut named.named { + let ident = field.ident.clone().expect("a named field"); + let position = field + .attrs + .iter() + .position(|attr| attr.path().is_ident("prost")); + let Some(position) = position else { + return Err(format!("{name}.{ident}: no #[prost(...)] attribute")); + }; + let attr = field.attrs.remove(position); + fields.push(read_field(&name, ident, &attr)?); + } + named.named.push(syn::parse_quote! { + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields + }); + + // The derive gave the message Default and Debug. Default is derived + // (every field of a proto3 message defaults to its type's default) and + // Debug is written below. A message with unknown fields owns a buffer, + // so it cannot be Copy. + let kept: Vec = derives(message) + .into_iter() + .filter(|path| !is_prost_message(path) && !path.is_ident("Copy")) + .collect(); + message.attrs.retain(|attr| !attr.path().is_ident("derive")); + message + .attrs + .push(syn::parse_quote!(#[derive(#(#kept,)* Default)])); + + // Debug prints the fields in declaration order; the wire has them in + // tag order, a oneof at its lowest tag. + let debug: Vec = fields.iter().map(Field::debug).collect(); + let methods: Vec = fields.iter().filter_map(Field::methods).collect(); + fields.sort_by_key(|field| field.tags.iter().copied().min().unwrap_or(0)); + let encode = fields.iter().map(Field::encode); + let merge = fields.iter().map(Field::merge); + let encoded_len = fields.iter().map(Field::encoded_len); + + let methods = if methods.is_empty() { + quote!() + } else { + quote! { + impl #name { + #(#methods)* + } + } + }; + + Ok(quote! { + impl ::prost::Message for #name { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + #(#encode)* + self.unknown_fields.encode(buf); + } + + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(#name); + match tag { + #(#merge)* + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + + #[inline] + fn encoded_len(&self) -> usize { + 0 #(+ #encoded_len)* + self.unknown_fields.encoded_len() + } + + fn clear(&mut self) { + *self = Self::default(); + } + } + + impl ::core::fmt::Debug for #name { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(#name)) + #(#debug)* + .field("unknown_fields", &self.unknown_fields) + .finish() + } + } + + #methods + }) +} + +/// Reads one `#[prost(...)]` attribute as prost-build writes it. +fn read_field(message: &Ident, ident: Ident, attr: &Attribute) -> Result { + let unknown = || { + format!( + "{message}.{ident}: codegen does not write the field kind `{}` yet; add it to codegen/src/messages.rs", + quote!(#attr) + ) + }; + let metas = attr + .parse_args_with(Punctuated::::parse_terminated) + .map_err(|_| unknown())?; + + let (mut ty, mut label, mut tags) = (None, Label::Plain, Vec::new()); + for meta in &metas { + let word = meta + .path() + .get_ident() + .map(Ident::to_string) + .ok_or_else(unknown)?; + match (word.as_str(), meta) { + ("optional", Meta::Path(_)) => label = Label::Optional, + ("repeated", Meta::Path(_)) => label = Label::Repeated, + ("string" | "message", Meta::Path(_)) => ty = Some((word, String::new())), + ("enumeration" | "map" | "oneof", Meta::NameValue(_)) => { + ty = Some((word, string_of(meta).ok_or_else(unknown)?)); + } + ("tag" | "tags", Meta::NameValue(_)) => { + for tag in string_of(meta).ok_or_else(unknown)?.split(',') { + tags.push(tag.trim().parse::().map_err(|_| unknown())?); + } + } + _ => return Err(unknown()), + } + } + if tags.is_empty() { + return Err(unknown()); + } + + let path = |s: &str| syn::parse_str::(s).map_err(|_| unknown()); + let kind = match ( + ty.as_ref() + .map(|(word, value)| (word.as_str(), value.as_str())), + label, + ) { + (Some(("string", _)), Label::Plain | Label::Optional) => Kind::String(label), + (Some(("enumeration", of)), _) => Kind::Enumeration(path(of)?, label), + (Some(("message", _)), Label::Optional | Label::Repeated) => Kind::Message(label), + (Some(("map", "string, string")), Label::Plain) => Kind::Map(MapValue::String), + (Some(("map", "string, bytes")), Label::Plain) => Kind::Map(MapValue::Bytes), + (Some(("map", "string, message")), Label::Plain) => Kind::Map(MapValue::Message), + (Some(("oneof", of)), Label::Plain) => Kind::Oneof(path(of)?), + _ => return Err(unknown()), + }; + Ok(Field { ident, kind, tags }) +} + +fn string_of(meta: &Meta) -> Option { + let Meta::NameValue(pair) = meta else { + return None; + }; + let Expr::Lit(literal) = &pair.value else { + return None; + }; + let Lit::Str(value) = &literal.lit else { + return None; + }; + Some(value.value()) +} + +impl Field { + /// The tag of a field that is no oneof. + fn tag(&self) -> u32 { + self.tags[0] + } + + /// The statement that encodes the field, as prost's derive writes it. + fn encode(&self) -> TokenStream { + let (field, tag) = (&self.ident, self.tag()); + match &self.kind { + Kind::String(Label::Plain) => quote! { + if self.#field != "" { + ::prost::encoding::string::encode(#tag, &self.#field, buf); + } + }, + Kind::String(_) => quote! { + if let ::core::option::Option::Some(ref value) = self.#field { + ::prost::encoding::string::encode(#tag, value, buf); + } + }, + Kind::Enumeration(of, Label::Plain) => quote! { + if self.#field != #of::default() as i32 { + ::prost::encoding::int32::encode(#tag, &self.#field, buf); + } + }, + Kind::Enumeration(_, Label::Optional) => quote! { + if let ::core::option::Option::Some(ref value) = self.#field { + ::prost::encoding::int32::encode(#tag, value, buf); + } + }, + // proto3 packs a repeated enumeration. + Kind::Enumeration(_, Label::Repeated) => quote! { + ::prost::encoding::int32::encode_packed(#tag, &self.#field, buf); + }, + Kind::Message(Label::Repeated) => quote! { + for msg in &self.#field { + ::prost::encoding::message::encode(#tag, msg, buf); + } + }, + Kind::Message(_) => quote! { + if let Some(ref msg) = self.#field { + ::prost::encoding::message::encode(#tag, msg, buf); + } + }, + Kind::Map(value) => { + let value = value.module(); + quote! { + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::#value::encode, + ::prost::encoding::#value::encoded_len, + #tag, + &self.#field, + buf, + ); + } + } + Kind::Oneof(_) => quote! { + if let Some(ref oneof) = self.#field { + oneof.encode(buf) + } + }, + } + } + + /// The arm of `merge_field` that decodes the field. An error names the + /// message and the field, as prost's derive has it. + fn merge(&self) -> TokenStream { + let (field, tags) = (&self.ident, &self.tags); + let merge = match &self.kind { + Kind::String(Label::Plain) => quote! { + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + }, + Kind::String(_) => quote! { + ::prost::encoding::string::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + }, + Kind::Enumeration(_, Label::Plain) => quote! { + ::prost::encoding::int32::merge(wire_type, value, buf, ctx) + }, + Kind::Enumeration(_, Label::Optional) => quote! { + ::prost::encoding::int32::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + }, + Kind::Enumeration(_, Label::Repeated) => quote! { + ::prost::encoding::int32::merge_repeated(wire_type, value, buf, ctx) + }, + Kind::Message(Label::Repeated) => quote! { + ::prost::encoding::message::merge_repeated(wire_type, value, buf, ctx) + }, + Kind::Message(_) => quote! { + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + }, + // The wire type is checked here: hash_map::merge does not. + Kind::Map(value) => { + let value = value.module(); + quote! { + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::#value::merge, + value, + buf, + ctx, + ) + }) + } + } + Kind::Oneof(of) => quote! { + #of::merge(value, tag, wire_type, buf, ctx) + }, + }; + quote! { + #(#tags)|* => { + let value = &mut self.#field; + #merge.map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(#field)); + error + }) + } + } + } + + /// The expression that is the field's encoded length. + fn encoded_len(&self) -> TokenStream { + let (field, tag) = (&self.ident, self.tag()); + match &self.kind { + Kind::String(Label::Plain) => quote! { + if self.#field != "" { + ::prost::encoding::string::encoded_len(#tag, &self.#field) + } else { + 0 + } + }, + Kind::String(_) => quote! { + self.#field + .as_ref() + .map_or(0, |value| ::prost::encoding::string::encoded_len(#tag, value)) + }, + Kind::Enumeration(of, Label::Plain) => quote! { + if self.#field != #of::default() as i32 { + ::prost::encoding::int32::encoded_len(#tag, &self.#field) + } else { + 0 + } + }, + Kind::Enumeration(_, Label::Optional) => quote! { + self.#field + .as_ref() + .map_or(0, |value| ::prost::encoding::int32::encoded_len(#tag, value)) + }, + Kind::Enumeration(_, Label::Repeated) => quote! { + ::prost::encoding::int32::encoded_len_packed(#tag, &self.#field) + }, + Kind::Message(Label::Repeated) => quote! { + ::prost::encoding::message::encoded_len_repeated(#tag, &self.#field) + }, + Kind::Message(_) => quote! { + self.#field + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(#tag, msg)) + }, + Kind::Map(value) => { + let value = value.module(); + quote! { + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::#value::encoded_len, + #tag, + &self.#field, + ) + } + } + Kind::Oneof(of) => quote! { + self.#field.as_ref().map_or(0, #of::encoded_len) + }, + } + } + + /// The `.field(..)` call of `Debug`. An enumeration prints by variant + /// name, as prost's derive prints it. + fn debug(&self) -> TokenStream { + let field = &self.ident; + let by_name = quote!(crate::proto::unknown::enum_debug); + match &self.kind { + Kind::Enumeration(of, Label::Plain) => quote! { + .field(stringify!(#field), &#by_name::<#of>(&self.#field)) + }, + Kind::Enumeration(of, Label::Optional) => quote! { + .field(stringify!(#field), &self.#field.as_ref().map(#by_name::<#of>)) + }, + Kind::Enumeration(of, Label::Repeated) => quote! { + .field( + stringify!(#field), + &self.#field.iter().map(#by_name::<#of>).collect::<::prost::alloc::vec::Vec<_>>(), + ) + }, + _ => quote!(.field(stringify!(#field), &self.#field)), + } + } + + /// The accessors prost's derive adds for an enumeration and for an + /// optional string, under the names and docs it gives them. + fn methods(&self) -> Option { + let field = &self.ident; + let name = field.to_string(); + let name = name.strip_prefix("r#").unwrap_or(&name); + let set = format_ident!("set_{name}"); + let set_doc = format!("Sets `{name}` to the provided enum value."); + Some(match &self.kind { + Kind::Enumeration(of, Label::Plain) => { + let get_doc = format!( + "Returns the enum value of `{name}`, or the default if the field is set to an invalid enum value." + ); + quote! { + #[doc = #get_doc] + pub fn #field(&self) -> #of { + ::core::convert::TryFrom::try_from(self.#field).unwrap_or(#of::default()) + } + + #[doc = #set_doc] + pub fn #set(&mut self, value: #of) { + self.#field = value as i32; + } + } + } + Kind::Enumeration(of, Label::Optional) => { + let get_doc = format!( + "Returns the enum value of `{name}`, or the default if the field is unset or set to an invalid enum value." + ); + quote! { + #[doc = #get_doc] + pub fn #field(&self) -> #of { + self.#field + .and_then(|x| { + let result: ::core::result::Result<#of, _> = + ::core::convert::TryFrom::try_from(x); + result.ok() + }) + .unwrap_or(#of::default()) + } + + #[doc = #set_doc] + pub fn #set(&mut self, value: #of) { + self.#field = ::core::option::Option::Some(value as i32); + } + } + } + Kind::Enumeration(of, Label::Repeated) => { + let push = format_ident!("push_{name}"); + let iter_doc = format!( + "Returns an iterator which yields the valid enum values contained in `{name}`." + ); + let push_doc = format!("Appends the provided enum value to `{name}`."); + quote! { + #[doc = #iter_doc] + pub fn #field( + &self, + ) -> ::core::iter::FilterMap< + ::core::iter::Cloned<::core::slice::Iter<'_, i32>>, + fn(i32) -> ::core::option::Option<#of>, + > { + self.#field.iter().cloned().filter_map(|x| { + let result: ::core::result::Result<#of, _> = + ::core::convert::TryFrom::try_from(x); + result.ok() + }) + } + + #[doc = #push_doc] + pub fn #push(&mut self, value: #of) { + self.#field.push(value as i32); + } + } + } + Kind::String(Label::Optional) => { + let get_doc = format!( + "Returns the value of `{name}`, or the default value if `{name}` is unset." + ); + quote! { + #[doc = #get_doc] + pub fn #field(&self) -> &str { + match self.#field { + ::core::option::Option::Some(ref val) => &val[..], + ::core::option::Option::None => "", + } + } + } + } + _ => return None, + }) + } +} + +impl MapValue { + /// The module of `prost::encoding` that encodes the value. + fn module(self) -> Ident { + match self { + MapValue::String => format_ident!("string"), + MapValue::Bytes => format_ident!("bytes"), + MapValue::Message => format_ident!("message"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PROST: &str = r#" +/// A message. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Meta { + /// Its tag. + #[prost(string, tag = "1")] + pub tag: ::prost::alloc::string::String, + #[prost(enumeration = "Kind", optional, tag = "2")] + pub kind: ::core::option::Option, + #[prost(oneof = "meta::Source", tags = "4, 3")] + pub source: ::core::option::Option, +} +/// Nested message and enum types in `Meta`. +pub mod meta { + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Source { + #[prost(string, tag = "3")] + Name(::prost::alloc::string::String), + #[prost(message, tag = "4")] + Inner(Inner), + } + #[derive(Clone, Copy, PartialEq, ::prost::Message)] + pub struct Inner {} +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Kind { + Unspecified = 0, +} +"#; + + #[test] + fn a_message_keeps_what_prost_wrote_but_the_derive() { + let got = rewrite(PROST).expect("rewrites"); + assert_eq!(got.messages, ["Meta", "meta::Inner"]); + let source = got.source; + + // The struct: its docs and other derives stay, the prost attributes + // go, and the field is added. + assert!(source.contains("/// A message.\n#[allow(clippy::all)]\n#[derive(Clone, PartialEq, Eq, Hash, Default)]\npub struct Meta {"), "{source}"); + assert!( + source.contains(" /// Its tag.\n pub tag: ::prost::alloc::string::String,\n"), + "{source}" + ); + assert!(source.contains(" /// Fields this SDK's proto does not know, kept and re-encoded.\n pub unknown_fields: crate::proto::UnknownFields,\n"), "{source}"); + assert!(!source.contains("::prost::Message)]"), "{source}"); + assert!( + !source.contains("#[prost(string, tag = \"1\")]\n pub tag"), + "{source}" + ); + + // The impls: the fallback arm keeps the field, a oneof takes every + // tag it has, the accessors are back. + assert!( + source.contains("impl ::prost::Message for Meta {"), + "{source}" + ); + assert!( + source.contains("_ => self.unknown_fields.merge(tag, wire_type, buf, ctx),"), + "{source}" + ); + assert!(source.contains("4u32 | 3u32 => {"), "{source}"); + assert!( + source.contains("pub fn set_kind(&mut self, value: Kind) {"), + "{source}" + ); + + // What is no message stays as prost wrote it, a nested message + // loses Copy, and the result is a file rustc can read. + assert!( + source.contains("#[derive(Clone, PartialEq, ::prost::Oneof)]\n pub enum Source {"), + "{source}" + ); + assert!( + source.contains(" #[prost(string, tag = \"3\")]\n Name("), + "{source}" + ); + assert!( + source.contains(" #[derive(Clone, PartialEq, Default)]\n pub struct Inner {"), + "{source}" + ); + assert!( + source.contains("::prost::Enumeration)]\n#[repr(i32)]\npub enum Kind {"), + "{source}" + ); + syn::parse_file(&source).expect("the rewritten file parses"); + } + + #[test] + fn fields_are_encoded_in_tag_order() { + let source = rewrite(PROST).expect("rewrites").source; + let encode = &source[source.find("fn encode_raw").expect("encode_raw")..]; + let tag = encode.find("encode(1u32").expect("tag 1"); + let kind = encode.find("encode(2u32").expect("tag 2"); + let oneof = encode.find("oneof.encode(buf)").expect("the oneof"); + let unknown = encode + .find("self.unknown_fields.encode(buf)") + .expect("the unknown fields"); + assert!(tag < kind && kind < oneof && oneof < unknown); + } + + #[test] + fn a_field_kind_the_pass_does_not_know_is_an_error_naming_it() { + let prost = r#" +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Meta { + #[prost(bool, tag = "1")] + pub ready: bool, +} +"#; + let error = rewrite(prost).err().expect("refused"); + assert_eq!( + error, + "Meta.ready: codegen does not write the field kind `# [prost (bool , tag = \"1\")]` yet; add it to codegen/src/messages.rs" + ); + } +} diff --git a/sdk/src/generated/v1.rs b/sdk/src/generated/v1.rs index b8bc1d0..526c110 100644 --- a/sdk/src/generated/v1.rs +++ b/sdk/src/generated/v1.rs @@ -1,16 +1,14 @@ // This file is @generated by prost-build. /// A RunFunctionRequest requests that the function be run. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct RunFunctionRequest { /// Metadata pertaining to this request. - #[prost(message, optional, tag = "1")] pub meta: ::core::option::Option, /// The observed state prior to invocation of a function pipeline. State passed /// to each function is fresh as of the time the pipeline was invoked, not as /// of the time each function was invoked. - #[prost(message, optional, tag = "2")] - pub observed: ::core::option::Option, + pub observed: ::core::option::Option, /// Desired state according to a function pipeline. The state passed to a /// particular function may have been accumulated by previous functions in the /// pipeline. @@ -21,17 +19,14 @@ pub struct RunFunctionRequest { /// likely not what you want to do. Leaving out fields that had been returned /// as desired before will result in them being deleted from the objects in the /// cluster. - #[prost(message, optional, tag = "3")] - pub desired: ::core::option::Option, + pub desired: ::core::option::Option, /// Optional input specific to this function invocation. A JSON representation /// of the 'input' block of the relevant entry in a function pipeline. - #[prost(message, optional, tag = "4")] pub input: ::core::option::Option<::pbjson_types::Struct>, /// Optional context. Crossplane may pass arbitrary contextual information to a /// function. A function may also return context in its RunFunctionResponse, /// and that context will be passed to subsequent functions. Crossplane /// discards all context returned by the last function in the pipeline. - #[prost(message, optional, tag = "5")] pub context: ::core::option::Option<::pbjson_types::Struct>, /// Optional resources that the function specified in its requirements. Note /// that resources is a map to Resources, plural. The map key corresponds to @@ -42,14 +37,12 @@ pub struct RunFunctionRequest { /// extra_resources in its requirements. /// /// Deprecated: Use required_resources instead. - #[prost(map = "string, message", tag = "6")] pub extra_resources: ::std::collections::HashMap< ::prost::alloc::string::String, Resources, >, /// Optional credentials that this function may use to communicate with an /// external system. - #[prost(map = "string, message", tag = "7")] pub credentials: ::std::collections::HashMap< ::prost::alloc::string::String, Credentials, @@ -61,7 +54,6 @@ pub struct RunFunctionRequest { /// the map key to an empty Resources message to indicate that it attempted to /// satisfy the request. This field is only populated when the function uses /// resources in its requirements. - #[prost(map = "string, message", tag = "8")] pub required_resources: ::std::collections::HashMap< ::prost::alloc::string::String, Resources, @@ -71,19 +63,345 @@ pub struct RunFunctionRequest { /// field. If a function requested a schema that could not be found, Crossplane /// sets the map key to an empty Schema message to indicate that it attempted /// to satisfy the request. - #[prost(map = "string, message", tag = "9")] pub required_schemas: ::std::collections::HashMap< ::prost::alloc::string::String, Schema, >, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for RunFunctionRequest { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref msg) = self.meta { + ::prost::encoding::message::encode(1u32, msg, buf); + } + if let Some(ref msg) = self.observed { + ::prost::encoding::message::encode(2u32, msg, buf); + } + if let Some(ref msg) = self.desired { + ::prost::encoding::message::encode(3u32, msg, buf); + } + if let Some(ref msg) = self.input { + ::prost::encoding::message::encode(4u32, msg, buf); + } + if let Some(ref msg) = self.context { + ::prost::encoding::message::encode(5u32, msg, buf); + } + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 6u32, + &self.extra_resources, + buf, + ); + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 7u32, + &self.credentials, + buf, + ); + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 8u32, + &self.required_resources, + buf, + ); + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 9u32, + &self.required_schemas, + buf, + ); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(RunFunctionRequest); + match tag { + 1u32 => { + let value = &mut self.meta; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(meta)); + error + }) + } + 2u32 => { + let value = &mut self.observed; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(observed)); + error + }) + } + 3u32 => { + let value = &mut self.desired; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(desired)); + error + }) + } + 4u32 => { + let value = &mut self.input; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(input)); + error + }) + } + 5u32 => { + let value = &mut self.context; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(context)); + error + }) + } + 6u32 => { + let value = &mut self.extra_resources; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(extra_resources)); + error + }) + } + 7u32 => { + let value = &mut self.credentials; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(credentials)); + error + }) + } + 8u32 => { + let value = &mut self.required_resources; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(required_resources)); + error + }) + } + 9u32 => { + let value = &mut self.required_schemas; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(required_schemas)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + self + .meta + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(1u32, msg)) + + self + .observed + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(2u32, msg)) + + self + .desired + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(3u32, msg)) + + self + .input + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(4u32, msg)) + + self + .context + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(5u32, msg)) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 6u32, + &self.extra_resources, + ) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 7u32, + &self.credentials, + ) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 8u32, + &self.required_resources, + ) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 9u32, + &self.required_schemas, + ) + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for RunFunctionRequest { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(RunFunctionRequest)) + .field(stringify!(meta), &self.meta) + .field(stringify!(observed), &self.observed) + .field(stringify!(desired), &self.desired) + .field(stringify!(input), &self.input) + .field(stringify!(context), &self.context) + .field(stringify!(extra_resources), &self.extra_resources) + .field(stringify!(credentials), &self.credentials) + .field(stringify!(required_resources), &self.required_resources) + .field(stringify!(required_schemas), &self.required_schemas) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// Credentials that a function may use to communicate with an external system. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct Credentials { /// Source of the credentials. - #[prost(oneof = "credentials::Source", tags = "1")] pub source: ::core::option::Option, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Credentials { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref oneof) = self.source { + oneof.encode(buf) + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Credentials); + match tag { + 1u32 => { + let value = &mut self.source; + credentials::Source::merge(value, tag, wire_type, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(source)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + self.source.as_ref().map_or(0, credentials::Source::encoded_len) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Credentials { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Credentials)) + .field(stringify!(source), &self.source) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// Nested message and enum types in `Credentials`. pub mod credentials { @@ -98,27 +416,139 @@ pub mod credentials { } /// CredentialData loaded by Crossplane, for example from a Secret. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct CredentialData { - #[prost(map = "string, bytes", tag = "1")] pub data: ::std::collections::HashMap< ::prost::alloc::string::String, ::prost::alloc::vec::Vec, >, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for CredentialData { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::bytes::encode, + ::prost::encoding::bytes::encoded_len, + 1u32, + &self.data, + buf, + ); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(CredentialData); + match tag { + 1u32 => { + let value = &mut self.data; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::bytes::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(data)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::bytes::encoded_len, + 1u32, + &self.data, + ) + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for CredentialData { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(CredentialData)) + .field(stringify!(data), &self.data) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// Resources represents the state of several Crossplane resources. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct Resources { - #[prost(message, repeated, tag = "1")] - pub items: ::prost::alloc::vec::Vec, + pub items: ::prost::alloc::vec::Vec, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Resources { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + for msg in &self.items { + ::prost::encoding::message::encode(1u32, msg, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Resources); + match tag { + 1u32 => { + let value = &mut self.items; + ::prost::encoding::message::merge_repeated(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(items)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + ::prost::encoding::message::encoded_len_repeated(1u32, &self.items) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Resources { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Resources)) + .field(stringify!(items), &self.items) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// A RunFunctionResponse contains the result of a function run. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct RunFunctionResponse { /// Metadata pertaining to this response. - #[prost(message, optional, tag = "1")] pub meta: ::core::option::Option, /// Desired state according to a function pipeline. functions may add desired /// state, and may mutate or delete any part of the desired state they are @@ -131,111 +561,722 @@ pub struct RunFunctionResponse { /// likely not what you want to do. Leaving out fields that had been returned /// as desired before will result in them being deleted from the objects in the /// cluster. - #[prost(message, optional, tag = "2")] - pub desired: ::core::option::Option, + pub desired: ::core::option::Option, /// Results of the function run. Results are used for observability purposes. - #[prost(message, repeated, tag = "3")] pub results: ::prost::alloc::vec::Vec, /// Optional context to be passed to the next function in the pipeline as part /// of the RunFunctionRequest. Dropped on the last function in the pipeline. - #[prost(message, optional, tag = "4")] pub context: ::core::option::Option<::pbjson_types::Struct>, /// Requirements that must be satisfied for this function to run successfully. - #[prost(message, optional, tag = "5")] pub requirements: ::core::option::Option, /// Status conditions to be applied to the XR. Conditions may also optionally /// be applied to the XR's associated claim. /// /// Conditions are only used for composition. They're ignored by Operations. - #[prost(message, repeated, tag = "6")] pub conditions: ::prost::alloc::vec::Vec, /// Optional output specific to this function invocation. /// /// Only Operations use function output. XRs will discard any function output. - #[prost(message, optional, tag = "7")] pub output: ::core::option::Option<::pbjson_types::Struct>, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for RunFunctionResponse { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref msg) = self.meta { + ::prost::encoding::message::encode(1u32, msg, buf); + } + if let Some(ref msg) = self.desired { + ::prost::encoding::message::encode(2u32, msg, buf); + } + for msg in &self.results { + ::prost::encoding::message::encode(3u32, msg, buf); + } + if let Some(ref msg) = self.context { + ::prost::encoding::message::encode(4u32, msg, buf); + } + if let Some(ref msg) = self.requirements { + ::prost::encoding::message::encode(5u32, msg, buf); + } + for msg in &self.conditions { + ::prost::encoding::message::encode(6u32, msg, buf); + } + if let Some(ref msg) = self.output { + ::prost::encoding::message::encode(7u32, msg, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(RunFunctionResponse); + match tag { + 1u32 => { + let value = &mut self.meta; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(meta)); + error + }) + } + 2u32 => { + let value = &mut self.desired; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(desired)); + error + }) + } + 3u32 => { + let value = &mut self.results; + ::prost::encoding::message::merge_repeated(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(results)); + error + }) + } + 4u32 => { + let value = &mut self.context; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(context)); + error + }) + } + 5u32 => { + let value = &mut self.requirements; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(requirements)); + error + }) + } + 6u32 => { + let value = &mut self.conditions; + ::prost::encoding::message::merge_repeated(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(conditions)); + error + }) + } + 7u32 => { + let value = &mut self.output; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(output)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + self + .meta + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(1u32, msg)) + + self + .desired + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(2u32, msg)) + + ::prost::encoding::message::encoded_len_repeated(3u32, &self.results) + + self + .context + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(4u32, msg)) + + self + .requirements + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(5u32, msg)) + + ::prost::encoding::message::encoded_len_repeated(6u32, &self.conditions) + + self + .output + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(7u32, msg)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for RunFunctionResponse { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(RunFunctionResponse)) + .field(stringify!(meta), &self.meta) + .field(stringify!(desired), &self.desired) + .field(stringify!(results), &self.results) + .field(stringify!(context), &self.context) + .field(stringify!(requirements), &self.requirements) + .field(stringify!(conditions), &self.conditions) + .field(stringify!(output), &self.output) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// RequestMeta contains metadata pertaining to a RunFunctionRequest. #[allow(clippy::all)] -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +#[derive(Clone, PartialEq, Eq, Hash, Default)] pub struct RequestMeta { /// An opaque string identifying a request. Requests with identical tags will /// be otherwise identical. - #[prost(string, tag = "1")] pub tag: ::prost::alloc::string::String, /// Capabilities supported by this version of Crossplane. Functions may use /// this to determine whether Crossplane will honor certain fields in their /// response, or populate certain fields in their request. - #[prost(enumeration = "Capability", repeated, tag = "2")] pub capabilities: ::prost::alloc::vec::Vec, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for RequestMeta { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.tag != "" { + ::prost::encoding::string::encode(1u32, &self.tag, buf); + } + ::prost::encoding::int32::encode_packed(2u32, &self.capabilities, buf); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(RequestMeta); + match tag { + 1u32 => { + let value = &mut self.tag; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(tag)); + error + }) + } + 2u32 => { + let value = &mut self.capabilities; + ::prost::encoding::int32::merge_repeated(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(capabilities)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.tag != "" { + ::prost::encoding::string::encoded_len(1u32, &self.tag) + } else { + 0 + } + ::prost::encoding::int32::encoded_len_packed(2u32, &self.capabilities) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for RequestMeta { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(RequestMeta)) + .field(stringify!(tag), &self.tag) + .field( + stringify!(capabilities), + &self + .capabilities + .iter() + .map(crate::proto::unknown::enum_debug::) + .collect::<::prost::alloc::vec::Vec<_>>(), + ) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +impl RequestMeta { + ///Returns an iterator which yields the valid enum values contained in `capabilities`. + pub fn capabilities( + &self, + ) -> ::core::iter::FilterMap< + ::core::iter::Cloned<::core::slice::Iter<'_, i32>>, + fn(i32) -> ::core::option::Option, + > { + self.capabilities + .iter() + .cloned() + .filter_map(|x| { + let result: ::core::result::Result = ::core::convert::TryFrom::try_from( + x, + ); + result.ok() + }) + } + ///Appends the provided enum value to `capabilities`. + pub fn push_capabilities(&mut self, value: Capability) { + self.capabilities.push(value as i32); + } } /// Requirements that must be satisfied for a function to run successfully. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct Requirements { /// Resources that this function requires. The map key uniquely identifies the /// group of resources. /// /// Deprecated: Use resources instead. - #[prost(map = "string, message", tag = "1")] pub extra_resources: ::std::collections::HashMap< ::prost::alloc::string::String, ResourceSelector, >, /// Resources that this function requires. The map key uniquely identifies the /// group of resources. - #[prost(map = "string, message", tag = "2")] pub resources: ::std::collections::HashMap< ::prost::alloc::string::String, ResourceSelector, >, /// Schemas that this function requires. The map key uniquely identifies the /// schema request. - #[prost(map = "string, message", tag = "3")] pub schemas: ::std::collections::HashMap< ::prost::alloc::string::String, SchemaSelector, >, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Requirements { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 1u32, + &self.extra_resources, + buf, + ); + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 2u32, + &self.resources, + buf, + ); + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 3u32, + &self.schemas, + buf, + ); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Requirements); + match tag { + 1u32 => { + let value = &mut self.extra_resources; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(extra_resources)); + error + }) + } + 2u32 => { + let value = &mut self.resources; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(resources)); + error + }) + } + 3u32 => { + let value = &mut self.schemas; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(schemas)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 1u32, + &self.extra_resources, + ) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 2u32, + &self.resources, + ) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 3u32, + &self.schemas, + ) + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Requirements { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Requirements)) + .field(stringify!(extra_resources), &self.extra_resources) + .field(stringify!(resources), &self.resources) + .field(stringify!(schemas), &self.schemas) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// SchemaSelector identifies a resource kind whose OpenAPI schema is requested. #[allow(clippy::all)] -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +#[derive(Clone, PartialEq, Eq, Hash, Default)] pub struct SchemaSelector { /// API version of the resource kind, e.g. "example.org/v1". - #[prost(string, tag = "1")] pub api_version: ::prost::alloc::string::String, /// Kind of resource, e.g. "MyResource". - #[prost(string, tag = "2")] pub kind: ::prost::alloc::string::String, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for SchemaSelector { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.api_version != "" { + ::prost::encoding::string::encode(1u32, &self.api_version, buf); + } + if self.kind != "" { + ::prost::encoding::string::encode(2u32, &self.kind, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(SchemaSelector); + match tag { + 1u32 => { + let value = &mut self.api_version; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(api_version)); + error + }) + } + 2u32 => { + let value = &mut self.kind; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(kind)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.api_version != "" { + ::prost::encoding::string::encoded_len(1u32, &self.api_version) + } else { + 0 + } + + if self.kind != "" { + ::prost::encoding::string::encoded_len(2u32, &self.kind) + } else { + 0 + } + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for SchemaSelector { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(SchemaSelector)) + .field(stringify!(api_version), &self.api_version) + .field(stringify!(kind), &self.kind) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// Schema represents the OpenAPI schema for a resource kind. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct Schema { /// The OpenAPI v3 schema of the resource kind as unstructured JSON. /// For CRDs this is the spec.versions\[\].schema.openAPIV3Schema field. /// Empty if Crossplane could not find a schema for the requested kind. - #[prost(message, optional, tag = "1")] pub openapi_v3: ::core::option::Option<::pbjson_types::Struct>, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Schema { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref msg) = self.openapi_v3 { + ::prost::encoding::message::encode(1u32, msg, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Schema); + match tag { + 1u32 => { + let value = &mut self.openapi_v3; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(openapi_v3)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + self + .openapi_v3 + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(1u32, msg)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Schema { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Schema)) + .field(stringify!(openapi_v3), &self.openapi_v3) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// ResourceSelector selects a group of resources, either by name or by label. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct ResourceSelector { /// API version of resources to select. - #[prost(string, tag = "1")] pub api_version: ::prost::alloc::string::String, /// Kind of resources to select. - #[prost(string, tag = "2")] pub kind: ::prost::alloc::string::String, /// Match resources in this namespace. Omit namespace to match cluster scoped /// resources, or to match namespaced resources by labels across all /// namespaces. - #[prost(string, optional, tag = "5")] pub namespace: ::core::option::Option<::prost::alloc::string::String>, /// Resources to match. - #[prost(oneof = "resource_selector::Match", tags = "3, 4")] pub r#match: ::core::option::Option, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for ResourceSelector { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.api_version != "" { + ::prost::encoding::string::encode(1u32, &self.api_version, buf); + } + if self.kind != "" { + ::prost::encoding::string::encode(2u32, &self.kind, buf); + } + if let Some(ref oneof) = self.r#match { + oneof.encode(buf) + } + if let ::core::option::Option::Some(ref value) = self.namespace { + ::prost::encoding::string::encode(5u32, value, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(ResourceSelector); + match tag { + 1u32 => { + let value = &mut self.api_version; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(api_version)); + error + }) + } + 2u32 => { + let value = &mut self.kind; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(kind)); + error + }) + } + 3u32 | 4u32 => { + let value = &mut self.r#match; + resource_selector::Match::merge(value, tag, wire_type, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(r#match)); + error + }) + } + 5u32 => { + let value = &mut self.namespace; + ::prost::encoding::string::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(namespace)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.api_version != "" { + ::prost::encoding::string::encoded_len(1u32, &self.api_version) + } else { + 0 + } + + if self.kind != "" { + ::prost::encoding::string::encoded_len(2u32, &self.kind) + } else { + 0 + } + self.r#match.as_ref().map_or(0, resource_selector::Match::encoded_len) + + self + .namespace + .as_ref() + .map_or(0, |value| ::prost::encoding::string::encoded_len(5u32, value)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for ResourceSelector { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(ResourceSelector)) + .field(stringify!(api_version), &self.api_version) + .field(stringify!(kind), &self.kind) + .field(stringify!(namespace), &self.namespace) + .field(stringify!(r#match), &self.r#match) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +impl ResourceSelector { + ///Returns the value of `namespace`, or the default value if `namespace` is unset. + pub fn namespace(&self) -> &str { + match self.namespace { + ::core::option::Option::Some(ref val) => &val[..], + ::core::option::Option::None => "", + } + } } /// Nested message and enum types in `ResourceSelector`. pub mod resource_selector { @@ -253,73 +1294,789 @@ pub mod resource_selector { } /// MatchLabels defines a set of labels to match resources against. #[allow(clippy::all)] -#[derive(Clone, PartialEq, ::prost::Message)] +#[derive(Clone, PartialEq, Default)] pub struct MatchLabels { - #[prost(map = "string, string", tag = "1")] pub labels: ::std::collections::HashMap< ::prost::alloc::string::String, ::prost::alloc::string::String, >, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for MatchLabels { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + 1u32, + &self.labels, + buf, + ); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(MatchLabels); + match tag { + 1u32 => { + let value = &mut self.labels; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::string::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(labels)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::string::encoded_len, + 1u32, + &self.labels, + ) + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for MatchLabels { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(MatchLabels)) + .field(stringify!(labels), &self.labels) + .field("unknown_fields", &self.unknown_fields) + .finish() + } } /// ResponseMeta contains metadata pertaining to a RunFunctionResponse. #[allow(clippy::all)] -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +#[derive(Clone, PartialEq, Eq, Hash, Default)] pub struct ResponseMeta { /// An opaque string identifying the content of the request. Must match the /// meta.tag of the corresponding RunFunctionRequest. - #[prost(string, tag = "1")] pub tag: ::prost::alloc::string::String, /// Time-to-live of this response. Crossplane will call the function again when /// the TTL expires. Crossplane may cache the response to avoid calling the /// function again until the TTL expires. - #[prost(message, optional, tag = "2")] pub ttl: ::core::option::Option<::pbjson_types::Duration>, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for ResponseMeta { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.tag != "" { + ::prost::encoding::string::encode(1u32, &self.tag, buf); + } + if let Some(ref msg) = self.ttl { + ::prost::encoding::message::encode(2u32, msg, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(ResponseMeta); + match tag { + 1u32 => { + let value = &mut self.tag; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(tag)); + error + }) + } + 2u32 => { + let value = &mut self.ttl; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(ttl)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.tag != "" { + ::prost::encoding::string::encoded_len(1u32, &self.tag) + } else { + 0 + } + + self + .ttl + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(2u32, msg)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for ResponseMeta { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(ResponseMeta)) + .field(stringify!(tag), &self.tag) + .field(stringify!(ttl), &self.ttl) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +/// State of the XR (XR) and any resources. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Default)] +pub struct State { + /// The state of the XR (XR). + pub composite: ::core::option::Option, + /// The state of any other resources. In composition functions these are the + /// composed resources. In operation functions they're arbitrary resources that + /// the operation wants to create or update. + pub resources: ::std::collections::HashMap<::prost::alloc::string::String, Resource>, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for State { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref msg) = self.composite { + ::prost::encoding::message::encode(1u32, msg, buf); + } + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encode, + ::prost::encoding::message::encoded_len, + 2u32, + &self.resources, + buf, + ); + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(State); + match tag { + 1u32 => { + let value = &mut self.composite; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(composite)); + error + }) + } + 2u32 => { + let value = &mut self.resources; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::message::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(resources)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + self + .composite + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(1u32, msg)) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::message::encoded_len, + 2u32, + &self.resources, + ) + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for State { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(State)) + .field(stringify!(composite), &self.composite) + .field(stringify!(resources), &self.resources) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +/// A Resource represents the state of a Kubernetes resource. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Default)] +pub struct Resource { + /// The JSON representation of the resource. + /// + /// * Crossplane will set this field in a RunFunctionRequest to the entire + /// observed state of a resource - including its metadata, spec, and status. + /// + /// * A function should set this field in a RunFunctionRequest to communicate + /// the desired state of the resource. + /// + /// * A function may only specify the desired status of a XR - not its metadata + /// or spec. A function should not return desired metadata or spec for a XR. + /// This will be ignored. + /// + /// * A function may not specify the desired status of any other resource - + /// e.g. composed resources. It may only specify their metadata and spec. + /// Status will be ignored. + pub resource: ::core::option::Option<::pbjson_types::Struct>, + /// The resource's connection details. + /// + /// * Crossplane will set this field in a RunFunctionRequest to communicate the + /// the observed connection details of a composite or composed resource. + /// + /// * A function should set this field in a RunFunctionResponse to indicate the + /// desired connection details of legacy XRs. For modern XRs, this will be ignored. + /// + /// * A function should not set this field in a RunFunctionResponse to indicate + /// the desired connection details of a composed resource. This will be + /// ignored. + /// + /// Connection details are only used for composition. They're ignored by + /// Operations. + pub connection_details: ::std::collections::HashMap< + ::prost::alloc::string::String, + ::prost::alloc::vec::Vec, + >, + /// Ready indicates whether the resource should be considered ready. + /// + /// * Crossplane will never set this field in a RunFunctionRequest. + /// + /// * A function should set this field to READY_TRUE in a RunFunctionResponse + /// to indicate that a desired resource is ready. + /// + /// * A function should set this field to READY_TRUE in a RunFunctionResponse + /// to indicate that a desired XR is ready. This overwrites the standard + /// readiness detection that determines the ready state of the composite by the + /// ready state of the composed resources. + /// + /// Ready is only used for composition. It's ignored by Operations. + pub ready: i32, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Resource { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if let Some(ref msg) = self.resource { + ::prost::encoding::message::encode(1u32, msg, buf); + } + ::prost::encoding::hash_map::encode( + ::prost::encoding::string::encode, + ::prost::encoding::string::encoded_len, + ::prost::encoding::bytes::encode, + ::prost::encoding::bytes::encoded_len, + 2u32, + &self.connection_details, + buf, + ); + if self.ready != Ready::default() as i32 { + ::prost::encoding::int32::encode(3u32, &self.ready, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Resource); + match tag { + 1u32 => { + let value = &mut self.resource; + ::prost::encoding::message::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(resource)); + error + }) + } + 2u32 => { + let value = &mut self.connection_details; + ::prost::encoding::check_wire_type( + ::prost::encoding::WireType::LengthDelimited, + wire_type, + ) + .and_then(|()| { + ::prost::encoding::hash_map::merge( + ::prost::encoding::string::merge, + ::prost::encoding::bytes::merge, + value, + buf, + ctx, + ) + }) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(connection_details)); + error + }) + } + 3u32 => { + let value = &mut self.ready; + ::prost::encoding::int32::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(ready)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + self + .resource + .as_ref() + .map_or(0, |msg| ::prost::encoding::message::encoded_len(1u32, msg)) + + ::prost::encoding::hash_map::encoded_len( + ::prost::encoding::string::encoded_len, + ::prost::encoding::bytes::encoded_len, + 2u32, + &self.connection_details, + ) + + if self.ready != Ready::default() as i32 { + ::prost::encoding::int32::encoded_len(3u32, &self.ready) + } else { + 0 + } + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Resource { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Resource)) + .field(stringify!(resource), &self.resource) + .field(stringify!(connection_details), &self.connection_details) + .field( + stringify!(ready), + &crate::proto::unknown::enum_debug::(&self.ready), + ) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +impl Resource { + ///Returns the enum value of `ready`, or the default if the field is set to an invalid enum value. + pub fn ready(&self) -> Ready { + ::core::convert::TryFrom::try_from(self.ready).unwrap_or(Ready::default()) + } + ///Sets `ready` to the provided enum value. + pub fn set_ready(&mut self, value: Ready) { + self.ready = value as i32; + } } /// A Result of running a function. #[allow(clippy::all)] -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +#[derive(Clone, PartialEq, Eq, Hash, Default)] pub struct Result { /// Severity of this result. - #[prost(enumeration = "Severity", tag = "1")] pub severity: i32, /// Human-readable details about the result. - #[prost(string, tag = "2")] pub message: ::prost::alloc::string::String, /// Optional PascalCase, machine-readable reason for this result. If omitted, /// the value will be ComposeResources. - #[prost(string, optional, tag = "3")] pub reason: ::core::option::Option<::prost::alloc::string::String>, /// The resources this result targets. - #[prost(enumeration = "Target", optional, tag = "4")] pub target: ::core::option::Option, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Result { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.severity != Severity::default() as i32 { + ::prost::encoding::int32::encode(1u32, &self.severity, buf); + } + if self.message != "" { + ::prost::encoding::string::encode(2u32, &self.message, buf); + } + if let ::core::option::Option::Some(ref value) = self.reason { + ::prost::encoding::string::encode(3u32, value, buf); + } + if let ::core::option::Option::Some(ref value) = self.target { + ::prost::encoding::int32::encode(4u32, value, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Result); + match tag { + 1u32 => { + let value = &mut self.severity; + ::prost::encoding::int32::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(severity)); + error + }) + } + 2u32 => { + let value = &mut self.message; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(message)); + error + }) + } + 3u32 => { + let value = &mut self.reason; + ::prost::encoding::string::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(reason)); + error + }) + } + 4u32 => { + let value = &mut self.target; + ::prost::encoding::int32::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(target)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.severity != Severity::default() as i32 { + ::prost::encoding::int32::encoded_len(1u32, &self.severity) + } else { + 0 + } + + if self.message != "" { + ::prost::encoding::string::encoded_len(2u32, &self.message) + } else { + 0 + } + + self + .reason + .as_ref() + .map_or(0, |value| ::prost::encoding::string::encoded_len(3u32, value)) + + self + .target + .as_ref() + .map_or(0, |value| ::prost::encoding::int32::encoded_len(4u32, value)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Result { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Result)) + .field( + stringify!(severity), + &crate::proto::unknown::enum_debug::(&self.severity), + ) + .field(stringify!(message), &self.message) + .field(stringify!(reason), &self.reason) + .field( + stringify!(target), + &self.target.as_ref().map(crate::proto::unknown::enum_debug::), + ) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +impl Result { + ///Returns the enum value of `severity`, or the default if the field is set to an invalid enum value. + pub fn severity(&self) -> Severity { + ::core::convert::TryFrom::try_from(self.severity).unwrap_or(Severity::default()) + } + ///Sets `severity` to the provided enum value. + pub fn set_severity(&mut self, value: Severity) { + self.severity = value as i32; + } + ///Returns the value of `reason`, or the default value if `reason` is unset. + pub fn reason(&self) -> &str { + match self.reason { + ::core::option::Option::Some(ref val) => &val[..], + ::core::option::Option::None => "", + } + } + ///Returns the enum value of `target`, or the default if the field is unset or set to an invalid enum value. + pub fn target(&self) -> Target { + self.target + .and_then(|x| { + let result: ::core::result::Result = ::core::convert::TryFrom::try_from( + x, + ); + result.ok() + }) + .unwrap_or(Target::default()) + } + ///Sets `target` to the provided enum value. + pub fn set_target(&mut self, value: Target) { + self.target = ::core::option::Option::Some(value as i32); + } } /// Status condition to be applied to the XR. Condition may also optionally be /// applied to the XR's associated claim. For detailed information on proper /// usage of status conditions, please see /// #[allow(clippy::all)] -#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +#[derive(Clone, PartialEq, Eq, Hash, Default)] pub struct Condition { /// Type of condition in PascalCase. - #[prost(string, tag = "1")] pub r#type: ::prost::alloc::string::String, /// Status of the condition. - #[prost(enumeration = "Status", tag = "2")] pub status: i32, /// Reason contains a programmatic identifier indicating the reason for the /// condition's last transition. Producers of specific condition types may /// define expected values and meanings for this field, and whether the values /// are considered a guaranteed API. The value should be a PascalCase string. /// This field may not be empty. - #[prost(string, tag = "3")] pub reason: ::prost::alloc::string::String, /// Message is a human readable message indicating details about the /// transition. This may be an empty string. - #[prost(string, optional, tag = "4")] pub message: ::core::option::Option<::prost::alloc::string::String>, /// The resources this condition targets. - #[prost(enumeration = "Target", optional, tag = "5")] pub target: ::core::option::Option, + /// Fields this SDK's proto does not know, kept and re-encoded. + pub unknown_fields: crate::proto::UnknownFields, +} +impl ::prost::Message for Condition { + fn encode_raw(&self, buf: &mut impl ::prost::bytes::BufMut) { + if self.r#type != "" { + ::prost::encoding::string::encode(1u32, &self.r#type, buf); + } + if self.status != Status::default() as i32 { + ::prost::encoding::int32::encode(2u32, &self.status, buf); + } + if self.reason != "" { + ::prost::encoding::string::encode(3u32, &self.reason, buf); + } + if let ::core::option::Option::Some(ref value) = self.message { + ::prost::encoding::string::encode(4u32, value, buf); + } + if let ::core::option::Option::Some(ref value) = self.target { + ::prost::encoding::int32::encode(5u32, value, buf); + } + self.unknown_fields.encode(buf); + } + fn merge_field( + &mut self, + tag: u32, + wire_type: ::prost::encoding::WireType, + buf: &mut impl ::prost::bytes::Buf, + ctx: ::prost::encoding::DecodeContext, + ) -> ::core::result::Result<(), ::prost::DecodeError> { + const STRUCT_NAME: &str = stringify!(Condition); + match tag { + 1u32 => { + let value = &mut self.r#type; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(r#type)); + error + }) + } + 2u32 => { + let value = &mut self.status; + ::prost::encoding::int32::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(status)); + error + }) + } + 3u32 => { + let value = &mut self.reason; + ::prost::encoding::string::merge(wire_type, value, buf, ctx) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(reason)); + error + }) + } + 4u32 => { + let value = &mut self.message; + ::prost::encoding::string::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(message)); + error + }) + } + 5u32 => { + let value = &mut self.target; + ::prost::encoding::int32::merge( + wire_type, + value.get_or_insert_with(::core::default::Default::default), + buf, + ctx, + ) + .map_err(|mut error| { + error.push(STRUCT_NAME, stringify!(target)); + error + }) + } + _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), + } + } + #[inline] + fn encoded_len(&self) -> usize { + 0 + + if self.r#type != "" { + ::prost::encoding::string::encoded_len(1u32, &self.r#type) + } else { + 0 + } + + if self.status != Status::default() as i32 { + ::prost::encoding::int32::encoded_len(2u32, &self.status) + } else { + 0 + } + + if self.reason != "" { + ::prost::encoding::string::encoded_len(3u32, &self.reason) + } else { + 0 + } + + self + .message + .as_ref() + .map_or(0, |value| ::prost::encoding::string::encoded_len(4u32, value)) + + self + .target + .as_ref() + .map_or(0, |value| ::prost::encoding::int32::encoded_len(5u32, value)) + + self.unknown_fields.encoded_len() + } + fn clear(&mut self) { + *self = Self::default(); + } +} +impl ::core::fmt::Debug for Condition { + fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { + f.debug_struct(stringify!(Condition)) + .field(stringify!(r#type), &self.r#type) + .field( + stringify!(status), + &crate::proto::unknown::enum_debug::(&self.status), + ) + .field(stringify!(reason), &self.reason) + .field(stringify!(message), &self.message) + .field( + stringify!(target), + &self.target.as_ref().map(crate::proto::unknown::enum_debug::), + ) + .field("unknown_fields", &self.unknown_fields) + .finish() + } +} +impl Condition { + ///Returns the enum value of `status`, or the default if the field is set to an invalid enum value. + pub fn status(&self) -> Status { + ::core::convert::TryFrom::try_from(self.status).unwrap_or(Status::default()) + } + ///Sets `status` to the provided enum value. + pub fn set_status(&mut self, value: Status) { + self.status = value as i32; + } + ///Returns the value of `message`, or the default value if `message` is unset. + pub fn message(&self) -> &str { + match self.message { + ::core::option::Option::Some(ref val) => &val[..], + ::core::option::Option::None => "", + } + } + ///Returns the enum value of `target`, or the default if the field is unset or set to an invalid enum value. + pub fn target(&self) -> Target { + self.target + .and_then(|x| { + let result: ::core::result::Result = ::core::convert::TryFrom::try_from( + x, + ); + result.ok() + }) + .unwrap_or(Target::default()) + } + ///Sets `target` to the provided enum value. + pub fn set_target(&mut self, value: Target) { + self.target = ::core::option::Option::Some(value as i32); + } } /// Capability indicates that Crossplane supports a particular feature. /// Functions can check for capabilities to determine whether Crossplane will diff --git a/sdk/src/generated/v1.serde.rs b/sdk/src/generated/v1.serde.rs index bb06a17..92f3f50 100644 --- a/sdk/src/generated/v1.serde.rs +++ b/sdk/src/generated/v1.serde.rs @@ -238,6 +238,7 @@ impl<'de> serde::Deserialize<'de> for Condition { reason: reason__.unwrap_or_default(), message: message__, target: target__, + unknown_fields: Default::default(), }) } } @@ -334,6 +335,7 @@ impl<'de> serde::Deserialize<'de> for CredentialData { } Ok(CredentialData { data: data__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -431,6 +433,7 @@ impl<'de> serde::Deserialize<'de> for Credentials { } Ok(Credentials { source: source__, + unknown_fields: Default::default(), }) } } @@ -524,6 +527,7 @@ impl<'de> serde::Deserialize<'de> for MatchLabels { } Ok(MatchLabels { labels: labels__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -710,6 +714,7 @@ impl<'de> serde::Deserialize<'de> for RequestMeta { Ok(RequestMeta { tag: tag__.unwrap_or_default(), capabilities: capabilities__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -842,6 +847,7 @@ impl<'de> serde::Deserialize<'de> for Requirements { extra_resources: extra_resources__.unwrap_or_default(), resources: resources__.unwrap_or_default(), schemas: schemas__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -1138,6 +1144,7 @@ impl<'de> serde::Deserialize<'de> for ResourceSelector { kind: kind__.unwrap_or_default(), namespace: namespace__, r#match: r#match__, + unknown_fields: Default::default(), }) } } @@ -1229,6 +1236,7 @@ impl<'de> serde::Deserialize<'de> for Resources { } Ok(Resources { items: items__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -1337,6 +1345,7 @@ impl<'de> serde::Deserialize<'de> for ResponseMeta { Ok(ResponseMeta { tag: tag__.unwrap_or_default(), ttl: ttl__, + unknown_fields: Default::default(), }) } } @@ -1483,6 +1492,7 @@ impl<'de> serde::Deserialize<'de> for Result { message: message__.unwrap_or_default(), reason: reason__, target: target__, + unknown_fields: Default::default(), }) } } @@ -1721,6 +1731,7 @@ impl<'de> serde::Deserialize<'de> for RunFunctionRequest { credentials: credentials__.unwrap_or_default(), required_resources: required_resources__.unwrap_or_default(), required_schemas: required_schemas__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } @@ -1914,6 +1925,7 @@ impl<'de> serde::Deserialize<'de> for RunFunctionResponse { requirements: requirements__, conditions: conditions__.unwrap_or_default(), output: output__, + unknown_fields: Default::default(), }) } } @@ -2006,6 +2018,7 @@ impl<'de> serde::Deserialize<'de> for Schema { } Ok(Schema { openapi_v3: openapi_v3__, + unknown_fields: Default::default(), }) } } @@ -2115,6 +2128,7 @@ impl<'de> serde::Deserialize<'de> for SchemaSelector { Ok(SchemaSelector { api_version: api_version__.unwrap_or_default(), kind: kind__.unwrap_or_default(), + unknown_fields: Default::default(), }) } } diff --git a/sdk/src/proto.rs b/sdk/src/proto.rs index f6a882c..1cdeaa4 100644 --- a/sdk/src/proto.rs +++ b/sdk/src/proto.rs @@ -2,17 +2,16 @@ //! `apiextensions.fn.proto.v1` FunctionRunnerService API. //! //! Regenerate with `cargo run -p codegen` after changing the vendored proto. -//! `State` and `Resource` are written by hand in `proto/state.rs` to keep -//! unknown fields; update them when the proto changes either message. +//! Every message keeps the fields its proto does not know in +//! `unknown_fields`: codegen writes the `prost::Message` impls for that. -mod state; +mod unknown; -pub use state::UnknownFields; +pub use unknown::UnknownFields; /// Types and the gRPC service for the v1 FunctionRunnerService API. pub mod v1 { #![allow(clippy::all, clippy::pedantic)] - pub use super::state::{Resource, State}; include!("generated/v1.rs"); include!("generated/v1.serde.rs"); } diff --git a/sdk/src/proto/state.rs b/sdk/src/proto/state.rs deleted file mode 100644 index 0952025..0000000 --- a/sdk/src/proto/state.rs +++ /dev/null @@ -1,323 +0,0 @@ -//! The messages a function carries forward from request to response. -//! -//! prost discards fields it does not know. [`State`] and [`Resource`] are -//! written by hand instead of generated so that fields a newer Crossplane -//! adds to them survive a function built against an older proto, as they do -//! in function-sdk-go. Known fields are decoded and encoded as prost -//! generates it for these messages. - -use std::collections::HashMap; -use std::fmt; - -use prost::bytes::{Buf, BufMut}; -use prost::encoding::{self, DecodeContext, WireType}; -use prost::{DecodeError, Message}; - -use super::v1::Ready; - -/// Fields of a message that this SDK's proto does not know. -/// -/// Crossplane may add fields to a message after this SDK was built. They -/// are kept when a message is decoded and written back when it is encoded, -/// so a function passes them down the pipeline untouched. They cannot be -/// read or modified, and they have no JSON representation. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct UnknownFields(Vec); - -impl UnknownFields { - fn merge( - &mut self, - tag: u32, - wire_type: WireType, - buf: &mut impl Buf, - ctx: DecodeContext, - ) -> Result<(), DecodeError> { - let out = &mut self.0; - match wire_type { - WireType::Varint => { - let mut value = 0u64; - encoding::uint64::merge(wire_type, &mut value, buf, ctx)?; - encoding::uint64::encode(tag, &value, out); - } - WireType::SixtyFourBit => { - let mut value = 0u64; - encoding::fixed64::merge(wire_type, &mut value, buf, ctx)?; - encoding::fixed64::encode(tag, &value, out); - } - WireType::ThirtyTwoBit => { - let mut value = 0u32; - encoding::fixed32::merge(wire_type, &mut value, buf, ctx)?; - encoding::fixed32::encode(tag, &value, out); - } - WireType::LengthDelimited => { - let mut value = Vec::::new(); - encoding::bytes::merge(wire_type, &mut value, buf, ctx)?; - encoding::bytes::encode(tag, &value, out); - } - // Groups are a proto2 feature that the proto3 function API - // cannot use, so they are skipped as prost skips them. - WireType::StartGroup | WireType::EndGroup => { - encoding::skip_field(wire_type, tag, buf, ctx)?; - } - } - Ok(()) - } - - fn encode(&self, buf: &mut impl BufMut) { - buf.put_slice(&self.0); - } - - fn encoded_len(&self) -> usize { - self.0.len() - } -} - -fn in_field(message: &'static str, field: &'static str) -> impl FnOnce(DecodeError) -> DecodeError { - move |mut error| { - error.push(message, field); - error - } -} - -/// State of the XR (XR) and any resources. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct State { - /// The state of the XR (XR). - pub composite: Option, - /// The state of any other resources. In composition functions these are the - /// composed resources. In operation functions they're arbitrary resources that - /// the operation wants to create or update. - pub resources: HashMap, - /// Fields this SDK's proto does not know, kept and re-encoded. - pub unknown_fields: UnknownFields, -} - -impl Message for State { - fn encode_raw(&self, buf: &mut impl BufMut) { - if let Some(composite) = &self.composite { - encoding::message::encode(1, composite, buf); - } - encoding::hash_map::encode( - encoding::string::encode, - encoding::string::encoded_len, - encoding::message::encode, - encoding::message::encoded_len, - 2, - &self.resources, - buf, - ); - self.unknown_fields.encode(buf); - } - - fn merge_field( - &mut self, - tag: u32, - wire_type: WireType, - buf: &mut impl Buf, - ctx: DecodeContext, - ) -> Result<(), DecodeError> { - match tag { - 1 => encoding::message::merge( - wire_type, - self.composite.get_or_insert_with(Default::default), - buf, - ctx, - ) - .map_err(in_field("State", "composite")), - 2 => encoding::check_wire_type(WireType::LengthDelimited, wire_type) - .and_then(|()| { - encoding::hash_map::merge( - encoding::string::merge, - encoding::message::merge, - &mut self.resources, - buf, - ctx, - ) - }) - .map_err(in_field("State", "resources")), - _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), - } - } - - fn encoded_len(&self) -> usize { - self.composite - .as_ref() - .map_or(0, |composite| encoding::message::encoded_len(1, composite)) - + encoding::hash_map::encoded_len( - encoding::string::encoded_len, - encoding::message::encoded_len, - 2, - &self.resources, - ) - + self.unknown_fields.encoded_len() - } - - fn clear(&mut self) { - *self = Self::default(); - } -} - -/// A Resource represents the state of a Kubernetes resource. -#[derive(Clone, Default, PartialEq)] -pub struct Resource { - /// The JSON representation of the resource. - /// - /// * Crossplane will set this field in a RunFunctionRequest to the entire - /// observed state of a resource - including its metadata, spec, and status. - /// - /// * A function should set this field in a RunFunctionRequest to communicate - /// the desired state of the resource. - /// - /// * A function may only specify the desired status of a XR - not its metadata - /// or spec. A function should not return desired metadata or spec for a XR. - /// This will be ignored. - /// - /// * A function may not specify the desired status of any other resource - - /// e.g. composed resources. It may only specify their metadata and spec. - /// Status will be ignored. - pub resource: Option, - /// The resource's connection details. - /// - /// * Crossplane will set this field in a RunFunctionRequest to communicate the - /// the observed connection details of a composite or composed resource. - /// - /// * A function should set this field in a RunFunctionResponse to indicate the - /// desired connection details of legacy XRs. For modern XRs, this will be ignored. - /// - /// * A function should not set this field in a RunFunctionResponse to indicate - /// the desired connection details of a composed resource. This will be - /// ignored. - /// - /// Connection details are only used for composition. They're ignored by - /// Operations. - pub connection_details: HashMap>, - /// Ready indicates whether the resource should be considered ready. - /// - /// * Crossplane will never set this field in a RunFunctionRequest. - /// - /// * A function should set this field to READY_TRUE in a RunFunctionResponse - /// to indicate that a desired resource is ready. - /// - /// * A function should set this field to READY_TRUE in a RunFunctionResponse - /// to indicate that a desired XR is ready. This overwrites the standard - /// readiness detection that determines the ready state of the composite by the - /// ready state of the composed resources. - /// - /// Ready is only used for composition. It's ignored by Operations. - pub ready: i32, - /// Fields this SDK's proto does not know, kept and re-encoded. - pub unknown_fields: UnknownFields, -} - -impl Resource { - /// Returns the enum value of `ready`, or the default if the field is set - /// to an invalid enum value. - pub fn ready(&self) -> Ready { - Ready::try_from(self.ready).unwrap_or_default() - } - - /// Sets `ready` to the provided enum value. - pub fn set_ready(&mut self, value: Ready) { - self.ready = value as i32; - } -} - -/// Prints `ready` as prost does: by variant name, or as a number when the -/// value is not a known variant. -struct ReadyDebug(i32); - -impl fmt::Debug for ReadyDebug { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match Ready::try_from(self.0) { - Ok(ready) => fmt::Debug::fmt(&ready, f), - Err(_) => fmt::Debug::fmt(&self.0, f), - } - } -} - -impl fmt::Debug for Resource { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Resource") - .field("resource", &self.resource) - .field("connection_details", &self.connection_details) - .field("ready", &ReadyDebug(self.ready)) - .field("unknown_fields", &self.unknown_fields) - .finish() - } -} - -impl Message for Resource { - fn encode_raw(&self, buf: &mut impl BufMut) { - if let Some(resource) = &self.resource { - encoding::message::encode(1, resource, buf); - } - encoding::hash_map::encode( - encoding::string::encode, - encoding::string::encoded_len, - encoding::bytes::encode, - encoding::bytes::encoded_len, - 2, - &self.connection_details, - buf, - ); - if self.ready != Ready::default() as i32 { - encoding::int32::encode(3, &self.ready, buf); - } - self.unknown_fields.encode(buf); - } - - fn merge_field( - &mut self, - tag: u32, - wire_type: WireType, - buf: &mut impl Buf, - ctx: DecodeContext, - ) -> Result<(), DecodeError> { - match tag { - 1 => encoding::message::merge( - wire_type, - self.resource.get_or_insert_with(Default::default), - buf, - ctx, - ) - .map_err(in_field("Resource", "resource")), - 2 => encoding::check_wire_type(WireType::LengthDelimited, wire_type) - .and_then(|()| { - encoding::hash_map::merge( - encoding::string::merge, - encoding::bytes::merge, - &mut self.connection_details, - buf, - ctx, - ) - }) - .map_err(in_field("Resource", "connection_details")), - 3 => encoding::int32::merge(wire_type, &mut self.ready, buf, ctx) - .map_err(in_field("Resource", "ready")), - _ => self.unknown_fields.merge(tag, wire_type, buf, ctx), - } - } - - fn encoded_len(&self) -> usize { - let ready = if self.ready != Ready::default() as i32 { - encoding::int32::encoded_len(3, &self.ready) - } else { - 0 - }; - self.resource - .as_ref() - .map_or(0, |resource| encoding::message::encoded_len(1, resource)) - + encoding::hash_map::encoded_len( - encoding::string::encoded_len, - encoding::bytes::encoded_len, - 2, - &self.connection_details, - ) - + ready - + self.unknown_fields.encoded_len() - } - - fn clear(&mut self) { - *self = Self::default(); - } -} diff --git a/sdk/src/proto/unknown.rs b/sdk/src/proto/unknown.rs new file mode 100644 index 0000000..7abf224 --- /dev/null +++ b/sdk/src/proto/unknown.rs @@ -0,0 +1,88 @@ +//! What the generated messages share so that they keep unknown fields. +//! +//! prost discards fields it does not know. Codegen writes the +//! `prost::Message` impl of every message itself (`codegen/src/messages.rs`) +//! so that fields a newer Crossplane adds survive a function built against +//! an older proto, as they do in function-sdk-go. Known fields are decoded +//! and encoded as prost generates it. + +use std::fmt; +use std::marker::PhantomData; + +use prost::DecodeError; +use prost::bytes::{Buf, BufMut}; +use prost::encoding::{self, DecodeContext, WireType}; + +/// Fields of a message that this SDK's proto does not know. +/// +/// Crossplane may add fields to a message after this SDK was built. They +/// are kept when a message is decoded and written back when it is encoded, +/// so a function passes them down the pipeline untouched. They cannot be +/// read or modified, and they have no JSON representation. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct UnknownFields(Vec); + +impl UnknownFields { + pub(crate) fn merge( + &mut self, + tag: u32, + wire_type: WireType, + buf: &mut impl Buf, + ctx: DecodeContext, + ) -> Result<(), DecodeError> { + let out = &mut self.0; + match wire_type { + WireType::Varint => { + let mut value = 0u64; + encoding::uint64::merge(wire_type, &mut value, buf, ctx)?; + encoding::uint64::encode(tag, &value, out); + } + WireType::SixtyFourBit => { + let mut value = 0u64; + encoding::fixed64::merge(wire_type, &mut value, buf, ctx)?; + encoding::fixed64::encode(tag, &value, out); + } + WireType::ThirtyTwoBit => { + let mut value = 0u32; + encoding::fixed32::merge(wire_type, &mut value, buf, ctx)?; + encoding::fixed32::encode(tag, &value, out); + } + WireType::LengthDelimited => { + let mut value = Vec::::new(); + encoding::bytes::merge(wire_type, &mut value, buf, ctx)?; + encoding::bytes::encode(tag, &value, out); + } + // Groups are a proto2 feature that the proto3 function API + // cannot use, so they are skipped as prost skips them. + WireType::StartGroup | WireType::EndGroup => { + encoding::skip_field(wire_type, tag, buf, ctx)?; + } + } + Ok(()) + } + + pub(crate) fn encode(&self, buf: &mut impl BufMut) { + buf.put_slice(&self.0); + } + + pub(crate) fn encoded_len(&self) -> usize { + self.0.len() + } +} + +/// Prints an enumeration field as prost does: by variant name, or as the +/// number when the value is not a known variant. +pub(crate) struct EnumDebug<'a, E>(&'a i32, PhantomData); + +pub(crate) fn enum_debug(value: &i32) -> EnumDebug<'_, E> { + EnumDebug(value, PhantomData) +} + +impl + fmt::Debug> fmt::Debug for EnumDebug<'_, E> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match E::try_from(*self.0) { + Ok(variant) => fmt::Debug::fmt(&variant, f), + Err(_) => fmt::Debug::fmt(self.0, f), + } + } +} diff --git a/sdk/src/response.rs b/sdk/src/response.rs index 4bba2a2..7276b3f 100644 --- a/sdk/src/response.rs +++ b/sdk/src/response.rs @@ -32,6 +32,7 @@ pub fn to(req: &RunFunctionRequest, ttl: Duration) -> RunFunctionResponse { seconds: ttl.as_secs() as i64, nanos: ttl.subsec_nanos() as i32, }), + ..Default::default() }), desired: req.desired.clone(), context: req.context.clone(), @@ -107,6 +108,7 @@ fn add_result( reason: None, // Explicitly target the XR by default, like function-sdk-go does. target: Some(Target::Composite as i32), + ..Default::default() }); rsp.results.last_mut().expect("a result was just pushed") } @@ -154,6 +156,7 @@ fn add_condition( reason: reason.into(), message: None, target: None, + ..Default::default() }); rsp.conditions .last_mut() @@ -189,11 +192,13 @@ pub fn require_resources( kind: kind.into(), r#match: r#match.map(|m| match m { ResourceMatch::Name(name) => resource_selector::Match::MatchName(name), - ResourceMatch::Labels(labels) => { - resource_selector::Match::MatchLabels(MatchLabels { labels }) - } + ResourceMatch::Labels(labels) => resource_selector::Match::MatchLabels(MatchLabels { + labels, + ..Default::default() + }), }), namespace, + ..Default::default() }; requirements(rsp).resources.insert(name.into(), selector); } @@ -212,6 +217,7 @@ pub fn require_schema( let selector = SchemaSelector { api_version: api_version.into(), kind: kind.into(), + ..Default::default() }; requirements(rsp).schemas.insert(name.into(), selector); } diff --git a/sdk/tests/generated/prost_v1.rs b/sdk/tests/generated/prost_v1.rs new file mode 100644 index 0000000..e3c404d --- /dev/null +++ b/sdk/tests/generated/prost_v1.rs @@ -0,0 +1,594 @@ +// This file is @generated by prost-build. +/// A RunFunctionRequest requests that the function be run. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RunFunctionRequest { + /// Metadata pertaining to this request. + #[prost(message, optional, tag = "1")] + pub meta: ::core::option::Option, + /// The observed state prior to invocation of a function pipeline. State passed + /// to each function is fresh as of the time the pipeline was invoked, not as + /// of the time each function was invoked. + #[prost(message, optional, tag = "2")] + pub observed: ::core::option::Option, + /// Desired state according to a function pipeline. The state passed to a + /// particular function may have been accumulated by previous functions in the + /// pipeline. + /// + /// Note that the desired state must be a partial object with only the fields + /// that this function (and its predecessors in the pipeline) wants to have set + /// in the object. Copying a non-partial observed state to desired is most + /// likely not what you want to do. Leaving out fields that had been returned + /// as desired before will result in them being deleted from the objects in the + /// cluster. + #[prost(message, optional, tag = "3")] + pub desired: ::core::option::Option, + /// Optional input specific to this function invocation. A JSON representation + /// of the 'input' block of the relevant entry in a function pipeline. + #[prost(message, optional, tag = "4")] + pub input: ::core::option::Option<::pbjson_types::Struct>, + /// Optional context. Crossplane may pass arbitrary contextual information to a + /// function. A function may also return context in its RunFunctionResponse, + /// and that context will be passed to subsequent functions. Crossplane + /// discards all context returned by the last function in the pipeline. + #[prost(message, optional, tag = "5")] + pub context: ::core::option::Option<::pbjson_types::Struct>, + /// Optional resources that the function specified in its requirements. Note + /// that resources is a map to Resources, plural. The map key corresponds to + /// the key in a RunFunctionResponse's requirements.extra_resources field. If a + /// function requested extra resources that did not exist, Crossplane sets + /// the map key to an empty Resources message to indicate that it attempted to + /// satisfy the request. This field is only populated when the function uses + /// extra_resources in its requirements. + /// + /// Deprecated: Use required_resources instead. + #[prost(map = "string, message", tag = "6")] + pub extra_resources: ::std::collections::HashMap< + ::prost::alloc::string::String, + Resources, + >, + /// Optional credentials that this function may use to communicate with an + /// external system. + #[prost(map = "string, message", tag = "7")] + pub credentials: ::std::collections::HashMap< + ::prost::alloc::string::String, + Credentials, + >, + /// Optional resources that the function specified in its requirements. Note + /// that resources is a map to Resources, plural. The map key corresponds to + /// the key in a RunFunctionResponse's requirements.resources field. If a + /// function requested required resources that did not exist, Crossplane sets + /// the map key to an empty Resources message to indicate that it attempted to + /// satisfy the request. This field is only populated when the function uses + /// resources in its requirements. + #[prost(map = "string, message", tag = "8")] + pub required_resources: ::std::collections::HashMap< + ::prost::alloc::string::String, + Resources, + >, + /// Optional schemas that the function specified in its requirements. The map + /// key corresponds to the key in a RunFunctionResponse's requirements.schemas + /// field. If a function requested a schema that could not be found, Crossplane + /// sets the map key to an empty Schema message to indicate that it attempted + /// to satisfy the request. + #[prost(map = "string, message", tag = "9")] + pub required_schemas: ::std::collections::HashMap< + ::prost::alloc::string::String, + Schema, + >, +} +/// Credentials that a function may use to communicate with an external system. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Credentials { + /// Source of the credentials. + #[prost(oneof = "credentials::Source", tags = "1")] + pub source: ::core::option::Option, +} +/// Nested message and enum types in `Credentials`. +pub mod credentials { + /// Source of the credentials. + #[allow(clippy::all)] + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Source { + /// Credential data loaded by Crossplane, for example from a Secret. + #[prost(message, tag = "1")] + CredentialData(super::CredentialData), + } +} +/// CredentialData loaded by Crossplane, for example from a Secret. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct CredentialData { + #[prost(map = "string, bytes", tag = "1")] + pub data: ::std::collections::HashMap< + ::prost::alloc::string::String, + ::prost::alloc::vec::Vec, + >, +} +/// Resources represents the state of several Crossplane resources. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Resources { + #[prost(message, repeated, tag = "1")] + pub items: ::prost::alloc::vec::Vec, +} +/// A RunFunctionResponse contains the result of a function run. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct RunFunctionResponse { + /// Metadata pertaining to this response. + #[prost(message, optional, tag = "1")] + pub meta: ::core::option::Option, + /// Desired state according to a function pipeline. functions may add desired + /// state, and may mutate or delete any part of the desired state they are + /// concerned with. A function must pass through any part of the desired state + /// that it is not concerned with. + /// + /// Note that the desired state must be a partial object with only the fields + /// that this function (and its predecessors in the pipeline) wants to have set + /// in the object. Copying a non-partial observed state to desired is most + /// likely not what you want to do. Leaving out fields that had been returned + /// as desired before will result in them being deleted from the objects in the + /// cluster. + #[prost(message, optional, tag = "2")] + pub desired: ::core::option::Option, + /// Results of the function run. Results are used for observability purposes. + #[prost(message, repeated, tag = "3")] + pub results: ::prost::alloc::vec::Vec, + /// Optional context to be passed to the next function in the pipeline as part + /// of the RunFunctionRequest. Dropped on the last function in the pipeline. + #[prost(message, optional, tag = "4")] + pub context: ::core::option::Option<::pbjson_types::Struct>, + /// Requirements that must be satisfied for this function to run successfully. + #[prost(message, optional, tag = "5")] + pub requirements: ::core::option::Option, + /// Status conditions to be applied to the XR. Conditions may also optionally + /// be applied to the XR's associated claim. + /// + /// Conditions are only used for composition. They're ignored by Operations. + #[prost(message, repeated, tag = "6")] + pub conditions: ::prost::alloc::vec::Vec, + /// Optional output specific to this function invocation. + /// + /// Only Operations use function output. XRs will discard any function output. + #[prost(message, optional, tag = "7")] + pub output: ::core::option::Option<::pbjson_types::Struct>, +} +/// RequestMeta contains metadata pertaining to a RunFunctionRequest. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct RequestMeta { + /// An opaque string identifying a request. Requests with identical tags will + /// be otherwise identical. + #[prost(string, tag = "1")] + pub tag: ::prost::alloc::string::String, + /// Capabilities supported by this version of Crossplane. Functions may use + /// this to determine whether Crossplane will honor certain fields in their + /// response, or populate certain fields in their request. + #[prost(enumeration = "Capability", repeated, tag = "2")] + pub capabilities: ::prost::alloc::vec::Vec, +} +/// Requirements that must be satisfied for a function to run successfully. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Requirements { + /// Resources that this function requires. The map key uniquely identifies the + /// group of resources. + /// + /// Deprecated: Use resources instead. + #[prost(map = "string, message", tag = "1")] + pub extra_resources: ::std::collections::HashMap< + ::prost::alloc::string::String, + ResourceSelector, + >, + /// Resources that this function requires. The map key uniquely identifies the + /// group of resources. + #[prost(map = "string, message", tag = "2")] + pub resources: ::std::collections::HashMap< + ::prost::alloc::string::String, + ResourceSelector, + >, + /// Schemas that this function requires. The map key uniquely identifies the + /// schema request. + #[prost(map = "string, message", tag = "3")] + pub schemas: ::std::collections::HashMap< + ::prost::alloc::string::String, + SchemaSelector, + >, +} +/// SchemaSelector identifies a resource kind whose OpenAPI schema is requested. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct SchemaSelector { + /// API version of the resource kind, e.g. "example.org/v1". + #[prost(string, tag = "1")] + pub api_version: ::prost::alloc::string::String, + /// Kind of resource, e.g. "MyResource". + #[prost(string, tag = "2")] + pub kind: ::prost::alloc::string::String, +} +/// Schema represents the OpenAPI schema for a resource kind. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Schema { + /// The OpenAPI v3 schema of the resource kind as unstructured JSON. + /// For CRDs this is the spec.versions\[\].schema.openAPIV3Schema field. + /// Empty if Crossplane could not find a schema for the requested kind. + #[prost(message, optional, tag = "1")] + pub openapi_v3: ::core::option::Option<::pbjson_types::Struct>, +} +/// ResourceSelector selects a group of resources, either by name or by label. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct ResourceSelector { + /// API version of resources to select. + #[prost(string, tag = "1")] + pub api_version: ::prost::alloc::string::String, + /// Kind of resources to select. + #[prost(string, tag = "2")] + pub kind: ::prost::alloc::string::String, + /// Match resources in this namespace. Omit namespace to match cluster scoped + /// resources, or to match namespaced resources by labels across all + /// namespaces. + #[prost(string, optional, tag = "5")] + pub namespace: ::core::option::Option<::prost::alloc::string::String>, + /// Resources to match. + #[prost(oneof = "resource_selector::Match", tags = "3, 4")] + pub r#match: ::core::option::Option, +} +/// Nested message and enum types in `ResourceSelector`. +pub mod resource_selector { + /// Resources to match. + #[allow(clippy::all)] + #[derive(Clone, PartialEq, ::prost::Oneof)] + pub enum Match { + /// Match the resource with this name. + #[prost(string, tag = "3")] + MatchName(::prost::alloc::string::String), + /// Match all resources with these labels. + #[prost(message, tag = "4")] + MatchLabels(super::MatchLabels), + } +} +/// MatchLabels defines a set of labels to match resources against. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct MatchLabels { + #[prost(map = "string, string", tag = "1")] + pub labels: ::std::collections::HashMap< + ::prost::alloc::string::String, + ::prost::alloc::string::String, + >, +} +/// ResponseMeta contains metadata pertaining to a RunFunctionResponse. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct ResponseMeta { + /// An opaque string identifying the content of the request. Must match the + /// meta.tag of the corresponding RunFunctionRequest. + #[prost(string, tag = "1")] + pub tag: ::prost::alloc::string::String, + /// Time-to-live of this response. Crossplane will call the function again when + /// the TTL expires. Crossplane may cache the response to avoid calling the + /// function again until the TTL expires. + #[prost(message, optional, tag = "2")] + pub ttl: ::core::option::Option<::pbjson_types::Duration>, +} +/// State of the XR (XR) and any resources. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct State { + /// The state of the XR (XR). + #[prost(message, optional, tag = "1")] + pub composite: ::core::option::Option, + /// The state of any other resources. In composition functions these are the + /// composed resources. In operation functions they're arbitrary resources that + /// the operation wants to create or update. + #[prost(map = "string, message", tag = "2")] + pub resources: ::std::collections::HashMap<::prost::alloc::string::String, Resource>, +} +/// A Resource represents the state of a Kubernetes resource. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, ::prost::Message)] +pub struct Resource { + /// The JSON representation of the resource. + /// + /// * Crossplane will set this field in a RunFunctionRequest to the entire + /// observed state of a resource - including its metadata, spec, and status. + /// + /// * A function should set this field in a RunFunctionRequest to communicate + /// the desired state of the resource. + /// + /// * A function may only specify the desired status of a XR - not its metadata + /// or spec. A function should not return desired metadata or spec for a XR. + /// This will be ignored. + /// + /// * A function may not specify the desired status of any other resource - + /// e.g. composed resources. It may only specify their metadata and spec. + /// Status will be ignored. + #[prost(message, optional, tag = "1")] + pub resource: ::core::option::Option<::pbjson_types::Struct>, + /// The resource's connection details. + /// + /// * Crossplane will set this field in a RunFunctionRequest to communicate the + /// the observed connection details of a composite or composed resource. + /// + /// * A function should set this field in a RunFunctionResponse to indicate the + /// desired connection details of legacy XRs. For modern XRs, this will be ignored. + /// + /// * A function should not set this field in a RunFunctionResponse to indicate + /// the desired connection details of a composed resource. This will be + /// ignored. + /// + /// Connection details are only used for composition. They're ignored by + /// Operations. + #[prost(map = "string, bytes", tag = "2")] + pub connection_details: ::std::collections::HashMap< + ::prost::alloc::string::String, + ::prost::alloc::vec::Vec, + >, + /// Ready indicates whether the resource should be considered ready. + /// + /// * Crossplane will never set this field in a RunFunctionRequest. + /// + /// * A function should set this field to READY_TRUE in a RunFunctionResponse + /// to indicate that a desired resource is ready. + /// + /// * A function should set this field to READY_TRUE in a RunFunctionResponse + /// to indicate that a desired XR is ready. This overwrites the standard + /// readiness detection that determines the ready state of the composite by the + /// ready state of the composed resources. + /// + /// Ready is only used for composition. It's ignored by Operations. + #[prost(enumeration = "Ready", tag = "3")] + pub ready: i32, +} +/// A Result of running a function. +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Result { + /// Severity of this result. + #[prost(enumeration = "Severity", tag = "1")] + pub severity: i32, + /// Human-readable details about the result. + #[prost(string, tag = "2")] + pub message: ::prost::alloc::string::String, + /// Optional PascalCase, machine-readable reason for this result. If omitted, + /// the value will be ComposeResources. + #[prost(string, optional, tag = "3")] + pub reason: ::core::option::Option<::prost::alloc::string::String>, + /// The resources this result targets. + #[prost(enumeration = "Target", optional, tag = "4")] + pub target: ::core::option::Option, +} +/// Status condition to be applied to the XR. Condition may also optionally be +/// applied to the XR's associated claim. For detailed information on proper +/// usage of status conditions, please see +/// +#[allow(clippy::all)] +#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] +pub struct Condition { + /// Type of condition in PascalCase. + #[prost(string, tag = "1")] + pub r#type: ::prost::alloc::string::String, + /// Status of the condition. + #[prost(enumeration = "Status", tag = "2")] + pub status: i32, + /// Reason contains a programmatic identifier indicating the reason for the + /// condition's last transition. Producers of specific condition types may + /// define expected values and meanings for this field, and whether the values + /// are considered a guaranteed API. The value should be a PascalCase string. + /// This field may not be empty. + #[prost(string, tag = "3")] + pub reason: ::prost::alloc::string::String, + /// Message is a human readable message indicating details about the + /// transition. This may be an empty string. + #[prost(string, optional, tag = "4")] + pub message: ::core::option::Option<::prost::alloc::string::String>, + /// The resources this condition targets. + #[prost(enumeration = "Target", optional, tag = "5")] + pub target: ::core::option::Option, +} +/// Capability indicates that Crossplane supports a particular feature. +/// Functions can check for capabilities to determine whether Crossplane will +/// honor a particular request or response field. +#[allow(clippy::all)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Capability { + Unspecified = 0, + /// Crossplane sends capabilities in RequestMeta. If this capability is + /// present, the function knows that if another capability is absent, it's + /// because Crossplane doesn't support it (not because Crossplane predates + /// capability advertisement). Added in Crossplane v2.2. + Capabilities = 1, + /// Crossplane supports the requirements.resources field. Functions can return + /// resource requirements and Crossplane will fetch the requested resources and + /// return them in required_resources. Added in Crossplane v1.15. + RequiredResources = 2, + /// Crossplane supports the credentials field. Functions can receive + /// credentials from secrets specified in the Composition. Added in Crossplane + /// v1.16. + Credentials = 3, + /// Crossplane supports the conditions field. Functions can return status + /// conditions to be applied to the XR and optionally its claim. Added in + /// Crossplane v1.17. + Conditions = 4, + /// Crossplane supports the requirements.schemas field. Functions can request + /// OpenAPI schemas and Crossplane will return them in required_schemas. Added + /// in Crossplane v2.2. + RequiredSchemas = 5, +} +impl Capability { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "CAPABILITY_UNSPECIFIED", + Self::Capabilities => "CAPABILITY_CAPABILITIES", + Self::RequiredResources => "CAPABILITY_REQUIRED_RESOURCES", + Self::Credentials => "CAPABILITY_CREDENTIALS", + Self::Conditions => "CAPABILITY_CONDITIONS", + Self::RequiredSchemas => "CAPABILITY_REQUIRED_SCHEMAS", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "CAPABILITY_UNSPECIFIED" => Some(Self::Unspecified), + "CAPABILITY_CAPABILITIES" => Some(Self::Capabilities), + "CAPABILITY_REQUIRED_RESOURCES" => Some(Self::RequiredResources), + "CAPABILITY_CREDENTIALS" => Some(Self::Credentials), + "CAPABILITY_CONDITIONS" => Some(Self::Conditions), + "CAPABILITY_REQUIRED_SCHEMAS" => Some(Self::RequiredSchemas), + _ => None, + } + } +} +/// Ready indicates whether a resource should be considered ready. +#[allow(clippy::all)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Ready { + Unspecified = 0, + /// True means the resource has been observed to be ready. + True = 1, + /// False means the resource has not been observed to be ready. + False = 2, +} +impl Ready { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "READY_UNSPECIFIED", + Self::True => "READY_TRUE", + Self::False => "READY_FALSE", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "READY_UNSPECIFIED" => Some(Self::Unspecified), + "READY_TRUE" => Some(Self::True), + "READY_FALSE" => Some(Self::False), + _ => None, + } + } +} +/// Severity of function results. +#[allow(clippy::all)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Severity { + Unspecified = 0, + /// Fatal results are fatal; subsequent functions may run, but the function + /// pipeline run will be considered a failure and the first fatal result will + /// be returned as an error. + Fatal = 1, + /// Warning results are non-fatal; the entire pipeline will run to completion + /// but warning events and debug logs associated with the XR or Operation will + /// be emitted. + Warning = 2, + /// Normal results are emitted as normal events and debug logs associated with + /// the XR or operation. + Normal = 3, +} +impl Severity { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "SEVERITY_UNSPECIFIED", + Self::Fatal => "SEVERITY_FATAL", + Self::Warning => "SEVERITY_WARNING", + Self::Normal => "SEVERITY_NORMAL", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "SEVERITY_UNSPECIFIED" => Some(Self::Unspecified), + "SEVERITY_FATAL" => Some(Self::Fatal), + "SEVERITY_WARNING" => Some(Self::Warning), + "SEVERITY_NORMAL" => Some(Self::Normal), + _ => None, + } + } +} +/// Target of function results and conditions. +#[allow(clippy::all)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Target { + /// If the target is unspecified, the result targets the XR. + Unspecified = 0, + /// Target the XR. Results that target the XR should include detailed, advanced + /// information. + Composite = 1, + /// Target the XR and the claim. Results that target the XR and the claim + /// should include only end-user friendly information. + CompositeAndClaim = 2, +} +impl Target { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::Unspecified => "TARGET_UNSPECIFIED", + Self::Composite => "TARGET_COMPOSITE", + Self::CompositeAndClaim => "TARGET_COMPOSITE_AND_CLAIM", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "TARGET_UNSPECIFIED" => Some(Self::Unspecified), + "TARGET_COMPOSITE" => Some(Self::Composite), + "TARGET_COMPOSITE_AND_CLAIM" => Some(Self::CompositeAndClaim), + _ => None, + } + } +} +#[allow(clippy::all)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] +#[repr(i32)] +pub enum Status { + ConditionUnspecified = 0, + ConditionUnknown = 1, + ConditionTrue = 2, + ConditionFalse = 3, +} +impl Status { + /// String value of the enum field names used in the ProtoBuf definition. + /// + /// The values are not transformed in any way and thus are considered stable + /// (if the ProtoBuf definition does not change) and safe for programmatic use. + pub fn as_str_name(&self) -> &'static str { + match self { + Self::ConditionUnspecified => "STATUS_CONDITION_UNSPECIFIED", + Self::ConditionUnknown => "STATUS_CONDITION_UNKNOWN", + Self::ConditionTrue => "STATUS_CONDITION_TRUE", + Self::ConditionFalse => "STATUS_CONDITION_FALSE", + } + } + /// Creates an enum from field names used in the ProtoBuf definition. + pub fn from_str_name(value: &str) -> ::core::option::Option { + match value { + "STATUS_CONDITION_UNSPECIFIED" => Some(Self::ConditionUnspecified), + "STATUS_CONDITION_UNKNOWN" => Some(Self::ConditionUnknown), + "STATUS_CONDITION_TRUE" => Some(Self::ConditionTrue), + "STATUS_CONDITION_FALSE" => Some(Self::ConditionFalse), + _ => None, + } + } +} diff --git a/sdk/tests/generated_messages.rs b/sdk/tests/generated_messages.rs new file mode 100644 index 0000000..5f6ca58 --- /dev/null +++ b/sdk/tests/generated_messages.rs @@ -0,0 +1,507 @@ +//! Holds every message codegen writes to the message prost derives from the +//! same proto. +//! +//! Codegen replaces prost's `Message` derive so that a message keeps unknown +//! fields (`codegen/src/messages.rs`), and writes what prost-build generated, +//! derive and all, to `tests/generated/prost_v1.rs`. The two must agree on +//! everything but unknown fields: the bytes of the known fields, the verdict +//! and the error on malformed input, `Debug`, the defaults and the accessors. +//! A map in a fixture has one entry, because prost encodes a map in hash +//! order and the tests compare bytes. +#![allow(deprecated)] + +use std::collections::HashMap; +use std::fmt::Debug; + +use function_sdk_rust::proto::FILE_DESCRIPTOR_SET; +use function_sdk_rust::proto::v1 as ours; +use function_sdk_rust::resource::json_to_struct; +use prost::Message; +use prost::encoding; +use prost_types::FileDescriptorSet; + +/// The messages as prost derives them, which drop unknown fields. +#[allow(dead_code, clippy::all, clippy::pedantic)] +mod theirs { + include!("generated/prost_v1.rs"); +} + +/// Runs `$check!(Message)` for every message of the function API. +/// `the_checks_cover_every_message_of_the_proto` holds the list to the +/// descriptor. +macro_rules! for_every_message { + ($check:ident) => { + $check!(RunFunctionRequest); + $check!(Credentials); + $check!(CredentialData); + $check!(Resources); + $check!(RunFunctionResponse); + $check!(RequestMeta); + $check!(Requirements); + $check!(SchemaSelector); + $check!(Schema); + $check!(ResourceSelector); + $check!(MatchLabels); + $check!(ResponseMeta); + $check!(State); + $check!(Result); + $check!(Resource); + $check!(Condition); + }; +} + +fn object() -> pbjson_types::Struct { + let json = serde_json::json!({"spec": {"forProvider": {"region": "eu-central-1"}}}); + json_to_struct(json.as_object().expect("the fixture is an object")) +} + +fn resource() -> theirs::Resource { + theirs::Resource { + resource: Some(object()), + connection_details: HashMap::from([("password".to_string(), b"secret".to_vec())]), + ready: theirs::Ready::True as i32, + } +} + +fn state() -> theirs::State { + theirs::State { + composite: Some(resource()), + resources: HashMap::from([("bucket".to_string(), resource())]), + } +} + +fn resources() -> theirs::Resources { + theirs::Resources { + items: vec![resource(), theirs::Resource::default()], + } +} + +fn match_labels() -> theirs::MatchLabels { + theirs::MatchLabels { + labels: HashMap::from([("app".to_string(), "web".to_string())]), + } +} + +fn selector() -> theirs::ResourceSelector { + theirs::ResourceSelector { + api_version: "v1".to_string(), + kind: "Secret".to_string(), + namespace: Some("crossplane-system".to_string()), + r#match: Some(theirs::resource_selector::Match::MatchLabels(match_labels())), + } +} + +fn credential_data() -> theirs::CredentialData { + theirs::CredentialData { + data: HashMap::from([("token".to_string(), b"t0ken".to_vec())]), + } +} + +fn credentials() -> theirs::Credentials { + theirs::Credentials { + source: Some(theirs::credentials::Source::CredentialData( + credential_data(), + )), + } +} + +fn schema() -> theirs::Schema { + theirs::Schema { + openapi_v3: Some(object()), + } +} + +fn schema_selector() -> theirs::SchemaSelector { + theirs::SchemaSelector { + api_version: "example.org/v1".to_string(), + kind: "XBucket".to_string(), + } +} + +fn request_meta() -> theirs::RequestMeta { + theirs::RequestMeta { + tag: "tag".to_string(), + capabilities: vec![ + theirs::Capability::Capabilities as i32, + theirs::Capability::RequiredSchemas as i32, + // A capability this proto does not name. + 42, + ], + } +} + +fn response_meta() -> theirs::ResponseMeta { + theirs::ResponseMeta { + tag: "tag".to_string(), + ttl: Some(pbjson_types::Duration { + seconds: 60, + nanos: 5, + }), + } +} + +fn result() -> theirs::Result { + theirs::Result { + severity: theirs::Severity::Warning as i32, + message: "a message".to_string(), + reason: Some("AReason".to_string()), + target: Some(theirs::Target::CompositeAndClaim as i32), + } +} + +fn condition() -> theirs::Condition { + theirs::Condition { + r#type: "DatabaseReady".to_string(), + status: theirs::Status::ConditionFalse as i32, + reason: "Creating".to_string(), + message: Some("still creating".to_string()), + target: Some(theirs::Target::Composite as i32), + } +} + +fn requirements() -> theirs::Requirements { + theirs::Requirements { + extra_resources: HashMap::from([( + "by-name".to_string(), + theirs::ResourceSelector { + api_version: "v1".to_string(), + kind: "ConfigMap".to_string(), + namespace: None, + r#match: Some(theirs::resource_selector::Match::MatchName( + "cm".to_string(), + )), + }, + )]), + resources: HashMap::from([("by-labels".to_string(), selector())]), + schemas: HashMap::from([("xbucket".to_string(), schema_selector())]), + } +} + +fn request() -> theirs::RunFunctionRequest { + theirs::RunFunctionRequest { + meta: Some(request_meta()), + observed: Some(state()), + desired: Some(state()), + input: Some(object()), + context: Some(object()), + extra_resources: HashMap::from([("extra".to_string(), resources())]), + credentials: HashMap::from([("api".to_string(), credentials())]), + required_resources: HashMap::from([("required".to_string(), resources())]), + required_schemas: HashMap::from([("xbucket".to_string(), schema())]), + } +} + +fn response() -> theirs::RunFunctionResponse { + theirs::RunFunctionResponse { + meta: Some(response_meta()), + desired: Some(state()), + results: vec![result(), theirs::Result::default()], + context: Some(object()), + requirements: Some(requirements()), + conditions: vec![condition()], + output: Some(object()), + } +} + +/// One value of the message with every field set, encoded by prost's +/// derive: what a valid message looks like on the wire. +fn sample(message: &str) -> Vec { + match message { + "RunFunctionRequest" => request().encode_to_vec(), + "Credentials" => credentials().encode_to_vec(), + "CredentialData" => credential_data().encode_to_vec(), + "Resources" => resources().encode_to_vec(), + "RunFunctionResponse" => response().encode_to_vec(), + "RequestMeta" => request_meta().encode_to_vec(), + "Requirements" => requirements().encode_to_vec(), + "SchemaSelector" => schema_selector().encode_to_vec(), + "Schema" => schema().encode_to_vec(), + "ResourceSelector" => selector().encode_to_vec(), + "MatchLabels" => match_labels().encode_to_vec(), + "ResponseMeta" => response_meta().encode_to_vec(), + "State" => state().encode_to_vec(), + "Result" => result().encode_to_vec(), + "Resource" => resource().encode_to_vec(), + "Condition" => condition().encode_to_vec(), + other => panic!("{other} has no sample: add one, and the message to for_every_message"), + } +} + +/// One field of every wire type proto3 can produce, under field numbers no +/// message of the function API uses. +fn fields_from_a_newer_crossplane() -> Vec { + let mut buf = Vec::new(); + encoding::uint64::encode(100, &u64::MAX, &mut buf); + encoding::fixed64::encode(101, &7, &mut buf); + encoding::fixed32::encode(102, &9, &mut buf); + encoding::string::encode(103, &"from-the-future".to_string(), &mut buf); + buf +} + +/// `Debug` of one of our messages without the field prost's does not have. +fn debug_of_known_fields(message: &impl Debug) -> String { + format!("{message:?}").replace(", unknown_fields: UnknownFields([])", "") +} + +/// Decodes `input` as both messages and expects one verdict: the same +/// error, or the same known fields. prost's message drops unknown fields, +/// so decoding our output with it compares the known fields alone. +fn agree(message: &str, input: &[u8]) +where + Ours: Message + Default + Debug, + Theirs: Message + Default + Debug + PartialEq, +{ + match (Ours::decode(input), Theirs::decode(input)) { + (Ok(ours), Ok(theirs)) => { + let encoded = ours.encode_to_vec(); + assert_eq!(ours.encoded_len(), encoded.len(), "{message} {input:?}"); + let known = Theirs::decode(encoded.as_slice()) + .unwrap_or_else(|e| panic!("{message} {input:?}: prost refuses our output: {e}")); + assert_eq!(known, theirs, "{message} {input:?}"); + } + (Err(ours), Err(theirs)) => { + assert_eq!(ours.to_string(), theirs.to_string(), "{message} {input:?}"); + } + (ours, theirs) => panic!("{message} {input:?}: ours {ours:?}, prost's {theirs:?}"), + } +} + +fn a_valid_message_is_the_same_bytes(message: &str) +where + Ours: Message + Default + Debug, + Theirs: Message + Default + Debug + PartialEq, +{ + let sample = sample(message); + let ours = Ours::decode(sample.as_slice()).expect("our message decodes prost's output"); + let theirs = Theirs::decode(sample.as_slice()).expect("prost decodes its own output"); + + assert_eq!(ours.encode_to_vec(), sample, "{message}"); + assert_eq!(ours.encoded_len(), sample.len(), "{message}"); + assert_eq!( + debug_of_known_fields(&ours), + format!("{theirs:?}"), + "{message}" + ); + agree::(message, &sample); + + // Cut anywhere, the sample is the same error or the same shorter message. + for end in 0..sample.len() { + agree::(message, &sample[..end]); + } +} + +fn a_default_message_is_prost_s_default(message: &str) +where + Ours: Message + Default + Debug, + Theirs: Message + Default + Debug, +{ + assert!(Ours::default().encode_to_vec().is_empty(), "{message}"); + assert_eq!( + debug_of_known_fields(&Ours::default()), + format!("{:?}", Theirs::default()), + "{message}" + ); + + let mut cleared = Ours::decode(sample(message).as_slice()).expect("decodes"); + cleared.clear(); + assert!(cleared.encode_to_vec().is_empty(), "{message}"); +} + +/// Every field number the proto uses and a few it does not, with every wire +/// type and a few payloads. +fn malformed_input_is_prost_s_verdict(message: &str) +where + Ours: Message + Default + Debug, + Theirs: Message + Default + Debug + PartialEq, +{ + let payloads: [&[u8]; 8] = [ + &[], + &[0x00], + &[0x01], + &[0x7f], + &[0x04, 0x0a, 0x02, b'h', b'i'], + &[0x02, 0x08, 0x01], + &[0x00, 0x00, 0x00, 0x00], + &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + ]; + for tag in 1..=12u8 { + for wire_type in 0..=5u8 { + for payload in payloads { + let mut input = vec![tag << 3 | wire_type]; + input.extend(payload); + agree::(message, &input); + } + } + } +} + +fn unknown_fields_are_kept_byte_for_byte(message: &str) +where + Ours: Message + Default + Debug, + Theirs: Message + Default + Debug, +{ + let sample = sample(message); + let mut newer = sample.clone(); + newer.extend(fields_from_a_newer_crossplane()); + + let ours = Ours::decode(newer.as_slice()).expect("decodes"); + assert_eq!(ours.encoded_len(), newer.len(), "{message}"); + assert_eq!(ours.encode_to_vec(), newer, "{message}"); + assert!( + format!("{ours:?}").contains("unknown_fields: UnknownFields([160, 6,"), + "{message}: {ours:?}" + ); + + // What the rewrite is for: prost's own message loses them. + let theirs = Theirs::decode(newer.as_slice()).expect("decodes"); + assert_eq!(theirs.encode_to_vec(), sample, "{message}"); + + // An unknown field cut short is an error, not a shorter message. + newer.truncate(newer.len() - 1); + assert!(Ours::decode(newer.as_slice()).is_err(), "{message}"); +} + +#[test] +fn a_valid_message_encodes_as_prost_encodes_it() { + macro_rules! check { + ($message:ident) => { + a_valid_message_is_the_same_bytes::(stringify!( + $message + )) + }; + } + for_every_message!(check); +} + +#[test] +fn a_default_message_is_what_prost_defaults_to() { + macro_rules! check { + ($message:ident) => { + a_default_message_is_prost_s_default::(stringify!( + $message + )) + }; + } + for_every_message!(check); +} + +#[test] +fn malformed_input_decodes_as_prost_decodes_it() { + macro_rules! check { + ($message:ident) => { + malformed_input_is_prost_s_verdict::(stringify!( + $message + )) + }; + } + for_every_message!(check); +} + +#[test] +fn every_message_keeps_unknown_fields() { + macro_rules! check { + ($message:ident) => { + unknown_fields_are_kept_byte_for_byte::(stringify!( + $message + )) + }; + } + for_every_message!(check); +} + +/// The accessors prost's derive adds: an enumeration read as its enum, set +/// and pushed, and an optional string read as a `&str`. +#[test] +fn the_accessors_are_prost_s() { + for ready in [0, 1, 2, 7] { + let (mut a, mut b) = (ours::Resource::default(), theirs::Resource::default()); + (a.ready, b.ready) = (ready, ready); + assert_eq!(a.ready() as i32, b.ready() as i32, "ready {ready}"); + a.set_ready(ours::Ready::False); + b.set_ready(theirs::Ready::False); + assert_eq!(a.ready, b.ready); + } + + let unset = (ours::Result::default(), theirs::Result::default()); + assert_eq!(unset.0.reason(), unset.1.reason()); + assert_eq!(unset.0.target() as i32, unset.1.target() as i32); + assert_eq!(unset.0.severity() as i32, unset.1.severity() as i32); + for value in [0, 2, 9] { + let (mut a, mut b) = (ours::Result::default(), theirs::Result::default()); + (a.severity, b.severity) = (value, value); + (a.target, b.target) = (Some(value), Some(value)); + (a.reason, b.reason) = (Some("why".to_string()), Some("why".to_string())); + assert_eq!(a.severity() as i32, b.severity() as i32, "severity {value}"); + assert_eq!(a.target() as i32, b.target() as i32, "target {value}"); + assert_eq!(a.reason(), b.reason()); + a.set_severity(ours::Severity::Fatal); + b.set_severity(theirs::Severity::Fatal); + a.set_target(ours::Target::CompositeAndClaim); + b.set_target(theirs::Target::CompositeAndClaim); + assert_eq!((a.severity, a.target), (b.severity, b.target)); + } + + let (mut a, mut b) = (ours::Condition::default(), theirs::Condition::default()); + assert_eq!(a.message(), b.message()); + assert_eq!(a.status() as i32, b.status() as i32); + assert_eq!(a.target() as i32, b.target() as i32); + a.set_status(ours::Status::ConditionTrue); + b.set_status(theirs::Status::ConditionTrue); + a.set_target(ours::Target::Composite); + b.set_target(theirs::Target::Composite); + assert_eq!((a.status, a.target), (b.status, b.target)); + + let (a, b) = ( + ours::ResourceSelector::default(), + theirs::ResourceSelector::default(), + ); + assert_eq!(a.namespace(), b.namespace()); + + let (mut a, mut b) = (ours::RequestMeta::default(), theirs::RequestMeta::default()); + (a.capabilities, b.capabilities) = (vec![1, 42, 5], vec![1, 42, 5]); + a.push_capabilities(ours::Capability::Conditions); + b.push_capabilities(theirs::Capability::Conditions); + assert_eq!(a.capabilities, b.capabilities); + let read: (Vec, Vec) = ( + a.capabilities().map(|c| c as i32).collect(), + b.capabilities().map(|c| c as i32).collect(), + ); + assert_eq!(read.0, read.1); + assert_eq!(read.0, [1, 5, 4]); +} + +/// A message the proto gains has to join `for_every_message` and `sample`, +/// or nothing here would hold it to prost's. +#[test] +fn the_checks_cover_every_message_of_the_proto() { + let mut checked: Vec<&str> = Vec::new(); + macro_rules! check { + ($message:ident) => { + checked.push(stringify!($message)) + }; + } + for_every_message!(check); + checked.sort_unstable(); + + let files = FileDescriptorSet::decode(FILE_DESCRIPTOR_SET).expect("the descriptor decodes"); + let mut messages = Vec::new(); + for message in files + .file + .iter() + .filter(|file| file.package() == "apiextensions.fn.proto.v1") + .flat_map(|file| &file.message_type) + { + messages.push(message.name()); + // A map field is a nested entry message, which is no message of the + // API. Any other nested message would need its own check. + let nested: Vec<_> = message + .nested_type + .iter() + .filter(|nested| !nested.options.as_ref().is_some_and(|o| o.map_entry())) + .map(|nested| nested.name()) + .collect(); + assert!(nested.is_empty(), "{} nests {nested:?}", message.name()); + } + messages.sort_unstable(); + assert_eq!(checked, messages); +} diff --git a/sdk/tests/serve.rs b/sdk/tests/serve.rs index 0eb68cf..e2506b5 100644 --- a/sdk/tests/serve.rs +++ b/sdk/tests/serve.rs @@ -44,6 +44,7 @@ async fn serve_handles_a_run_function_request() { meta: Some(RequestMeta { tag: "smoke".to_string(), capabilities: vec![], + ..Default::default() }), ..Default::default() }) diff --git a/sdk/tests/unknown_fields.rs b/sdk/tests/unknown_fields.rs index cf852cd..f025e93 100644 --- a/sdk/tests/unknown_fields.rs +++ b/sdk/tests/unknown_fields.rs @@ -1,34 +1,17 @@ +//! What a function sees of the fields its SDK does not know: they pass +//! through it, on every message. `generated_messages.rs` holds the messages +//! themselves to the ones prost derives. + use std::collections::HashMap; +use function_sdk_rust::proto::UnknownFields; use function_sdk_rust::proto::v1::{ - Ready, Resource, RunFunctionRequest, RunFunctionResponse, State, + Ready, RequestMeta, Requirements, Resource, ResourceSelector, ResponseMeta, Result as FnResult, + RunFunctionRequest, RunFunctionResponse, State, }; -use function_sdk_rust::proto::{FILE_DESCRIPTOR_SET, UnknownFields}; use function_sdk_rust::{resource, response}; use prost::Message; use prost::encoding; -use prost_types::FileDescriptorSet; -use prost_types::field_descriptor_proto::Type; - -/// What prost generates for `State` from the vendored proto. -#[derive(Clone, PartialEq, Message)] -struct GeneratedState { - #[prost(message, optional, tag = "1")] - composite: Option, - #[prost(map = "string, message", tag = "2")] - resources: HashMap, -} - -/// What prost generates for `Resource` from the vendored proto. -#[derive(Clone, PartialEq, Message)] -struct GeneratedResource { - #[prost(message, optional, tag = "1")] - resource: Option, - #[prost(map = "string, bytes", tag = "2")] - connection_details: HashMap>, - #[prost(enumeration = "Ready", tag = "3")] - ready: i32, -} /// Every map in the fixtures has one entry, because prost encodes maps in /// hash order and the tests compare encoded bytes. @@ -101,20 +84,6 @@ fn desired_bytes(rsp: &RunFunctionResponse) -> Vec { .encode_to_vec() } -#[test] -fn known_fields_encode_as_prost_generates_them() { - let state = known_state(); - let generated = GeneratedState::decode(state.encode_to_vec().as_slice()) - .expect("the generated message decodes hand-written output"); - - assert_eq!(state.encode_to_vec(), generated.encode_to_vec()); - assert_eq!(state.encoded_len(), generated.encoded_len()); - assert_eq!( - State::decode(generated.encode_to_vec().as_slice()).expect("decodes"), - state - ); -} - #[test] fn default_messages_encode_to_nothing() { assert!(State::default().encode_to_vec().is_empty()); @@ -199,48 +168,6 @@ fn a_known_field_with_the_wrong_wire_type_fails_to_decode() { assert!(error.to_string().contains("Resource.ready"), "{error}"); } -/// Feeds both messages every known field number with every wire type and a -/// few payloads, and expects the same verdict as the messages prost -/// generates. The generated messages drop unknown fields, so decoding the -/// hand-written output with them compares the known fields alone. -#[test] -fn malformed_input_decodes_as_prost_generates_it() { - let payloads: [&[u8]; 6] = [ - &[], - &[0x00], - &[0x01], - &[0x04, 0x0a, 0x02, b'h', b'i'], - &[0x00, 0x00, 0x00, 0x00], - &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], - ]; - for tag in 1..=4u8 { - for wire_type in 0..=5u8 { - for payload in payloads { - let mut input = vec![tag << 3 | wire_type]; - input.extend(payload); - - let state = State::decode(input.as_slice()); - let generated = GeneratedState::decode(input.as_slice()); - assert_eq!(state.is_ok(), generated.is_ok(), "State {input:?}"); - if let (Ok(state), Ok(generated)) = (state, generated) { - let known = GeneratedState::decode(state.encode_to_vec().as_slice()) - .expect("the generated message decodes hand-written output"); - assert_eq!(known, generated, "State {input:?}"); - } - - let resource = Resource::decode(input.as_slice()); - let generated = GeneratedResource::decode(input.as_slice()); - assert_eq!(resource.is_ok(), generated.is_ok(), "Resource {input:?}"); - if let (Ok(resource), Ok(generated)) = (resource, generated) { - let known = GeneratedResource::decode(resource.encode_to_vec().as_slice()) - .expect("the generated message decodes hand-written output"); - assert_eq!(known, generated, "Resource {input:?}"); - } - } - } - } -} - #[test] fn a_map_field_with_the_wrong_wire_type_fails_to_decode() { let error = Resource::decode([0x10, 0x00].as_slice()).expect_err("a map is not a varint"); @@ -263,29 +190,6 @@ fn unknown_fields_of_the_composite_resource_are_kept() { assert_eq!(decoded.encode_to_vec(), state); } -#[test] -fn debug_prints_ready_as_prost_generates_it() { - for ready in [0, 1, 2, 7] { - let resource = Resource { - ready, - ..Default::default() - }; - let generated = GeneratedResource { - ready, - ..Default::default() - }; - let want = format!("{generated:?}") - .replace("GeneratedResource", "Resource") - .replace(" }", ", unknown_fields: UnknownFields([]) }"); - assert_eq!(format!("{resource:?}"), want); - } - let ready = Resource { - ready: Ready::True as i32, - ..Default::default() - }; - assert!(format!("{ready:?}").contains("ready: True")); -} - #[test] fn clear_drops_unknown_fields() { let mut resource = @@ -314,43 +218,90 @@ fn known_state_without_composite() -> State { } } -/// The hand-written messages must be updated when the vendored proto -/// changes them. Until then a new field still passes through as an unknown -/// field, but functions cannot read or set it. +/// `message` as field `number` of the message that holds it. +fn field(number: u32, message: &[u8]) -> Vec { + let mut buf = Vec::new(); + encoding::bytes::encode(number, &message.to_vec(), &mut buf); + buf +} + +/// The fields Crossplane has added since the function API went v1 are on +/// the request, its meta, the response, the requirements and the resource +/// selector: none is on State or Resource. A function that forwards a +/// request, or returns a response it did not build, keeps what a newer +/// Crossplane or a newer function put on any of them. #[test] -fn hand_written_messages_cover_every_field_of_the_proto() { - let cases = [ - ( - "State", - vec![ - ("composite", 1, Type::Message), - ("resources", 2, Type::Message), - ], - ), - ( - "Resource", - vec![ - ("resource", 1, Type::Message), - ("connection_details", 2, Type::Message), - ("ready", 3, Type::Enum), - ], - ), - ]; - - let files = FileDescriptorSet::decode(FILE_DESCRIPTOR_SET).expect("the descriptor decodes"); - for (name, want) in cases { - let message = files - .file - .iter() - .filter(|file| file.package() == "apiextensions.fn.proto.v1") - .flat_map(|file| &file.message_type) - .find(|message| message.name() == name) - .unwrap_or_else(|| panic!("{name} is in the descriptor")); - let got: Vec<_> = message - .field - .iter() - .map(|field| (field.name(), field.number(), field.r#type())) - .collect(); - assert_eq!(got, want, "{name}: update sdk/src/proto/state.rs"); - } +fn unknown_fields_pass_through_every_message_of_a_request_and_a_response() { + let meta = RequestMeta { + tag: "tag".to_string(), + ..Default::default() + }; + let mut request = field(1, &with_unknown_fields(&meta)); + request.extend(field(3, &newer_state())); + request.extend(fields_from_a_newer_crossplane()); + + let decoded = RunFunctionRequest::decode(request.as_slice()).expect("decodes"); + assert_ne!(decoded.unknown_fields, UnknownFields::default()); + let decoded_meta = decoded.meta.as_ref().expect("has meta"); + assert_ne!(decoded_meta.unknown_fields, UnknownFields::default()); + assert_eq!(decoded_meta.tag, "tag"); + assert_eq!(decoded.encode_to_vec(), request); + + let selector = ResourceSelector { + api_version: "v1".to_string(), + kind: "Secret".to_string(), + ..Default::default() + }; + let mut selectors = Vec::new(); + encoding::hash_map::encode( + encoding::string::encode, + encoding::string::encoded_len, + encoding::bytes::encode, + encoding::bytes::encoded_len, + 2, + &HashMap::from([("secret".to_string(), with_unknown_fields(&selector))]), + &mut selectors, + ); + selectors.extend(fields_from_a_newer_crossplane()); + let result = FnResult { + message: "a message".to_string(), + ..Default::default() + }; + let response_meta = ResponseMeta { + tag: "tag".to_string(), + ..Default::default() + }; + let mut response = field(1, &with_unknown_fields(&response_meta)); + response.extend(field(2, &newer_state())); + response.extend(field(3, &with_unknown_fields(&result))); + response.extend(field(5, &selectors)); + response.extend(fields_from_a_newer_crossplane()); + + let decoded = RunFunctionResponse::decode(response.as_slice()).expect("decodes"); + assert_ne!(decoded.unknown_fields, UnknownFields::default()); + assert_ne!( + decoded.meta.as_ref().expect("has meta").unknown_fields, + UnknownFields::default() + ); + assert_ne!(decoded.results[0].unknown_fields, UnknownFields::default()); + let requirements: &Requirements = decoded.requirements.as_ref().expect("has requirements"); + assert_ne!(requirements.unknown_fields, UnknownFields::default()); + assert_ne!( + requirements.resources["secret"].unknown_fields, + UnknownFields::default() + ); + assert_eq!(requirements.resources["secret"].kind, "Secret"); + assert_eq!(decoded.encode_to_vec(), response); +} + +#[test] +fn debug_prints_an_enumeration_by_name_and_the_unknown_fields() { + let ready = Resource { + ready: Ready::True as i32, + ..Default::default() + }; + assert_eq!( + format!("{ready:?}"), + "Resource { resource: None, connection_details: {}, ready: True, unknown_fields: UnknownFields([]) }" + ); }