Skip to main content

Service

Struct Service 

Source
pub struct Service {
    pub(crate) db: Data,
    services: Arc<OnceServices>,
    url_preview_mutex: MutexMap<String, ()>,
    federation_mutex: MutexMap<String, ()>,
    mxc_state: MXCState,
    animated_thumbnail_slots: Arc<Semaphore>,
    video_thumbnail_slots: Semaphore,
    video_thumbnail_failures: Mutex<LruCache<String, Instant>>,
}

Fields§

§db: Data§services: Arc<OnceServices>§url_preview_mutex: MutexMap<String, ()>§federation_mutex: MutexMap<String, ()>§mxc_state: MXCState§animated_thumbnail_slots: Arc<Semaphore>§video_thumbnail_slots: Semaphore§video_thumbnail_failures: Mutex<LruCache<String, Instant>>

Implementations§

Source§

impl Service

Source

pub async fn get_url_preview(&self, url: &Url) -> Result<UrlPreviewData>

Source§

impl Service

Source

pub async fn request_url_preview(&self, url: &Url) -> Result<UrlPreviewData>

Source§

impl Service

Source

fn preview_get(&self, url: &Url, agent: Agent) -> RequestBuilder

Build a preview request through the preview client, carrying the headers preview_headers applies.

Source§

impl Service

Source

pub(super) fn preview_headers( &self, request: RequestBuilder, url: &Url, agent: Agent, ) -> RequestBuilder

Apply the configured User-Agent, Accept-Language, and any origin-specific headers to a preview request.

Headers are read per request rather than baked into the client, so a configuration reload takes effect without restarting the server. The configuration is bound once so the header options are read through a single handle.

Source§

impl Service

Source

fn check_remote_addr(&self, response: &Response) -> Result

Screen a preview response’s peer address against the CIDR denylist.

A missing peer address cannot be screened, so it fails closed.

Source§

impl Service

Source

async fn oembed_recover( &self, url: &Url, data: UrlPreviewData, ) -> UrlPreviewData

Recover a preview from the origin’s oEmbed endpoint when the page yielded nothing usable.

Some origins serve their <head> metadata only to an agent they recognise as a link-preview crawler, while answering oEmbed for anyone. A page that parsed to nothing is therefore worth one much smaller second request, and the original preview stands if that request fails too.

Source§

impl Service

Source

async fn oembed_preview( &self, endpoint: &Url, page: &Url, ) -> Result<UrlPreviewData>

Fetch an oEmbed document and render it as a preview.

The document names a thumbnail rather than carrying one, so the image is measured and staged through the same path an og:image takes.

Source§

impl Service

Source

async fn oembed_image(&self, thumbnail_url: Option<&str>) -> UrlPreviewData

Measure an oEmbed thumbnail, yielding an empty preview when it is absent or unusable.

A thumbnail failure must not cost the textual preview the document has already provided.

Source§

impl Service

Source

async fn preview_image(&self, image_url: &Url) -> Result<UrlPreviewData>

Fetch and measure a preview image, keeping the textual preview when the origin refuses it.

The measurement is a media fetch: it carries the media agent, or the origin could serve the measurement different content than it serves the relayed mxc.

Source§

impl Service

Source

pub async fn download_image(&self, response: Response) -> Result<UrlPreviewData>

Download an image for URL preview metadata.

When URL previews are enabled, the image is staged for lazy media retrieval; otherwise this returns the feature-disabled error.

Source§

impl Service

Source

async fn media_response(&self, url: &Url) -> Result<Response>

Fetch a URL with the media client, applying the same address and status screening as the page fetch. Direct preview media is measured and registered from the media client’s response so it matches what the relay will serve.

Source§

impl Service

Source

async fn media_refetch( &self, url: &Url, response: Response, via_media_client: bool, ) -> Result<Response>

Replace a page-client response with the media client’s for a direct media URL. When no distinct media agent is configured the two clients are identical and the original response is used as-is, avoiding a second request.

Source§

impl Service

Source

fn register_lazy_media(&self, url: &str) -> String

Mint a local mxc:// URI that resolves to url on first download (see Service::fetch_lazy_media), keeping preview generation independent of the underlying file size while routing clients through this server.

Source§

impl Service

Source

fn queue_lazy_media(&self, txn: &mut Txn, url: &str) -> String

Source§

