Skip to main content

catalog/
lib.rs

1//! Every generated connector operation, embedded at compile time.
2//!
3//! This is flux-connectors made consumable with `cargo add` instead of by copying artifacts into
4//! `~/.flux/flows`. Adding the crate *is* getting the catalog: every operation's Flux source and
5//! the metadata a caller needs to decide whether to run it are `&'static` data baked into the
6//! binary by `include_str!` and a generated table. There is no filesystem lookup, no parsing and
7//! no initialization; the one dependency is [`reader`] — the embedded catalog pack, itself
8//! dependency-free (C-537).
9//!
10//! It stays inside the charter (`AGENTS.md`): a library that hands out **text**, not a runtime.
11//! Nothing here executes an operation or touches the network — flux does that, from the module it
12//! loads.
13//!
14//! ```
15//! use catalog::{OperationKey, ProviderKey, Risk};
16//!
17//! let show = catalog::operation(OperationKey::id("zendesk-ticket-show")).unwrap();
18//! assert_eq!(show.risk, Risk::Low);
19//! assert!(show.flux.starts_with("op zendesk-ticket-show("));
20//!
21//! // "every operation in this provider" is one call.
22//! let zendesk = catalog::operations_of(ProviderKey::id("zendesk"));
23//! assert!(zendesk.iter().all(|operation| operation.provider == "zendesk"));
24//! ```
25//!
26//! # What is generated and what is not
27//!
28//! `flux-connectors build` writes three kinds of file into this crate, all committed and reviewed
29//! like every other generated artifact in the repository. **Nothing here is hand-written.**
30//!
31//! - `ops/<provider>/<operation>.flux` — one rendering per operation, byte for byte the same text
32//!   the provider's module carries for it;
33//! - `src/generated/<provider>.rs` — the table that embeds those renderings alongside their
34//!   metadata;
35//! - `src/generated.rs` — [`generated`], the index naming every provider's module.
36//!
37//! The first two are **per provider**, so `flux-connectors build --provider zendesk` regenerates
38//! exactly what it compiled. The index is not: it names every provider at once, so it is written by
39//! a **full** build only and a scoped run leaves the committed file untouched rather than rendering
40//! an index that drops the providers the run never looked at. `web/public/catalog.json` follows the
41//! same rule for the same reason.
42//!
43//! It was hand-written until C-104 on exactly that reasoning, and the cost was structural: two lines
44//! per provider, appended by hand, made this the one file every provider story touched — so any two
45//! provider stories conflicted and connectors shipped one at a time. `tests/embedded_operations.rs`
46//! still holds the list against `providers/`, which is now a staleness check on a committed artifact
47//! rather than a reminder to add a line.
48//!
49//! `crates/connector-cli/tests/catalog_artifacts.rs` is what makes the embedded data a *checked*
50//! artifact: it recomputes everything here from `providers/*.toml` and compares byte for byte, so a
51//! stale catalog — which still compiles and still answers every query — fails the build.
52//!
53//! # The per-provider module is still what ships
54//!
55//! `connectors/<provider>.flux` is unchanged in role: it is the artifact flux loads from
56//! `~/.flux/flows`, and it declares every one of that provider's operations. The renderings here
57//! are **additional** — the catalog's unit, not a substitute for the module — and each one is a
58//! substring of it (`tests/embedded_operations.rs` pins that).
59//!
60//! # Addressing, and what C-37 changes
61//!
62//! Operations are keyed today by [`Operation::id`], the declarable Flux symbol
63//! (`zendesk-ticket-show`). C-37 introduces a global address — an `oip` such as
64//! `com.zendesk.api/support/tickets:v2#show` — and the key types here exist so that lands
65//! **additively**: [`OperationKey`] and [`ProviderKey`] are opaque, constructed only through named
66//! constructors, so C-37 adds `OperationKey::oip` and `ProviderKey::pid` and no signature in this
67//! crate moves. There is deliberately no `From<&str>` for either: a bare string cannot say whether
68//! it is a symbol or an address, and guessing is exactly the ambiguity two identifiers exist to
69//! avoid.
70//!
71//! # The embedded pack, and what this crate is becoming (C-537)
72//!
73//! Decision 0022 (C-535) makes the compile destination a **catalog artifact**: one canonical JSON
74//! document per provider (C-536), compiled into one versioned, digest-carrying pack. This crate is
75//! the shim over that pack — it embeds it through [`reader`] and re-exports the reader whole, so
76//! every consumer of the catalogue already holds the document form of every operation:
77//!
78//! ```
79//! let show = catalog::reader::operation("zendesk-ticket-show").unwrap();
80//! assert_eq!(show.provider(), "zendesk");
81//! assert!(show.record().contains("\"id\": \"zendesk-ticket-show\""));
82//! ```
83//!
84//! The `&'static` tables beneath the API above remain generated Rust for now, because this API
85//! promises what the documents deliberately no longer carry — [`Operation::flux`], the emitted
86//! Flux text the documents replaced with a request template — and `connector-pack` still parses
87//! it. They reduce to the pack when C-540 retires the emitter; the deferral and its reasons are
88//! recorded in `docs/designs/catalog-artifact.md` §2. Nothing in this crate's public API moved to
89//! make room for the pack: the re-export is additive, which is what "no breaking change" means
90//! here, and `tests/consumer_api.rs` compiles the whole promised surface to hold that line.
91
92/// The catalog pack and its dependency-free reader, re-exported whole (C-537).
93///
94/// `catalog::reader::operation("zendesk-ticket-show")` serves the operation's canonical JSON
95/// record; `catalog::reader::Pack::load(path)` serves a newer pack than this crate was built
96/// with, refusing a wrong schema version or digest before serving any record. See
97/// `codewandler-connector-catalog-reader` for the format.
98pub use catalog_reader as reader;
99
100mod generated;
101
102/// How much damage an operation can do, in flux's own vocabulary.
103///
104/// A mirror of `connector_spec::Risk`, not a re-export: this crate resolves no machinery — its
105/// one dependency is the pack data behind [`reader`] — which is what makes it cheap to add. The
106/// mapping is exhaustive at the point of generation
107/// (`connector-cli`'s `catalog` module matches on every variant), so a variant added upstream is a
108/// compile error there rather than a silent omission here, and
109/// `tests/embedded_operations.rs::metadata_agrees_with_the_embedded_flux` pins every value against
110/// the `risk "…"` line of the Flux it describes.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub enum Risk {
113    /// Reads, and writes that cannot surprise anyone.
114    Low,
115    /// Writes with limited blast radius.
116    Medium,
117    /// Writes a reviewer would want to see first.
118    High,
119    /// Deletes or otherwise irreversible.
120    Destructive,
121}
122
123impl Risk {
124    /// The spelling flux's approval gate reads, and the one the embedded Flux declares.
125    pub const fn as_str(self) -> &'static str {
126        match self {
127            Risk::Low => "low",
128            Risk::Medium => "medium",
129            Risk::High => "high",
130            Risk::Destructive => "destructive",
131        }
132    }
133}
134
135/// Whether repeating an operation is safe, in flux's own vocabulary.
136///
137/// Mirrors `connector_spec::Idempotency` for the same reason [`Risk`] does.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
139pub enum Idempotency {
140    /// Repeating the call has the same effect as making it once.
141    Idempotent,
142    /// Repeating the call repeats its effect.
143    NonIdempotent,
144    /// Idempotent only under a condition the caller supplies (e.g. an idempotency key).
145    Conditional,
146}
147
148impl Idempotency {
149    /// The spelling the embedded Flux declares.
150    pub const fn as_str(self) -> &'static str {
151        match self {
152            Idempotency::Idempotent => "idempotent",
153            Idempotency::NonIdempotent => "non_idempotent",
154            Idempotency::Conditional => "conditional",
155        }
156    }
157}
158
159/// **Why an operation names the credentials it does** — and, when it names none, which of the two
160/// opposite reasons that is (C-235).
161///
162/// [`Operation::credentials`] is an empty slice in two situations that mean the reverse of each
163/// other, and a consumer reading only that slice gets one value for both. This field is what a
164/// connector *declares*, carried across rather than left to be inferred from an absence — the trap
165/// C-206 closed in the published catalogue and this closes in the embedded one.
166///
167/// # The vocabulary is C-206's
168///
169/// The two named states are the two codes `web/public/catalog.json` already publishes for the same
170/// distinction (`docs/designs/catalog-json.md`), and [`as_str`](Self::as_str) returns those tokens
171/// character for character. A host restating them in words of its own is how two surfaces
172/// describing one fact come to disagree, so this crate restates nothing:
173/// `connectors_api::api::Wiring` serializes these tokens directly.
174///
175/// [`Declared`](Self::Declared) is the ordinary case and has no published *status* code, because
176/// there is nothing to report about it — the operation names its mechanisms and the slice beside
177/// this field is them. It is given a token anyway so that every state has one name rather than two
178/// having names and one being "the other one".
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180pub enum CredentialRequirement {
181    /// The operation authenticates: [`Operation::credentials`] names at least one mechanism.
182    Declared,
183    /// **The vendor requires no credential**, declared positively by the connector (`auth = []` on
184    /// the operation). Nothing is withheld and nothing is missing: the unauthenticated call is the
185    /// correct working call.
186    NoneRequired,
187    /// **A credential is withheld.** Nothing is declared and nothing declares that nothing is
188    /// needed, so the request would go out unauthenticated — the fail-closed outcome, not a working
189    /// one. `freshdesk` is the shipped case: its API key occupies the Basic *username* position,
190    /// which this repository's model treats as non-secret config, so declaring it would route a
191    /// live key outside the secret gate (`AGENTS.md`, Intentional gaps).
192    ///
193    /// The operator-facing consequence is the part worth carrying: there is nothing for an operator
194    /// to supply *and* the operation does not work, which is neither of the other two states.
195    Withheld,
196}
197
198impl CredentialRequirement {
199    /// The token this state travels as — C-206's published spellings for the two it named.
200    ///
201    /// `no-credential-required` is `connector_cli::status::NO_CREDENTIAL_REQUIRED` and
202    /// `no-credential` is `connector_cli::status::NO_CREDENTIAL`, both of which are published
203    /// contract tokens that are extended but never renamed once shipped.
204    pub const fn as_str(self) -> &'static str {
205        match self {
206            CredentialRequirement::Declared => "declared",
207            CredentialRequirement::NoneRequired => "no-credential-required",
208            CredentialRequirement::Withheld => "no-credential",
209        }
210    }
211}
212
213/// The connector-authored vendor-state direction of an operation.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum OperationDirection {
216    /// The operation observes vendor state without changing it.
217    Read,
218    /// The operation changes vendor state.
219    Write,
220}
221
222impl OperationDirection {
223    /// The provider/public spelling shared by every artifact.
224    pub const fn as_str(self) -> &'static str {
225        match self {
226            Self::Read => "read",
227            Self::Write => "write",
228        }
229    }
230}
231
232/// One operation: its Flux source, and what a caller needs in order to decide whether to use it.
233///
234/// `#[non_exhaustive]` because C-37 adds the global address to this struct and C-10 adds the
235/// resolved endpoint spec; neither should be a breaking change for a consumer. C-197's
236/// [`service`](Self::service) is the first field to land on that headroom, and it is what the
237/// attribute was for: a consumer outside this crate can neither construct one with a struct literal
238/// nor destructure one exhaustively, so a field arriving is additive for them and breaking only for
239/// the generated tables in this crate, which the same build rewrites.
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241#[non_exhaustive]
242pub struct Operation {
243    /// The Flux symbol the operation is declared and called by, e.g. `zendesk-ticket-show`. Unique
244    /// across the whole catalog, and the key [`OperationKey::id`] matches on.
245    pub id: &'static str,
246    /// The [`Provider::id`] this operation belongs to.
247    pub provider: &'static str,
248    /// The **service** this operation belongs to — `delivery`, `s3`, or the reserved `default` for
249    /// a provider with a single API surface. Never empty: the IR always names a service
250    /// (`connector_spec::ir::DEFAULT_SERVICE`), and the reserved name is elided from *addresses*
251    /// only, never from this field.
252    ///
253    /// # Why it is here, and what was wrong without it (C-197)
254    ///
255    /// Services partition the operation set, and a service owns its own `base_url` — so
256    /// [`Operation::hosts`] is already per service. What was missing was the *name*, and a consumer
257    /// that cannot read it cannot key anything by service.
258    ///
259    /// `connector-pack`'s configuration port is where that bit. It keyed a tenant's endpoint values
260    /// on `(tenant, provider, kind, name)`, because there was no service here to key on, so two
261    /// services of one connector that spell the same `{variable}` in their own `base_url` collapsed
262    /// to a single value. `contentful` is the shipped case: `delivery_space_id` and
263    /// `management_space_id` are two declared configuration fields, both binding `endpoint.space_id`
264    /// under different services, and `contentful-entry-create` on `api.contentful.com` resolved
265    /// whatever `contentful-entry-get` on `cdn.contentful.com` had. A tenant whose two environments
266    /// differ got a `200` from the wrong one rather than a refusal.
267    ///
268    /// `web/public/catalog.json` had carried the service all along; this is the embedded catalogue
269    /// catching up, which is why every provider's generated table moved when it landed.
270    pub service: &'static str,
271    /// Whether this operation reads or writes vendor state. Authored in the connector declaration;
272    /// never inferred from its HTTP method or any policy metadata.
273    pub direction: OperationDirection,
274    /// What the operation does, in one line — the same text the model sees as the tool description.
275    pub description: &'static str,
276    /// How much damage it can do.
277    pub risk: Risk,
278    /// Whether repeating it is safe.
279    pub idempotency: Idempotency,
280    /// Flux semantic-effect tags (`money`, `delete`, `send_external`, …), distinct from the host
281    /// effects carried by [`Self::flux`]. Empty means no semantic consequence is declared.
282    pub semantic_effects: &'static [&'static str],
283    /// The credentials the operation needs, as **alternatives of mechanisms**: the outer slice is
284    /// an OR over ways to authenticate, and each inner slice is the set of credentials that must
285    /// all be satisfied on the same request (AND).
286    ///
287    /// `&[&["babelforce.access_id", "babelforce.access_token"]]` is one mechanism needing two
288    /// headers together, not two ways to authenticate — the distinction babelforce forces and that
289    /// a flat list of credential names cannot express. An empty outer slice means the operation
290    /// needs no credential at all.
291    ///
292    /// The names are credential *references*. No secret, and no environment variable's value, is
293    /// ever in this crate — flux resolves the reference and applies the scheme.
294    ///
295    /// **An empty outer slice does not say why**, which is what [`credential_requirement`] is for.
296    ///
297    /// [`credential_requirement`]: Self::credential_requirement
298    pub credentials: &'static [&'static [&'static str]],
299    /// **Why [`credentials`](Self::credentials) is what it is** — and, when it is empty, which of
300    /// the two opposite reasons that is (C-235). See [`CredentialRequirement`].
301    ///
302    /// It is a separate field rather than a richer `credentials` because the type of that field is
303    /// this crate's published API: a consumer already matching on the mechanism list keeps working,
304    /// and one that needs the reason reads a field that was not there before. `Operation` is
305    /// `#[non_exhaustive]` precisely so that is additive.
306    ///
307    /// The invariant, held at emission and pinned by
308    /// `tests/embedded_operations.rs::the_declared_requirement_agrees_with_the_mechanism_list`:
309    /// this is [`Declared`](CredentialRequirement::Declared) exactly when `credentials` is
310    /// non-empty.
311    pub credential_requirement: CredentialRequirement,
312    /// The hosts a call reaches, as the connector's base URL spells them — templating included, so
313    /// Zendesk is `{subdomain}.zendesk.com` rather than a tenant nobody has chosen yet. What a
314    /// caller does with this is decide whether their egress policy admits the call.
315    pub hosts: &'static [&'static str],
316    /// The operation's Flux source: exactly the `op` declaration
317    /// `connectors/<provider>.flux` carries for it.
318    pub flux: &'static str,
319}
320
321/// **Where a credential goes on the way out** — the *placement* axis of
322/// `docs/designs/unified-auth.md`.
323///
324/// The design's central claim is carried by one field: `prefix` on [`Header`](Self::Header) is what
325/// turns `Bearer` from an enum variant into data, so `Bearer `, `Basic `, `Token `, `GenieKey ` and
326/// the empty prefix are one code path rather than five variants. A flat scheme enum conflates
327/// *where* a secret goes with *what it is prefixed by*, and needs a new variant the moment a vendor
328/// wants `Token <t>` in `Authorization`.
329///
330/// Deliberately **not** `#[non_exhaustive]`, unlike [`Provider`] and [`Operation`]. A consumer
331/// placing a credential must match every variant, and a new placement must be a compile error at
332/// every such site rather than a silently skipped credential — a request that quietly went out
333/// without one is exactly the failure this type exists to prevent.
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
335pub enum Placement {
336    /// `<name>: <prefix><value>`. `Authorization: Bearer <t>` is
337    /// `Header { name: "Authorization", prefix: "Bearer " }`; a raw-value header such as
338    /// `X-Shopify-Access-Token` is the same variant with an empty prefix.
339    Header {
340        /// The header name.
341        name: &'static str,
342        /// The literal text the value is prefixed with, **trailing space included**. Empty for a
343        /// raw-value header.
344        prefix: &'static str,
345    },
346    /// `?<name>=<value>` — a query-parameter key.
347    Query {
348        /// The parameter name.
349        name: &'static str,
350    },
351    /// **Never placed on an outgoing request.** A webhook signing secret verifies bytes that
352    /// arrived, so it has no answer to "where does this go on the way out" — the one deliberate
353    /// divergence from flux's vocabulary, recorded in `AGENTS.md`'s authentication contract. It is
354    /// here so that one credential namespace covers both directions.
355    Inbound,
356}
357
358/// **How stored material becomes the value that is placed** — the *acquisition* axis.
359///
360/// Two of the three are pure: the stored secret is placed unchanged, or it is joined into a Basic
361/// pair. The third, [`Minted`](Self::Minted), is the one effectful acquisition this repository
362/// models, and it is modelled as *provenance* rather than as a step a connector performs — see its
363/// own documentation. The remaining effectful ones — token refresh, expiry, `session` — are still
364/// the host's, by the line `docs/designs/unified-auth.md` draws: they need a cache and a
365/// refresh-on-401, and C-90 put both out of scope.
366///
367/// Not `#[non_exhaustive]`, for the reason [`Placement`] is not.
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
369pub enum Acquisition {
370    /// The stored secret, unchanged.
371    Static,
372    /// **The stored secret, unchanged — and one of this connector's own operations put it there**
373    /// (C-136).
374    ///
375    /// Read as a *placement* instruction this is [`Static`](Self::Static): a minted credential goes
376    /// onto a request exactly as a statically provisioned one does, because by the time anything
377    /// places it, it is a value in the store like any other. What the variant adds is the fact the
378    /// diversion needs, and which nothing else in the catalogue carries: **which call mints it, and
379    /// where in that call's answer the value arrives**.
380    ///
381    /// `connector-pack` reads it from the minting side. Projecting an operation, it looks for the
382    /// declared credential whose [`by`](Self::Minted::by) is that operation's own id; finding one
383    /// makes the operation credential-producing, and its result stops being the vendor's body and
384    /// becomes the handle `{ "credential": "tenants/…" }`. A downstream operation that *uses* the
385    /// credential names it in `credentials` like any other and never sees a value — which is the
386    /// property C-136 exists for: **a caller can use a credential it can never read.**
387    ///
388    /// # Why the fact lives on the credential rather than on the operation
389    ///
390    /// It reads as though it belongs on [`Operation`], and semantically it is the operation's
391    /// declaration — `produces_credential` in the provider file sits in the `[[operations]]` block.
392    /// It is carried here because it is also, exactly, an answer on this axis, and because a field
393    /// on `Operation` is a field every one of the catalogue's generated tables must state: adding
394    /// one rewrites every `crates/catalog/src/generated/<provider>.rs`, every artifact hash under
395    /// it, and `connectors.lock` — for a fact no shipped connector declares. A variant costs
396    /// nothing until something uses it, which is the same reason `skip_serializing_if` is on the IR
397    /// field.
398    Minted {
399        /// The [`Operation::id`] whose call mints this credential.
400        by: &'static str,
401        /// Where the secret arrives in that operation's response body — **one** JSON Pointer into
402        /// the response value, `/access_token`.
403        ///
404        /// Exactly one location, and the loader refuses anything else. `credential_response`'s
405        /// sibling vocabulary admits `*` for every element of an array because it describes where
406        /// credentials *appear*; a mint stores one value at one address, so there would be nothing
407        /// to say which element it was. That is also what keeps this field's documented behaviour
408        /// and the runtime's the same thing: the diversion resolves it with
409        /// `serde_json::Value::pointer`, which has no wildcard.
410        from: &'static str,
411    },
412    /// `base64(<user><user_suffix>:<secret>)` — HTTP Basic, composed rather than pre-composed.
413    ///
414    /// The user half is **config, not a gated secret**: it is an email address or an account name,
415    /// and it resolves from the declared environment variables rather than from the secret store.
416    /// `user_suffix` is Zendesk's `/token` marker — public API syntax, and the reason a bare env
417    /// value is not enough (`docs/designs/auth-seam.md` §7.5).
418    ///
419    /// The secret occupies the **password** position. Freshdesk's shape, where the API key occupies
420    /// the *username* position, is not expressible here because the IR cannot yet say so either
421    /// (C-16 owns that decision); Freshdesk therefore declares no credential at all, which
422    /// `AGENTS.md` records as an intentional gap rather than an oversight.
423    BasicJoin {
424        /// Environment-variable **keys** holding the user half, tried in order. Never a value.
425        user_env: &'static [&'static str],
426        /// A literal appended to the resolved user half before the `user:secret` join.
427        user_suffix: &'static str,
428    },
429    /// **The host runs an OAuth2 grant and places the resulting access token** (C-525).
430    ///
431    /// Read as a placement instruction this is [`Static`](Self::Static) too — a freshly granted
432    /// access token goes onto the request exactly as a pasted one does. What the variant adds is
433    /// the only thing a host cannot derive from anything else in the catalogue: **which endpoints
434    /// the grant runs against, which grants this credential allows, and what it asks for.**
435    ///
436    /// It is on this axis rather than on [`Credential`] because that is what this axis *is* — how
437    /// stored material becomes the value that is placed — and because [`Minted`](Self::Minted)
438    /// settled the same question the same way: a variant costs nothing until something uses it,
439    /// whereas a field on `Credential` rewrites every generated table for a fact most connectors
440    /// never declare.
441    ///
442    /// **Nothing in this repository performs the grant.** An authorize endpoint is a browser
443    /// redirect and a token endpoint's response body *is* a credential, so neither is a connector
444    /// operation and neither is emitted into a `.flux` module. This variant is the declaration a
445    /// host reads before doing it itself.
446    OAuth2(&'static OAuth2),
447}
448
449/// How a host obtains an OAuth2-backed credential. Mirrors `connector_spec::OAuth2Spec`.
450///
451/// **Carries no secret and has no field one could occupy.** [`client_id`](Self::client_id) is
452/// public by specification (RFC 6749 §2.2); the client *secret* is a `[[config]]` binding the host
453/// resolves from its own store and never appears here, in a provider TOML, or in any generated
454/// artifact.
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
456pub struct OAuth2 {
457    /// The declared endpoint name whose base URL [`authorize_path`](Self::authorize_path) and
458    /// [`token_path`](Self::token_path) resolve against. Empty means the connector's own base URL.
459    ///
460    /// It is a name rather than a URL because the endpoint's host allow-list is what admits the
461    /// token exchange through the egress gate; a bare URL would name a host nothing had admitted.
462    pub endpoint: &'static str,
463    /// The declared service name whose base URL [`token_path`](Self::token_path) resolves against
464    /// when the token endpoint lives on a **different host** from the authorize endpoint (C-556).
465    /// Empty — every shipped declaration's value — means the token exchange resolves against
466    /// [`endpoint`](Self::endpoint), which is a connector's single-host behaviour unchanged.
467    ///
468    /// A host joins [`token_path`](Self::token_path) onto this service's base URL when it is set, and
469    /// onto [`endpoint`](Self::endpoint)'s otherwise. It is a name and never a URL, for the same
470    /// reason [`endpoint`](Self::endpoint) is: the host set is derived from declared services.
471    pub token_endpoint: &'static str,
472    /// The authorize endpoint path, joined onto the endpoint base URL.
473    pub authorize_path: &'static str,
474    /// The token endpoint path. Every grant and every refresh POSTs here. It resolves against
475    /// [`token_endpoint`](Self::token_endpoint)'s base URL when that is set, and
476    /// [`endpoint`](Self::endpoint)'s otherwise.
477    pub token_path: &'static str,
478    /// The OAuth2 client id. Public by specification — see the type's own documentation.
479    pub client_id: &'static str,
480    /// The scopes the grant requests.
481    pub scopes: &'static [&'static str],
482    /// The grants a host may run for this credential. A grant absent from this list is one the
483    /// connector does not allow, not one the host may try anyway.
484    pub grants: &'static [OAuthGrant],
485    /// The loopback redirect an [`OAuthGrant::AuthorizationCode`] login binds.
486    pub redirect: Option<OAuthRedirect>,
487    /// Whether this is a public PKCE client that issues and uses no client secret (C-556). `false`
488    /// — every shipped declaration's value — is a confidential client, which registers a client
489    /// secret an operator supplies. A public client needs a [`client_id`](Self::client_id) but no
490    /// secret, so a host must not require one.
491    pub public_client: bool,
492}
493
494/// One token grant an [`OAuth2`] credential allows. Mirrors `connector_spec::OAuthGrant`.
495///
496/// Closed, for the reason [`Placement`] is: a grant this did not recognise would have to become
497/// *some* grant, and every wrong answer either sends a credential to an endpoint that does not
498/// expect it or runs a flow the connector never allowed.
499#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
500pub enum OAuthGrant {
501    /// Browser redirect plus loopback callback, with PKCE.
502    AuthorizationCode,
503    /// The resource-owner password grant. RFC 6749 §4.3.2 makes discarding the password a MUST for
504    /// the client, and a host running this one is that client.
505    Password,
506    /// Exchange a stored refresh token for a fresh access token.
507    RefreshToken,
508    /// The two-legged client-credentials grant, with no user.
509    ClientCredentials,
510}
511
512/// The loopback redirect an `authorization_code` login binds. Mirrors
513/// `connector_spec::OAuthRedirect`.
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
515pub struct OAuthRedirect {
516    /// The loopback port to bind.
517    pub port: u16,
518    /// The callback path the browser is redirected to.
519    pub path: &'static str,
520}
521
522/// **Whose authority a credential carries when it is used** (C-528). Mirrors
523/// `connector_spec::Subject`.
524///
525/// The "on behalf of" axis, independent of every other one: [`Placement`] says where the value goes,
526/// [`Acquisition`] says how it is obtained, and this says *who the vendor thinks is acting* once it
527/// arrives. Slack is the case that forces it — one OAuth v2 grant returns a workspace bot token and
528/// a signed-in user's token in one response, placed identically and acquired identically, differing
529/// only in who they can act as.
530///
531/// A host reads this to bound a credential's reach and to decide where it may be stored: an
532/// app-subject credential is provisioned once for a tenant, a user-subject one once per person, and
533/// keeping a user token at a tenant-wide address would let one member act as another.
534///
535/// # `Unstated` is a real answer and must be handled
536///
537/// It means *"nobody has reviewed this credential for its subject"* — not "app". Every connector
538/// shipped before C-528 carries it, including genuinely ambiguous ones: GitHub's single
539/// `github.token` covers both an App installation token and a personal access token, which are
540/// opposite answers. **A consumer that needs the distinction refuses on `Unstated`** rather than
541/// assuming; assuming `App` over-grants, and assuming `User` silently fails.
542#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
543pub enum Subject {
544    /// Not reviewed. Carries no claim in either direction — refuse rather than choose one.
545    #[default]
546    Unstated,
547    /// The integration itself: Slack's `xoxb-` bot token, a GitHub App installation token.
548    App,
549    /// The person who granted it — "on behalf of": Slack's `xoxp-` user token, an Atlassian 3LO
550    /// token, a personal access token.
551    User,
552}
553
554/// **A named weakness in how a credential is obtained** (C-440). Mirrors
555/// `connector_spec::AuthHazard`.
556///
557/// The axis a host refuses on, and it is deliberately a *declared property* rather than a connector
558/// name: an operator who wants no password-grant authentication anywhere says that once, and the
559/// fifty-sixth connector — added next month by somebody who never read their policy — is covered by
560/// the same sentence. A list of names is correct on the day it is written and silently wrong
561/// afterwards.
562///
563/// # This is a *kind*. [`Risk`] is a *level*
564///
565/// Not interchangeable, and the difference is load-bearing because [`Risk`] is **ordered** and a
566/// selector compares against that ordering. A hazard has no position on that ladder: a password
567/// grant that buys a **read-only** token is [`Risk::Low`] *and* hazardous. A fifth rung would be
568/// wrong in one direction or the other — high enough to catch it and every destructive operation
569/// inherits a weakness it does not have; low enough not to and `at_most(Risk::High)` silently
570/// admits password-grant authentication to every rule an operator has already written.
571///
572/// # The absence is not a clean bill of health
573///
574/// `None` on a [`Credential`] means *no weakness is declared*, which is the state every connector
575/// but babelforce is in and which nobody has reviewed. It does not mean *reviewed and found safe*.
576/// A consumer's fail-closed default is written against the presence of a value.
577///
578/// Not `#[non_exhaustive]`, for the reason [`Placement`] is not: a consumer matching exhaustively
579/// *should* be told when the set grows, because a new hazard is a new weakness they have not decided
580/// about — and defaulting it into a catch-all arm is how a deployment admits one it never saw.
581#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
582pub enum AuthHazard {
583    /// The resource owner's own password is presented to **the host** rather than to the
584    /// authorization server — the OAuth 2.0 resource owner password credentials grant.
585    ///
586    /// **RFC 9700 §2.4** says the grant MUST NOT be used: it exposes the resource owner's
587    /// credentials to the client, widens where they can leak beyond the authorization server, and
588    /// cannot carry two-factor authentication. **RFC 6749 §4.3** makes discarding them once a token
589    /// is obtained a MUST for the client, and a host running the grant is that client. **CWE-522**
590    /// is the nearest weakness-catalogue entry. OAuth 2.1 drops the grant entirely.
591    ResourceOwnerSecretShared,
592}
593
594impl AuthHazard {
595    /// The stable published spelling a host's deployment filter matches as an exact word.
596    ///
597    /// Matched exhaustively rather than derived, for the reason [`Subject`] is: the string is
598    /// configuration an operator audits in another repository, and it must not move because a
599    /// derive attribute did.
600    pub const fn word(self) -> &'static str {
601        match self {
602            Self::ResourceOwnerSecretShared => "resource_owner_secret_shared",
603        }
604    }
605}
606
607/// One credential a connector declares: what it is called, where its value is kept, and how it
608/// reaches the wire.
609///
610/// **No value, ever**, and no field it could occupy: [`Credential::leaf`] is the last segment of a
611/// *path*, [`Acquisition`] names environment-variable *keys*, and [`Placement`] names a header, a
612/// prefix or a query key. This crate is `&'static` data compiled from the IR, so "it holds no secret"
613/// is a property of the shape rather than a habit of whoever last edited the emitter.
614///
615/// Not `#[non_exhaustive]`: a consumer constructs one in a test to prove its own placement code, and
616/// the type is small, declarative and complete.
617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
618pub struct Credential {
619    /// The flat-namespace name an operation references, e.g. `zendesk.api_token`. Vendor-prefixed,
620    /// because credentials share one namespace across the connector.
621    pub name: &'static str,
622    /// The last segment of the credential's address — `api_token`, not `zendesk.api_token`. The
623    /// path already carries the authority, so the vendor prefix would be said twice.
624    pub leaf: &'static str,
625    /// How stored material becomes the value that is placed.
626    pub acquire: Acquisition,
627    /// Where that value goes on the request.
628    pub place: Placement,
629    /// Whose authority the value carries once it arrives — see [`Subject`].
630    ///
631    /// Unlike the three fields above, this one has a meaningful *unreviewed* state, and every
632    /// connector shipped before C-528 is in it. Read [`Subject::Unstated`] before branching on this.
633    pub subject: Subject,
634    /// The declared weakness in **obtaining** this credential, when it has one — see [`AuthHazard`].
635    ///
636    /// `None` means no weakness is declared, not that one was looked for and not found. A host
637    /// refuses a hazardous acquisition unless its deployment explicitly opted into that hazard,
638    /// which is what makes the refusal a property rather than a list of connector names.
639    pub hazard: Option<AuthHazard>,
640}
641
642/// One string pair in a generated declaration (query, header or payload mapping).
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub struct Pair {
645    pub name: &'static str,
646    pub value: &'static str,
647}
648
649/// How an event reaches a connector binding.
650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
651pub enum ChannelTransport {
652    Webhook,
653    Socket,
654    Poll,
655}
656
657/// One event declaration, including the local/wire identity split.
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
659pub struct Event {
660    pub name: &'static str,
661    pub service: &'static str,
662    pub description: &'static str,
663    pub wire_value: Option<&'static str>,
664    pub default: bool,
665    pub group: &'static str,
666    /// Canonical JSON Schema text, or `None` when the vendor publishes none.
667    pub schema: Option<&'static str>,
668    /// Canonical JSON for the complete source declaration, including narrowing rules.
669    pub declaration_json: &'static str,
670}
671
672/// The generic RFC 6455 handshake facts for one socket binding.
673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674pub struct SocketConnect {
675    pub path: &'static str,
676    pub query: &'static [Pair],
677    pub headers: &'static [Pair],
678    pub auth: &'static [&'static [&'static str]],
679    pub subprotocols: &'static [&'static str],
680}
681
682/// One selector into an inbound envelope.
683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
684pub struct Selector {
685    pub source: &'static str,
686    pub name: &'static str,
687}
688
689/// One generated channel binding. Verification/reply/setup remain available in the manifest and
690/// public catalogue; this embedded shape carries every fact the zero-I/O socket planner and generic
691/// event router require.
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub struct Channel {
694    pub name: &'static str,
695    pub service: &'static str,
696    /// The service base URL against which [`SocketConnect::path`] is derived.
697    pub base_url: &'static str,
698    pub description: &'static str,
699    pub transport: ChannelTransport,
700    pub events: &'static [&'static str],
701    pub connect: Option<SocketConnect>,
702    pub discriminator: Option<Selector>,
703    /// Stable vendor delivery identity used for deduplication, when declared.
704    pub delivery_id: Option<Selector>,
705    pub payload: &'static [Pair],
706    pub payload_root: bool,
707    /// Canonical JSON for the complete binding declaration, including verification and reply.
708    pub declaration_json: &'static str,
709}
710
711/// One complete configuration field, with no stored value.
712///
713/// Activation policy is carried as [`Approval`] rather than left inside [`Self::declaration_json`]:
714/// a host enforcing whether a configured value may become active must match a closed vocabulary,
715/// not search serialized source text for a token.
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
717pub struct ConfigField {
718    pub name: &'static str,
719    pub service: &'static str,
720    pub label: &'static str,
721    pub help: &'static str,
722    pub example: Option<&'static str>,
723    pub format: &'static str,
724    pub required: bool,
725    pub default: Option<&'static str>,
726    /// Extra authorization required before the configured value becomes active.
727    pub approval: Approval,
728    pub secret: bool,
729    pub docs_url: Option<&'static str>,
730    pub binds: &'static str,
731    pub also_binds: &'static [&'static str],
732    /// The further services whose base URL this one value also fills (C-529).
733    ///
734    /// Empty for the ordinary field. When it is not, [`service`](Self::service) remains the address
735    /// the value is stored under and the services named here resolve their `{variable}` from that
736    /// same address — one question, one value, one [`approval`](Self::approval). A host composing a
737    /// URL for a sibling service must consult this or it will report an unbound placeholder for a
738    /// value the operator has already supplied.
739    pub also_services: &'static [&'static str],
740    /// Canonical JSON for the complete form declaration, including choices.
741    pub declaration_json: &'static str,
742}
743
744/// Extra authorization required before a supplied configuration value becomes active.
745///
746/// Mirrors `connector_spec::Approval`. Deliberately closed: a new activation policy must produce a
747/// compile error in every consumer that decides whether a value may influence a request.
748#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
749pub enum Approval {
750    /// The ordinary configuration flow may activate the value.
751    #[default]
752    None,
753    /// A deployment operator must approve and pin a non-default value for this connection.
754    Operator,
755}
756
757impl Approval {
758    /// The stable token used by the connector declaration and public catalogue.
759    pub const fn as_str(self) -> &'static str {
760        match self {
761            Self::None => "none",
762            Self::Operator => "operator",
763        }
764    }
765}
766
767/// **How a connector executes** — flux's runtime axis, as the catalogue publishes it (C-405).
768///
769/// The vocabulary mirrors flux's `docs/designs/ecosystem.md`, which replaces the plugin-versus-
770/// connector dichotomy with one axis: a plugin is a runtime kind a connector may declare, not a
771/// rival of one. It is the same closed set `connector_spec::Runtime` accepts at load; the emitter
772/// translates one into the other, so a variant that existed on only one side would not compile.
773///
774/// # What a consumer does with it
775///
776/// HTTP is easy to multi-tenant because the effect leaves the machine. Process spawning, container
777/// exec and raw sockets do not — they consume the host's own identity, network position, filesystem
778/// and descriptors — so **a host serving more than one tenant refuses a locally-executing runtime**.
779/// That refusal is mechanical only if the runtime is a declared fact, which is what this field is:
780/// before it existed a consumer derived [`Http`](Self::Http) and was right, and would have stayed
781/// right until the first connector that was not, at which point it was silently wrong for exactly
782/// the case the refusal exists to catch.
783///
784/// Deliberately carries **no** `is_local()` predicate. Which runtimes a deployment admits is the
785/// host's judgment (flux-exchange's `Deployment::admits`), and this crate publishes vendor facts;
786/// putting the policy here would make the catalogue an authority on a question it cannot see the
787/// inputs to.
788///
789/// Not `#[non_exhaustive]`, for the reason [`Placement`] is not: it is a closed set mirrored from a
790/// design, and a consumer matching exhaustively on it *should* be told when the set grows, because
791/// a new runtime is a new effect they have not decided about.
792#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
793pub enum Runtime {
794    /// A guarded HTTP request. Every connector this repository generates.
795    #[default]
796    Http,
797    /// A guarded dial — TCP, UDP or ICMP. **Locally executing.**
798    Socket,
799    /// A guarded, argv-only spawn under a sandbox backend. **Locally executing.**
800    Process,
801    /// A spawn inside docker or kubernetes. **Locally executing.**
802    Container,
803    /// The flux plugin protocol over stdio — a special case of [`Process`](Self::Process).
804    /// **Locally executing.**
805    Plugin,
806    /// Delegation to another substrate. Not locally executing: the effect leaves the machine.
807    Remote,
808}
809
810impl Runtime {
811    /// The token this runtime is published as, in `catalog.json` and in every `.connector.toml`.
812    pub fn word(self) -> &'static str {
813        match self {
814            Self::Http => "http",
815            Self::Socket => "socket",
816            Self::Process => "process",
817            Self::Container => "container",
818            Self::Plugin => "plugin",
819            Self::Remote => "remote",
820        }
821    }
822}
823
824/// One connector, and every operation the catalog carries for it.
825///
826/// `#[non_exhaustive]` for the same reason [`Operation`] is: C-37's `pid` lands here.
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
828#[non_exhaustive]
829pub struct Provider {
830    /// The connector id, e.g. `zendesk`. Names `connectors/<id>.flux`, and is the key
831    /// [`ProviderKey::id`] matches on.
832    pub id: &'static str,
833    /// The vendor's display name.
834    pub vendor: &'static str,
835    /// What the connector is for, in one line.
836    pub description: &'static str,
837    /// The reverse-DNS authority the connector publishes under (`com.slack.api`) — C-37's `pid`,
838    /// and the second segment of every credential address this connector's secrets live at.
839    ///
840    /// `None` for a connector that has not declared one yet. That is not cosmetic: without an
841    /// authority no credential address renders at all, so a consumer resolving credentials can only
842    /// refuse. Refusing is the correct answer — a request sent without the credential it declares is
843    /// the failure worth preventing — but the diagnostic must say *which* fact is missing.
844    pub authority: Option<&'static str>,
845    /// **How this connector executes** — see [`Runtime`]. `Http` for every connector shipped today,
846    /// and stated rather than assumed, which is the whole of C-405.
847    pub runtime: Runtime,
848    /// The API base URL, templating included.
849    pub base_url: &'static str,
850    /// Every credential the connector declares, in declaration order and keyed by
851    /// [`Credential::name`] — the vocabulary [`Operation::credentials`] references by name.
852    ///
853    /// Declared at **provider** level, exactly as the IR declares them: a credential belongs to the
854    /// connector, not to one of its services, which is why its address elides the service segment.
855    pub auth: &'static [Credential],
856    /// Every operation, in the order the provider declares them — which is also the order they
857    /// appear in `connectors/<id>.flux`.
858    pub operations: &'static [Operation],
859    /// Complete configuration declarations, never values.
860    pub config: &'static [ConfigField],
861    /// The bounded, low-risk operation a host invokes to verify this connector's configuration.
862    ///
863    /// The operation id is guaranteed by the loader to name one of [`Self::operations`]. `None`
864    /// means the connector declares no Test-connection read; it is not an invitation to guess one.
865    pub verify: Option<&'static str>,
866    /// Inbound events in declaration order.
867    pub events: &'static [Event],
868    /// Channel bindings in declaration order.
869    pub channels: &'static [Channel],
870    /// **Every configuration field whose value comes from a closed set** — C-225.
871    ///
872    /// Empty for most connectors. Present for the ones whose value is a *choice* rather than a
873    /// string the operator knows: New Relic's two region hosts, Intercom's three.
874    ///
875    /// The complete declaration is available through [`Self::config`] (C-87). This stays as the
876    /// indexed compatibility view for consumers that address the set by `(service, kind, name)`.
877    pub config_choices: &'static [ConfigChoices],
878}
879
880/// One configuration field that permits a closed set of values, and the set — C-225.
881///
882/// Addressed the way the runtime configuration port addresses a stored value: by
883/// `(service, kind, name)`, where `kind` is `endpoint`, `path`, `query`, `header`, `username` or
884/// `oauth` and `name` is the binding target within it. `field` is the declaration's own name, which
885/// is what a form labels the row with and what an error message quotes.
886///
887/// Not `#[non_exhaustive]`: a consumer builds one in a test to prove its own rendering, exactly as
888/// it does with [`Credential`].
889#[derive(Debug, Clone, Copy, PartialEq, Eq)]
890pub struct ConfigChoices {
891    /// The service whose configuration this is. Written out, `default` included, because a consumer
892    /// grouping by service needs a name in every row (C-197).
893    pub service: &'static str,
894    /// The declared field name — `host`. The key a host stores the collected value under.
895    pub field: &'static str,
896    /// The form label — `New Relic API host`.
897    pub label: &'static str,
898    /// Where the value goes: `endpoint`, `path`, `query`, `header`, `username` or `oauth`.
899    pub kind: &'static str,
900    /// The name within `kind` — the base-URL `{variable}`, the pinned wire name, the credential.
901    pub name: &'static str,
902    /// The permitted values, in the vendor's own order.
903    pub choices: &'static [Choice],
904}
905
906/// One permitted value of a [`ConfigChoices`] set, and the text a renderer shows for it.
907///
908/// The label is what makes the set usable: an operator knows their account is in Frankfurt and does
909/// not know that `api.eu.newrelic.com` is what that means.
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911pub struct Choice {
912    /// The value itself — what a host stores and what substitution puts on the request.
913    pub value: &'static str,
914    /// The human name for it — `European Union`.
915    pub label: &'static str,
916}
917
918impl Provider {
919    /// One of this provider's operations, by key.
920    pub fn operation(&self, key: OperationKey<'_>) -> Option<&'static Operation> {
921        self.operations
922            .iter()
923            .find(|operation| key.matches(operation))
924    }
925
926    /// The credential this connector declares under `name`, or `None` when nothing declares it.
927    ///
928    /// A lookup rather than a map because the list is short, ordered and generated; the ordering is
929    /// the connector's own, and an alternative-selection rule that depends on declaration order
930    /// needs it preserved.
931    pub fn credential(&self, name: &str) -> Option<&'static Credential> {
932        self.auth.iter().find(|credential| credential.name == name)
933    }
934
935    /// One declared channel binding, by its service-local name.
936    pub fn channel(&self, name: &str) -> Option<&'static Channel> {
937        self.channels.iter().find(|channel| channel.name == name)
938    }
939
940    /// The closed set governing one configuration slot, addressed exactly as the runtime port
941    /// addresses a stored value — `(service, kind, name)`.
942    ///
943    /// `None` means the slot is open, **not** that the value is unconstrained by anything: the full
944    /// [`ConfigField`] still carries its format. A caller uses this indexed view to decide between a
945    /// select and an input, and to refuse a value it was not offered.
946    pub fn choices_for(
947        &self,
948        service: &str,
949        kind: &str,
950        name: &str,
951    ) -> Option<&'static ConfigChoices> {
952        self.config_choices
953            .iter()
954            .find(|entry| entry.service == service && entry.kind == kind && entry.name == name)
955    }
956}
957
958/// How a caller names one operation.
959///
960/// A key type rather than a bare `&str` so that C-37's global address becomes a *constructor* —
961/// `OperationKey::oip(…)` — instead of a reshape of every lookup in the crate. The field is
962/// private and there is no `From<&str>`: a caller states which kind of name they hold.
963#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
964pub struct OperationKey<'a> {
965    /// The Flux symbol. C-37 turns this field into an enum over `{ id, oip }`; because the field is
966    /// private and every constructor is named, that is an additive change.
967    id: &'a str,
968}
969
970impl<'a> OperationKey<'a> {
971    /// Name an operation by its Flux symbol, e.g. `zendesk-ticket-show`.
972    pub const fn id(id: &'a str) -> Self {
973        Self { id }
974    }
975
976    /// Whether this key names `operation`.
977    fn matches(&self, operation: &Operation) -> bool {
978        operation.id == self.id
979    }
980}
981
982/// How a caller names one provider.
983///
984/// The sibling of [`OperationKey`], and additive in the same way: C-37's `pid`
985/// (`com.zendesk.api`) lands as `ProviderKey::pid`, and its middle level — the `gid`, a versioned
986/// resource group — lands as a `GroupKey` beside it without disturbing anything here.
987#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
988pub struct ProviderKey<'a> {
989    /// The connector id. C-37 turns this field into an enum over `{ id, pid }`.
990    id: &'a str,
991}
992
993impl<'a> ProviderKey<'a> {
994    /// Name a provider by its connector id, e.g. `zendesk`.
995    pub const fn id(id: &'a str) -> Self {
996        Self { id }
997    }
998
999    /// Whether this key names `provider`.
1000    fn matches(&self, provider: &Provider) -> bool {
1001        provider.id == self.id
1002    }
1003}
1004
1005/// Every provider in the catalog, ordered by [`Provider::id`].
1006pub fn providers() -> &'static [&'static Provider] {
1007    generated::PROVIDERS
1008}
1009
1010/// One provider, by key.
1011pub fn provider(key: ProviderKey<'_>) -> Option<&'static Provider> {
1012    providers()
1013        .iter()
1014        .copied()
1015        .find(|provider| key.matches(provider))
1016}
1017
1018/// **Every operation in one provider** — the listing that makes a provider addressable rather than
1019/// merely nameable.
1020///
1021/// An unknown provider yields an empty slice rather than an error; use [`provider`] when the
1022/// difference between "no such connector" and "a connector with nothing in it" matters.
1023pub fn operations_of(key: ProviderKey<'_>) -> &'static [Operation] {
1024    provider(key).map_or(&[], |provider| provider.operations)
1025}
1026
1027/// Every operation in the catalog, provider by provider.
1028pub fn operations() -> impl Iterator<Item = &'static Operation> {
1029    providers()
1030        .iter()
1031        .flat_map(|provider| provider.operations.iter())
1032}
1033
1034/// **The lookup.** One operation by key, with its Flux source and its metadata.
1035///
1036/// A linear scan: the catalog holds tens of operations today and low hundreds once spec ingest
1037/// selects more (a spec-ingested babelforce alone offers 163), which is well inside the range where
1038/// a scan over contiguous `&'static` data beats any index worth maintaining — and an index would be
1039/// a second generated artifact to keep in step with this one.
1040pub fn operation(key: OperationKey<'_>) -> Option<&'static Operation> {
1041    operations().find(|operation| key.matches(operation))
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047
1048    #[test]
1049    fn an_operation_is_found_by_its_symbol() {
1050        let operation = operation(OperationKey::id("zendesk-ticket-show"))
1051            .expect("the shipped catalog carries zendesk-ticket-show");
1052        assert_eq!(operation.provider, "zendesk");
1053        assert!(operation.flux.contains("op zendesk-ticket-show("));
1054    }
1055
1056    #[test]
1057    fn an_unknown_key_is_none_rather_than_a_panic() {
1058        // A negative sentinel must not be a plausible vendor name. `salesforce` was used here, and
1059        // shipping the Salesforce connector (C-163) turned "definitely unknown" into "shipped" and broke
1060        // three tests across two crates at once — `AGENTS.md` had named Salesforce as a provider that
1061        // belongs here all along, so this was scheduled to happen. The sentinel below is not a company,
1062        // and each use is self-checking: the assertion *is* that the catalogue does not carry it, so this
1063        // cannot rot into a vacuous pass the way a stale hardcoded name can.
1064        const NO_SUCH_PROVIDER: &str = "no-such-vendor";
1065
1066        assert!(operation(OperationKey::id("zendesk-ticket-obliterate")).is_none());
1067        assert!(provider(ProviderKey::id(NO_SUCH_PROVIDER)).is_none());
1068        assert!(operations_of(ProviderKey::id(NO_SUCH_PROVIDER)).is_empty());
1069    }
1070
1071    /// Listing by provider is the whole point of the middle level, so it must agree with the flat
1072    /// listing rather than being a second, drifting source.
1073    #[test]
1074    fn listing_by_provider_partitions_the_catalog() {
1075        let listed: usize = providers()
1076            .iter()
1077            .map(|provider| operations_of(ProviderKey::id(provider.id)).len())
1078            .sum();
1079        assert_eq!(listed, operations().count());
1080        assert!(
1081            listed > 0,
1082            "an empty catalog would pass every other test here"
1083        );
1084    }
1085
1086    /// Ids are what lookups key on, so a duplicate would make one of the two unreachable.
1087    #[test]
1088    fn operation_ids_are_unique_across_the_catalog() {
1089        let mut ids: Vec<&str> = operations().map(|operation| operation.id).collect();
1090        let total = ids.len();
1091        ids.sort_unstable();
1092        ids.dedup();
1093        assert_eq!(ids.len(), total, "duplicate operation id in the catalog");
1094    }
1095
1096    #[test]
1097    fn providers_are_listed_in_a_stable_order() {
1098        let ids: Vec<&str> = providers().iter().map(|provider| provider.id).collect();
1099        let mut sorted = ids.clone();
1100        sorted.sort_unstable();
1101        assert_eq!(ids, sorted);
1102    }
1103}