io_msgraph/lib.rs
1#![no_std]
2#![deny(missing_docs)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5//! # io-msgraph
6//!
7//! I/O-free coroutines for the [Microsoft Graph API], built on
8//! [io-http] (HTTP/1.1) and pumped by any stream the caller owns.
9//!
10//! [Microsoft Graph API]: https://learn.microsoft.com/en-us/graph/api/overview
11//! [io-http]: https://docs.rs/io-http
12//!
13//! io-msgraph is the Microsoft Graph sibling of [io-gmail]: same shape
14//! (JSON over HTTP), different vendor. Unlike io-gmail, which is scoped
15//! to Gmail's mail API, io-msgraph represents the whole Microsoft Graph
16//! API: the mail, contacts, calendar and To Do surfaces are covered
17//! today, and sibling resources will be added under the same tree over
18//! time.
19//!
20//! [io-gmail]: https://docs.rs/io-gmail
21//!
22//! ## Layers and features
23//!
24//! The crate has two of the three standard Pimalaya layers; there is no
25//! CLI. The always-present no_std core holds the I/O-free coroutines,
26//! the whole Microsoft Graph REST logic. The `client` feature adds
27//! [`v1::client::MsgraphClientStd`], a std blocking client over any
28//! stream, whose `connect` constructor opens the TCP/TLS connection
29//! itself behind a TLS feature (`rustls-ring` by default, `rustls-aws`,
30//! `native-tls`).
31//!
32//! ## Everything lives under v1
33//!
34//! The Microsoft Graph API is versioned (`/v1.0/`), so the crate is
35//! too: the version-agnostic [`coroutine`] contract stays at the crate
36//! root, everything else lives under [`v1`]. The day a breaking Graph
37//! version ships, a sibling module slots in without breaking `v1`
38//! consumers.
39//!
40//! ## The coroutine contract
41//!
42//! Every exchange implements [`coroutine::MsgraphCoroutine`]: `resume`
43//! takes the bytes read since the last yield and either requests I/O
44//! ([`coroutine::MsgraphYield`] `WantsRead` / `WantsWrite`) or
45//! completes. The [`msgraph_try!`] macro is the coroutine equivalent
46//! of `?`.
47//!
48//! A Graph call is a single HTTP request/response, so every REST
49//! coroutine is a thin wrapper around one shared primitive,
50//! [`v1::send::MsgraphSend`]: it builds the authorized request (bearer
51//! token, JSON in and out) and parses either the 2xx body or Graph's
52//! error envelope into [`v1::send::MsgraphSendError`], whose
53//! [`v1::send::MsgraphApiError`] keeps what the answer asks of the
54//! caller: the delay of a throttled request, the claims challenge of a
55//! 401, the request id and whether the connection survived. Redirects
56//! are never followed. The terminal [`v1::send::MsgraphSendOutput`]
57//! carries the parsed response, its headers and a keep-alive flag so
58//! pumps can reuse the connection across the many small requests a Graph
59//! session makes.
60//! Empty 2xx bodies (DELETE, sendMail, send draft) deserialize into the
61//! [`v1::send::MsgraphNoResponse`] unit marker. The two `$value`
62//! endpoints (raw message MIME and raw attachment content) return bytes
63//! rather than JSON: they run the HTTP send directly and yield the
64//! response body.
65//!
66//! ## Naming
67//!
68//! Public items follow `<Domain><Target><Verb><Ext>`: the domain is
69//! `Msgraph`, the target-verb pair mirrors the REST operation
70//! (`MsgraphMailFolderCreate` for creating a mail folder,
71//! `MsgraphContactsList` for listing contacts) and the extension
72//! distinguishes companions (`Params`, `Response`, `Error`, `Yield`).
73//! Pure data resources omit the verb (`MsgraphMessage`,
74//! `MsgraphContact`); the target is omitted when the verb applies to
75//! the whole exchange ([`v1::send::MsgraphSend`]).
76//!
77//! ## Module layout
78//!
79//! [`v1::rest`] mirrors the Graph reference. The mail, contacts,
80//! calendar and To Do surfaces hang off the users resource, so they live
81//! under [`v1::rest::users`], with each sub-resource a directory and each
82//! operation a file named after it: mail_folders (list, get, create,
83//! update, delete, move, copy, child_folders), messages (list, get,
84//! get_raw, create, create_mime, update, delete, move, copy, send,
85//! delta, attachments), contact_folders (list, get, create, update,
86//! delete, child_folders), contacts (list, get, create, update,
87//! delete, delta), calendars (list, get, create, update, delete), events
88//! (list, get, create, update, delete, instances, calendar_view, delta),
89//! todo lists (list, get, create, update, delete, delta) and their tasks
90//! (list, get, create, update, delete, delta, checklist_items), and the
91//! sendMail action (JSON and MIME form). JSON batching lives at
92//! the API root, under [`v1::rest::batch`]. A reader who knows the
93//! reference knows where to look.
94//!
95//! Domain types mirror the Graph schema. Full-resource bodies double as
96//! create and update bodies thanks to `skip_serializing_if` on every
97//! optional field; contact fields, and the recipients and categories of
98//! a message, use the [`v1::field::MsgraphField`] tri-state to
99//! distinguish a field left out of a PATCH body from one explicitly
100//! cleared. List operations take borrowed `*Params` structs whose fields
101//! rename to the OData system query options (`$top`, `$select`,
102//! `$filter` among others), flattened into query pairs by
103//! [`v1::query::to_query_pairs`], a tiny no_std serde serializer. Every
104//! listing and delta round answers a [`v1::page::MsgraphPage`], and
105//! [`v1::page::MsgraphPageGet`] follows the link it carries, which has
106//! to stay on the Graph origin.
107//!
108//! ## Authentication
109//!
110//! io-msgraph does no OAuth itself: the Graph API only accepts OAuth
111//! 2.0 bearer tokens, so the credential is exactly a bare access token,
112//! and minting or refreshing it is the caller's responsibility. The
113//! base URL is fixed ([`v1::send::MSGRAPH_API_BASE`]); the mailbox
114//! owner is addressed by [`v1::send::user_path`], which yields `me` for
115//! the authenticated user or `users/{id}` for an explicit user id or
116//! principal name (Graph rejects `users/me`).
117//!
118//! ## Logging
119//!
120//! Coroutines pair a `debug!` lifecycle line with one `trace!` per
121//! input variable in `new()`, and a `debug!` plus `trace!("out: ...")`
122//! when `resume` completes; the crate never logs above `debug!`.
123//!
124//! ## Example
125//!
126//! Running a coroutine against a caller-owned TLS stream:
127//!
128//! ```rust,no_run
129//! use std::{
130//! io::{Read, Write},
131//! net::TcpStream,
132//! sync::Arc,
133//! };
134//!
135//! use io_http::rfc6750::bearer::HttpAuthBearer;
136//! use io_msgraph::{coroutine::*, v1::rest::users::get::MsgraphUserGet};
137//! use rustls::{ClientConfig, ClientConnection, StreamOwned};
138//! use rustls_platform_verifier::ConfigVerifierExt;
139//!
140//! let config = ClientConfig::with_platform_verifier().unwrap();
141//! let server_name = "graph.microsoft.com".try_into().unwrap();
142//! let conn = ClientConnection::new(Arc::new(config), server_name).unwrap();
143//! let tcp = TcpStream::connect(("graph.microsoft.com", 443)).unwrap();
144//! let mut stream = StreamOwned::new(conn, tcp);
145//!
146//! let auth = HttpAuthBearer::new("token");
147//! let mut coroutine = MsgraphUserGet::new(&auth, "me").unwrap();
148//!
149//! let mut arg: Option<&[u8]> = None;
150//! let mut buf = [0u8; 8192];
151//! let mut read = Vec::new();
152//!
153//! let out = loop {
154//! match coroutine.resume(arg.take()) {
155//! MsgraphCoroutineState::Complete(Ok(out)) => break out,
156//! MsgraphCoroutineState::Complete(Err(err)) => panic!("{err}"),
157//! MsgraphCoroutineState::Yielded(MsgraphYield::WantsRead) => {
158//! let n = stream.read(&mut buf).unwrap();
159//! read.clear();
160//! read.extend_from_slice(&buf[..n]);
161//! arg = Some(&read);
162//! }
163//! MsgraphCoroutineState::Yielded(MsgraphYield::WantsWrite(bytes)) => {
164//! stream.write_all(&bytes).unwrap();
165//! }
166//! }
167//! };
168//!
169//! println!("user principal name: {:?}", out.response.user_principal_name);
170//! ```
171
172extern crate alloc;
173#[cfg(feature = "client")]
174extern crate std;
175
176pub mod coroutine;
177pub mod v1;