impl Service

Source§

impl Service

Source

pub async fn download_video(&self, response: Response) -> Result<UrlPreviewData>

Source§

impl Service

Source

pub async fn download_audio(&self, response: Response) -> Result<UrlPreviewData>

Source§

impl Service

Source

async fn download_html( &self, url: &Url, response: Response, ) -> Result<UrlPreviewData>

Source§

impl Service

Source

fn lazy_media( &self, page: &Url, obj: &OpengraphObject, class: &str, ) -> Option<String>

Mint an mxc:// URI for a page’s declared media, or nothing when it is not relayable.

The URL is recorded rather than fetched, so a page naming a large video costs the preview request no bandwidth; it is fetched and checked only once a client asks for the resulting URI. Screening IP literals here as well keeps a preview from handing out a URI that the same check at relay time is guaranteed to refuse.

Source§

impl Service

Source

pub(super) fn check_url_host(&self, url: &Url) -> Result

Source§

impl Service

Source

pub fn url_preview_allowed(&self, url: &Url) -> bool

Source§

impl Service

Source

pub async fn fetch_remote_thumbnail( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, dim: &Dim, animate: Animate, ) -> Result<Fetched>

Fetches a thumbnail at this dimension from the origin server.

The authenticated endpoint is asked first, falling back to the legacy one only where the peer answers no such media and this server is configured to ask. What the walk filing the answer settled travels back with it, so a caller deciding whether the picture may be served reads no bytes again.

Source§

impl Service

Source

pub async fn fetch_remote_content( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, ) -> Result<Fetched>

Fetches the original file from the origin server.

The authenticated endpoint is asked first, falling back to the legacy one only where the peer answers no such media and this server is configured to ask. What the walk filing the answer settled travels back with it, so a caller deciding whether the picture may be served reads no bytes again.

Source§

impl Service

Source

async fn fetch_thumbnail_authenticated( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, dim: &Dim, animate: Animate, ) -> Result<Fetched>

Source§

impl Service

Source

async fn fetch_content_authenticated( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, ) -> Result<Fetched>

Source§

impl Service

Source

async fn fetch_thumbnail_unauthenticated( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, dim: &Dim, animate: Animate, ) -> Result<Fetched>

Source§

impl Service

Source

async fn fetch_content_unauthenticated( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, timeout_ms: Duration, ) -> Result<Fetched>

Source§

impl Service

Source

async fn handle_thumbnail_file( &self, mxc: &Mxc<'_>, dim: &Dim, content: Content, ) -> Result<Fetched>

Source§

impl Service

Source

async fn handle_content_file( &self, mxc: &Mxc<'_>, content: Content, ) -> Result<Fetched>

Source§

impl Service

Source

async fn handle_location( &self, mxc: &Mxc<'_>, location: &str, ) -> Result<Fetched>

Source§

impl Service

Source

pub(super) async fn location_request( &self, fetch: Fetch, location: &str, limit: usize, ) -> Result<Media>

Source§

impl Service

Source

async fn federation_request<Request>( &self, mxc: &Mxc<'_>, server: Option<&ServerName>, request: Request, ) -> Result<Request::IncomingResponse>
where Request: OutgoingRequest + Send + Debug, Request::Authentication: FedAuth, Request::PathBuilder: FedPath,

Source§

impl Service

Source

pub async fn fetch_remote_thumbnail_legacy( &self, mxc: &Mxc<'_>, timeout_ms: Duration, dim: &Dim, animate: Animate, ) -> Result<Media>

Fetches a thumbnail from the origin server over the legacy media API.

The dimension the origin is asked for is the dimension its answer is filed under, and every later lookup normalizes before it seeks, so the two have to agree or nothing cached on one request is found on the next. A request too large for any thumbnail size normalizes to the original file, which is fetched rather than asked for at a dimension that is not a size.

Source§

impl Service

Source

pub async fn fetch_remote_content_legacy( &self, mxc: &Mxc<'_>, allow_redirect: bool, timeout_ms: Duration, ) -> Result<Response, Error>

Source§

impl Service

Source

fn check_fetch_authorized(&self, mxc: &Mxc<'_>) -> Result

Source§

impl Service

Source§

impl Service

Source

pub(super) async fn store_animated( &self, mxc: &Mxc<'_>, dim: &Dim, source: Bytes, admission: OwnedSemaphorePermit, ) -> Result<Output>

Encode this picture’s frames as an animated GIF thumbnail and store it.

Quantization runs per frame on a palette of its own, which is far more work than a still costs, so the encode is handed to a blocking worker rather than run on the async runtime. A source whose frames will not decode answers an error and the caller falls through to the still it would have produced.

Source§

impl Service

Source

pub(super) fn decode_still(&self, bytes: &[u8]) -> Result<DynamicImage>

Decodes a picture that may not be served in the state it is held in.

Serving it is what the request forbade, so a decode that fails leaves nothing answerable and the caller has no fallback to offer.

Source§

impl Service

Source

pub(in media) async fn store_still( &self, mxc: &Mxc<'_>, dim: &Dim, animated: Media, ) -> Result<Media>

Re-encode a fetched picture as a still thumbnail and store it.

A peer that ignores the parameter answers a cold fetch with animation, and this repairs it on the way out rather than one request later. The cached row takes its own path, which already holds the picture.

Source§

impl Service

Source

pub(super) async fn get_thumbnail_generate( &self, mxc: &Mxc<'_>, dim: &Dim, animate: Animate, data: Metadata, ) -> Result<Media>

Generate a thumbnail.

A source that animates yields both variants here rather than the one this request asked for. Generation runs only on a lookup miss, and the row it stores is what stops the next miss, so a variant left ungenerated would wait on a miss that the other variant has already made impossible.

Source§

impl Service

Source

pub(super) async fn store_thumbnail( &self, mxc: &Mxc<'_>, dim: &Dim, image: DynamicImage, ) -> Result<Media>

Encode a still PNG thumbnail at these dimensions and store it.

The generate path and the still-repair path share this, so a given size carries one content type and one disposition whichever produced it.

Source§

impl Service

Source

pub(super) async fn store_encoded( &self, mxc: &Mxc<'_>, dim: &Dim, content: Vec<u8>, content_type: &str, filename: &str, ) -> Result<Media>

Store an encoded thumbnail under the type and name it carries.

Both encoders end here, so a stored thumbnail is disposed inline under the name the media repository specification asks of one whether or not the original arrived with a name of its own.

Source§

impl Service

Source

pub(super) fn decode(&self, bytes: &[u8]) -> Result<DynamicImage>

Decode a picture whose header declares no more than the configured pixel count.

The dimensions are checked before any decoder allocates, since Limits enforces only a byte budget and leaves a decoder free to ignore it.

Source§

impl Service

Source

pub async fn upload_thumbnail( &self, mxc: &Mxc<'_>, content_disposition: Option<&ContentDisposition>, content_type: Option<&str>, dim: &Dim, file: &[u8], ) -> Result

Uploads or replaces a file thumbnail.

Metadata is written first, then the supplied bytes replace the stored media body for the requested dimensions.

Source

pub async fn get_or_fetch_thumbnail( &self, mxc: &Mxc<'_>, dim: &Dim, animate: Animate, timeout_ms: Duration, user: &UserId, ) -> Result<Media>

Answers a thumbnail request, fetching from the peer when it is remote.

The dimension a fetch asks the peer for is the dimension the answer is filed under, and every later lookup seeks the normalized one, so the three have to agree or nothing found on one request is found on the next. Past every bucket there is no dimension to ask at, and the request names the original file instead.

Source

pub fn get_thumbnail<'a>( &'a self, __arg1: &'a Mxc<'_>, __arg2: &'a Dim, __arg3: Animate, __arg4: Option<Duration>, ) -> Pin<Box<dyn Future<Output = Result<Media>> + Send + 'a>>

Downloads a thumbnail, waiting for a pending upload when requested.

The supplied duration bounds that wait. The future is boxed because the still-repair path pulls the thumbnailer into it, and inlining that into every caller overflows the layout depth limit in the federation handler.

Source

async fn __get_thumbnail<'a>( &'a self, mxc: &'a Mxc<'_>, dim: &'a Dim, animate: Animate, timeout_duration: Option<Duration>, ) -> Result<Media>

Source

pub async fn get_stored_thumbnail( &self, mxc: &Mxc<'_>, dim: &Dim, animate: Animate, ) -> Result<Media>

Downloads a stored or generated thumbnail.

Requests normalize to a bounded storage bucket. An existing variant is returned directly; a missing variant is generated from the original or answered from promoted storage when the original row is absent.

Source§

impl Service

Source

fn answer_original<'a>( &'a self, __arg1: &'a Mxc<'_>, __arg2: Animate, ) -> Pin<Box<dyn Future<Output = Result<Media>> + Send + 'a>>

Answers a request past every bucket, which names the original file.

The original’s own row is keyed at the sentinel, where there is no size to re-encode at, so a picture the request will not accept stands in at its own dimensions. Those are the largest a still may carry without upscaling, so the stand-in covers any request the original itself covers and is the best available where it does not.

The future is not inlined: this branch reaches the thumbnailer, and folding that into every caller overflows the layout depth limit.

Source

async fn __answer_original<'a>( &'a self, mxc: &'a Mxc<'_>, animate: Animate, ) -> Result<Media>

Source§

impl Service

Source

pub(super) async fn original_metadata(&self, mxc: &Mxc<'_>) -> Result<Metadata>

Metadata for the original file, which every thumbnail is derived from.

Its row is keyed at the sentinel dimension, and nothing is withheld from this lookup: the row is the original rather than a variant of it.

Source§

impl Service

Source

async fn answer_promoted( &self, mxc: &Mxc<'_>, animate: Animate, ) -> Result<Media>

Answers from stored media when no metadata row names the original.

The original may be lazy preview media promoted on this very request, which leaves no row behind, and only a picture is worth serving in a thumbnail’s place. No row having named it, the request’s own preference is the only gate it passes, so the picture is read here as it is anywhere else.

Source§

impl Service

Source

pub(super) async fn fetch_bytes(&self, key: &[u8]) -> Result<Bytes>

The stored bytes for a thumbnail row, from the first provider holding them.

Returning the shared Bytes spares a caller that only reads the picture the Vec copy Media would force on it.

Source§

impl Service

Source

async fn answer_stored( &self, mxc: &Mxc<'_>, dim: &Dim, animate: Animate, data: Metadata, ) -> Result<Media>

Answers a request from a stored row, re-deriving a still if it animates.

The type a row is stored under is whatever produced it claimed, and a peer is free to claim wrongly, so the picture itself decides once it is in hand. A row that may not answer is re-encoded and the still left behind for the next request.

Source§

impl Service

Source

pub(super) async fn video_frame( &self, mxc: &Mxc<'_>, dim: &Dim, media: &Media, ) -> Option<Vec<u8>>

Still frame standing in for a video, or None when the media is not a video, no program is configured, or extraction failed.

Source§

impl Service

Source

fn failed_recently(&self, mxc: &Mxc<'_>) -> bool

Whether this video failed within the cooldown, where trying again would spend a slot to reach the same failure.

Source§

impl Service

Source

pub(super) fn remember_failure(&self, mxc: &Mxc<'_>)

Source§

impl Service

Source

async fn extract_frame( &self, mxc: &Mxc<'_>, dim: &Dim, content: &[u8], ) -> Result<Vec<u8>>

Source§

impl Service

Source

pub async fn create_pending( &self, mxc: &Mxc<'_>, user: &UserId, unused_expires_at: u64, ) -> Result

Create a pending media upload ID.

Source

pub async fn upload_pending( &self, mxc: &Mxc<'_>, user: &UserId, content_disposition: Option<&ContentDisposition>, content_type: Option<&str>, file: &[u8], ) -> Result

Uploads content to a pending media ID.

Source

pub async fn create( &self, mxc: &Mxc<'_>, user: Option<&UserId>, content_disposition: Option<&ContentDisposition>, content_type: Option<&str>, file: &[u8], ) -> Result<bool>

Uploads a file and reports whether its own bytes carry a sequence.

The declared type is whoever uploaded it saying so, and a picture that animates is stored under the type its own container names instead. That is the only record of whether the media animates that a later lookup can read without fetching the whole of it. The disposition is left as the caller computed it, so a file already bound for download stays there.

Source

pub async fn delete(&self, mxc: &Mxc<'_>) -> Result

Deletes a file in the database and from the media directory via an MXC

Source

pub async fn delete_from_user(&self, user: &UserId) -> Result<usize>

Deletes all media by the specified user

currently, this is only practical for local users

Source

pub async fn get_or_fetch( &self, mxc: &Mxc<'_>, timeout_ms: Duration, ) -> Result<Media>

Get file from local storage or make a federation request if it originates remotely.

Source

pub async fn get( &self, mxc: &Mxc<'_>, timeout: Option<Duration>, ) -> Result<Media>

Get file from local storage while waiting up to a timeout_ms if it is pending.

Source

pub async fn get_stored(&self, mxc: &Mxc<'_>) -> Result<Media>

Get file from local storage.

A metadata miss falls through to the lazy-media path, which serializes on a per-mxc mutex and fetches the origin once.

Source

async fn fetch_lazy_media(&self, mxc: &Mxc<'_>) -> Result<Media>

Resolve lazy URL-preview media on first download, promoting the staged or freshly-fetched bytes into the media store so the origin is fetched at most once per item.

Source

pub async fn redirect_url( &self, mxc: &Mxc<'_>, dim: &Dim, animate: Animate, ) -> Result<Option<Url>>

Presigned redirect URL for locally-stored media (MSC3860).

Returns the first configured provider’s signed URL for the object, or None when redirects are disabled, the media is unknown, or no provider can presign it (filesystem-only media). A stored file that animates also answers None to a request forbidding animation, since handing over the object as it stands cannot re-encode it.

Source

pub async fn get_all_mxcs(&self) -> Result<Vec<OwnedMxcUri>>

Gets all the MXC URIs in our media database

Source

pub async fn user_media(&self, user: &UserId) -> Result<Vec<UserMediaEntry>>

Every media item uploaded by a local user, carrying the fields tuwunel can derive: content type, upload name, byte length and modification time from storage-provider object metadata. Untracked columns (last-access, quarantine, url-cache) are not represented.

Source

pub async fn media_entry(&self, mxc: &Mxc<'_>) -> Option<UserMediaEntry>

Derivable metadata for the single media item at the given MXC, with the uploading local user resolved from the uploader index when present.

Source

async fn user_media_entry( &self, user: Option<&UserId>, mxc: OwnedMxcUri, ) -> Option<UserMediaEntry>

Source

pub fn upload_stats(&self) -> impl Stream<Item = UploadStat> + Send + '_

Uploader, byte length and storage modification time of every media item uploaded by a local user, one row per upload; media missing from every storage provider are skipped.

Source

pub async fn delete_by_date_size( &self, before_ts: u64, size_gt: u64, keep_profiles: bool, ) -> Result<Vec<OwnedMxcUri>>

Deletes local media older than before_ts (by storage-provider mtime) and strictly larger than size_gt bytes, sparing profile and room-avatar media when keep_profiles. Returns the deleted MXCs, empty when none match. Quarantine and protection flags are not tracked, so no media is spared on those grounds.

Source

async fn avatar_mxcs(&self) -> HashSet<OwnedMxcUri>

The MXCs of every local user’s profile avatar and every room’s avatar, the spare-set honoured by keep_profiles.

Source

fn is_local(&self, mxc: &OwnedMxcUri) -> bool

Source

async fn head_meta(&self, key: &[u8]) -> Option<ObjectMeta>

First storage provider’s object metadata for the media stored under key (byte length and modification time), or None when no provider holds it.

Source

pub async fn delete_range( &self, time: SystemTime, older_than: bool, newer_than: bool, yes_i_want_to_delete_local_media: bool, ) -> Result<usize>

Deletes all media files before or after the given time. Returns a usize with the number of media files deleted.

Source

pub async fn create_media_dir(&self) -> Result

Source

async fn remove_media_file(&self, key: &[u8]) -> Result

Source

async fn create_media_file(&self, key: &[u8], file: &[u8]) -> Result

Source

fn storage_providers(&self) -> impl Iterator<Item = &Arc<Provider>> + Send + '_

Source

pub async fn get_metadata(&self, mxc: &Mxc<'_>) -> Option<Metadata>

Source

pub fn get_media_path_sha256(&self, key: &[u8]) -> PathBuf

Source

pub fn get_media_name_sha256(&self, key: &[u8]) -> String

new SHA256 file name media function. requires database migrated. uses SHA256 hash of the base64 key as the file name

Source

pub fn get_media_path_b64(&self, key: &[u8]) -> PathBuf

old base64 file name media function This is the old version of get_media_path_sha256 that uses the full base64 key as the filename.

Source

pub fn get_media_dir(&self) -> PathBuf

Trait Implementations§

Source§

impl Service for Service

Source§

fn build(args: &Args<'_>) -> Result<Arc<Self>>

Implement the construction of the service instance. Services are generally singletons so expect this to only be called once for a service type. Note that it may be called again after a server reload, but the prior instance will have been dropped first. Failure will shutdown the server with an error.
Source§

fn name(&self) -> &str

Return the name of the service. i.e. crate::service::make_name(std::module_path!())
Source§

fn worker<'async_trait>( self: Arc<Self>, ) -> Pin<Box<dyn Future<Output = Result> + Send + 'async_trait>>
where Self: 'async_trait,

Implement the service’s worker loop. The service manager spawns a task and calls this function after all services have been built.
Source§

fn interrupt<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Interrupt the service. This is sent to initiate a graceful shutdown. The service worker should return from its work loop.
Source§

fn clear_cache<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Clear any caches or similar runtime state.
Source§

fn memory_usage<'life0, 'life1, 'async_trait>( &'life0 self, _out: &'life1 mut (dyn Write + Send), ) -> Pin<Box<dyn Future<Output = Result> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Memory usage report in a markdown string.
Source§

fn unconstrained(&self) -> bool

Return true if the service worker opts out of the tokio cooperative budgeting. This can reduce tail latency at the risk of event loop starvation.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> DropFlavorWrapper<T> for T

§

type Flavor = MayDrop

The DropFlavor that [wrap]s T into Self
Source§

impl<T> ExpectInto for T

Source§

fn expect_into<Dst>(self) -> Dst
where Dst: TryFrom<Self>, Self: Sized,

Converts the value into Dst and returns the successful result. Read more
Source§

impl<T> Expected for T

Source§

fn expected_add(self, rhs: Self) -> Self
where Self: Sized + CheckedAdd,

Adds rhs with an expectation that the operation is valid. Read more
Source§

fn expected_sub(self, rhs: Self) -> Self
where Self: Sized + CheckedSub,

Subtracts rhs with an expectation that the operation is valid. Read more
Source§

fn expected_mul(self, rhs: Self) -> Self
where Self: Sized + CheckedMul,

Multiplies by rhs with an expectation that the operation is valid. Read more
Source§

fn expected_div(self, rhs: Self) -> Self
where Self: Sized + CheckedDiv,

Divides by rhs with an expectation that the operation is valid. Read more
Source§

fn expected_rem(self, rhs: Self) -> Self
where Self: Sized + CheckedRem,

Computes the remainder with an expectation that the operation is valid. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

impl<T> Identity for T
where T: ?Sized,

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> JsonCastable<CanonicalJsonValue> for T

§

impl<T> JsonCastable<Value> for T

§

impl<T> Paint for T
where T: ?Sized,

§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Primary].

§Example
println!("{}", value.primary());
§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Fixed].

§Example
println!("{}", value.fixed(color));
§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to [Color :: Rgb].

§Example
println!("{}", value.rgb(r, g, b));
§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Black].

§Example
println!("{}", value.black());
§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Red].

§Example
println!("{}", value.red());
§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Green].

§Example
println!("{}", value.green());
§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Yellow].

§Example
println!("{}", value.yellow());
§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Blue].

§Example
println!("{}", value.blue());
§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Magenta].

§Example
println!("{}", value.magenta());
§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: Cyan].

§Example
println!("{}", value.cyan());
§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: White].

§Example
println!("{}", value.white());
§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlack].

§Example
println!("{}", value.bright_black());
§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightRed].

§Example
println!("{}", value.bright_red());
§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightGreen].

§Example
println!("{}", value.bright_green());
§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightYellow].

§Example
println!("{}", value.bright_yellow());
§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightBlue].

§Example
println!("{}", value.bright_blue());
§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.bright_magenta());
§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightCyan].

§Example
println!("{}", value.bright_cyan());
§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to [Color :: BrightWhite].

§Example
println!("{}", value.bright_white());
§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Primary].

§Example
println!("{}", value.on_primary());
§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Fixed].

§Example
println!("{}", value.on_fixed(color));
§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to [Color :: Rgb].

§Example
println!("{}", value.on_rgb(r, g, b));
§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Black].

§Example
println!("{}", value.on_black());
§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Red].

§Example
println!("{}", value.on_red());
§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Green].

§Example
println!("{}", value.on_green());
§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Yellow].

§Example
println!("{}", value.on_yellow());
§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Blue].

§Example
println!("{}", value.on_blue());
§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Magenta].

§Example
println!("{}", value.on_magenta());
§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: Cyan].

§Example
println!("{}", value.on_cyan());
§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: White].

§Example
println!("{}", value.on_white());
§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlack].

§Example
println!("{}", value.on_bright_black());
§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightRed].

§Example
println!("{}", value.on_bright_red());
§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightGreen].

§Example
println!("{}", value.on_bright_green());
§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightYellow].

§Example
println!("{}", value.on_bright_yellow());
§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightBlue].

§Example
println!("{}", value.on_bright_blue());
§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightMagenta].

§Example
println!("{}", value.on_bright_magenta());
§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightCyan].

§Example
println!("{}", value.on_bright_cyan());
§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to [Color :: BrightWhite].

§Example
println!("{}", value.on_bright_white());
§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling [Attribute] value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Bold].

§Example
println!("{}", value.bold());
§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Dim].

§Example
println!("{}", value.dim());
§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Italic].

§Example
println!("{}", value.italic());
§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Underline].

§Example
println!("{}", value.underline());

Returns self with the attr() set to [Attribute :: Blink].

§Example
println!("{}", value.blink());

Returns self with the attr() set to [Attribute :: RapidBlink].

§Example
println!("{}", value.rapid_blink());
§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Invert].

§Example
println!("{}", value.invert());
§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Conceal].

§Example
println!("{}", value.conceal());
§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to [Attribute :: Strike].

§Example
println!("{}", value.strike());
§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi [Quirk] value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Mask].

§Example
println!("{}", value.mask());
§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Wrap].

§Example
println!("{}", value.wrap());
§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Linger].

§Example
println!("{}", value.linger());
§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1:

renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to [Quirk :: Clear].

§Example
println!("{}", value.clear());
§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Resetting].

§Example
println!("{}", value.resetting());
§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: Bright].

§Example
println!("{}", value.bright());
§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to [Quirk :: OnBright].

§Example
println!("{}", value.on_bright());
§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the [Condition] value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new [Painted] with a default [Style]. Read more
§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn add_extension<T>(self, value: T) -> AddExtension<Self, T>
where Self: Sized,

Add some shareable value to request extensions. Read more
§

fn compression(self) -> Compression<Self>
where Self: Sized,

Compresses response bodies. Read more
§

fn decompression(self) -> Decompression<Self>
where Self: Sized,

Decompress response bodies. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
§

fn sensitive_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveRequestHeaders<SetSensitiveResponseHeaders<Self>>
where Self: Sized,

Mark headers as sensitive on both requests and responses. Read more
§

fn sensitive_request_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveRequestHeaders<Self>
where Self: Sized,

Mark headers as sensitive on requests. Read more
§

fn sensitive_response_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveResponseHeaders<Self>
where Self: Sized,

Mark headers as sensitive on responses. Read more
§

fn override_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request. Read more
§

fn append_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Append a header into the request. Read more
§

fn insert_request_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request, if the header is not already present. Read more
§

fn override_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response. Read more
§

fn append_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Append a header into the response. Read more
§

fn insert_response_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response, if the header is not already present. Read more
§

fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>
where Self: Sized,

Catch panics and convert them into 500 Internal Server responses. Read more
Source§

impl<T> Tried for T

Source§

fn try_add(self, rhs: Self) -> Result<Self, Error>
where Self: Sized + CheckedAdd,

Adds rhs with checked arithmetic. Read more
Source§

fn try_sub(self, rhs: Self) -> Result<Self, Error>
where Self: Sized + CheckedSub,

Subtracts rhs with checked arithmetic. Read more
Source§

fn try_mul(self, rhs: Self) -> Result<Self, Error>
where Self: Sized + CheckedMul,

Multiplies by rhs with checked arithmetic. Read more
Source§

fn try_div(self, rhs: Self) -> Result<Self, Error>
where Self: Sized + CheckedDiv,

Divides by rhs with checked arithmetic. Read more
Source§

fn try_rem(self, rhs: Self) -> Result<Self, Error>
where Self: Sized + CheckedRem,

Computes the remainder by rhs with checked arithmetic. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more