Skip to main content

AssetRouter

Struct AssetRouter 

Source
pub struct AssetRouter<'content> { /* private fields */ }
Expand description

A router for certifying and serving static Assets.

Asset certification is configured using the AssetConfig enum.

§Examples

use ic_http_certification::{HttpRequest, StatusCode};
use ic_asset_certification::{Asset, AssetConfig, AssetFallbackConfig, AssetRouter, AssetRedirectKind, AssetEncoding};

let mut asset_router = AssetRouter::default();

let index_html_body = b"<html><body><h1>Hello World!</h1></body></html>".as_slice();
let app_js_body = b"console.log('Hello World!');".as_slice();
let app_css_body = b"html,body{min-height:100vh;}".as_slice();

let assets = vec![
    Asset::new("index.html", index_html_body),
    Asset::new("js/app-488df671.js", app_js_body),
    Asset::new("css/app-ba74b708.css", app_css_body),
];

let asset_configs = vec![
    AssetConfig::File {
        path: "index.html".to_string(),
        content_type: Some("text/html".to_string()),
        headers: vec![(
            "cache-control".to_string(),
            "public, no-cache, no-store".to_string(),
        )],
        fallback_for: vec![AssetFallbackConfig {
            status_code: Some(StatusCode::OK),
            scope: "/".to_string(),
        }],
        aliased_by: vec!["/".to_string()],
        encodings: vec![
            AssetEncoding::Brotli.default_config(),
            AssetEncoding::Gzip.default_config(),
        ],
    },
    AssetConfig::Pattern {
        pattern: "**/*.js".to_string(),
        content_type: Some("text/javascript".to_string()),
        headers: vec![(
            "cache-control".to_string(),
            "public, max-age=31536000, immutable".to_string(),
        )],
        encodings: vec![
            AssetEncoding::Brotli.default_config(),
            AssetEncoding::Gzip.default_config(),
        ],
    },
    AssetConfig::Pattern {
        pattern: "**/*.css".to_string(),
        content_type: Some("text/css".to_string()),
        headers: vec![(
            "cache-control".to_string(),
            "public, max-age=31536000, immutable".to_string(),
        )],
        encodings: vec![
            AssetEncoding::Brotli.default_config(),
            AssetEncoding::Gzip.default_config(),
        ],
    },
    AssetConfig::Redirect {
        from: "/old-url".to_string(),
        to: "/".to_string(),
        kind: AssetRedirectKind::Permanent,
        headers: vec![(
            "content-type".to_string(),
            "text/plain; charset=utf-8".to_string(),
        )],
    },
    AssetConfig::Redirect {
        from: "/css/app.css".to_string(),
        to: "/css/app-ba74b708.css".to_string(),
        kind: AssetRedirectKind::Temporary,
        headers: vec![(
            "content-type".to_string(),
            "text/plain; charset=utf-8".to_string(),
        )],
    },
];

asset_router
    .certify_assets(assets, asset_configs)
    .unwrap();

let index_html_request = HttpRequest::get("/").build();

// this should normally be retrieved using `ic_cdk::api::data_certificate()`.
let data_certificate = vec![1, 2, 3];
let index_html_response = asset_router
    .serve_asset(&data_certificate, &index_html_request)
    .unwrap();

It’s also possible to initialize the AssetRouter with an external HttpCertificationTree, for cases where the tree needs to be used to certify other HTTP responses.

use std::{cell::RefCell, rc::Rc};
use ic_http_certification::HttpCertificationTree;
use ic_asset_certification::AssetRouter;

let mut http_certification_tree: Rc<RefCell<HttpCertificationTree>> = Default::default();
let mut asset_router = AssetRouter::with_tree(http_certification_tree.clone());

Implementations§

Source§

impl<'content> AssetRouter<'content>

Source

pub fn new() -> Self

Creates a new AssetRouter.

Source

pub fn with_tree(tree: Rc<RefCell<HttpCertificationTree>>) -> Self

Creates a new AssetRouter using the provided HttpCertificationTree for certifying assets.

Source

pub fn serve_asset( &self, data_certificate: &[u8], request: &HttpRequest<'_>, ) -> AssetCertificationResult<HttpResponse<'content>>

Returns the corresponding HttpResponse for the provided HttpRequest if it is found in the router.

§Arguments
  • data_certificate - A byte slice representing the data certificate used for asset certification. This should be retrieved using ic_cdk::api::data_certificate().
  • request - A reference to an HttpRequest object representing the incoming HTTP request.

If an exact match is not found, then a fallback will be searched for. See the fallback_for configuration option for more information on fallbacks.

Returns None if no suitable HttpResponse is found for the given HttpRequest.

Source

pub fn get_assets(&self) -> &impl AssetMap<'content>

Returns all standard assets stored in the router.

See the get_fallback_assets() function for fallback assets.

See the AssetMap struct for more information on the returned type.

Source

pub fn get_fallback_assets(&self) -> &impl AssetMap<'content>

Returns all fallback assets stored in the router.

See the get_assets() function for standard assets.

See the AssetMap struct for more information on the returned type.

Source

pub fn certify_assets<'path>( &mut self, assets: impl IntoIterator<Item = Asset<'content, 'path>>, asset_configs: impl IntoIterator<Item = AssetConfig>, ) -> AssetCertificationResult

Certifies multiple assets and inserts them into the router, to be served later by the serve_asset method.

The asset certification is configured using the provided AssetConfig enum.

If no configuration matches an individual asset, the asset will be served and certified as-is, without headers.

After performing this operation, one must set the canister’s certified data (ic_cdk::api::set_certified_data()) to the new root hash of the tree.

Source

pub fn delete_assets<'path>( &mut self, assets: impl IntoIterator<Item = Asset<'content, 'path>>, asset_configs: impl IntoIterator<Item = AssetConfig>, ) -> AssetCertificationResult

Deletes multiple assets from the router, including any certification for those assets.

Depending on the configuration provided to the certify_assets function, multiple responses may be generated for the same asset. To ensure that all generated responses are deleted, this function accepts the same configuration.

After performing this operation, one must set the canister’s certified data (ic_cdk::api::set_certified_data()) to the new root hash of the tree.

Source

pub fn delete_assets_by_path<'path>( &mut self, asset_paths: impl IntoIterator<Item = &'path str>, )

Deletes multiple assets from the router by path, including any certification for those assets.

Depending on the configuration provided to the certify_assets function, multiple responses may be generated for the same asset. These assets may exist on different paths, for example if the alias configuration is used. If alias paths are not passed to this function, they will not be deleted.

If multiple encodings exist for a path, all encodings will be deleted.

Fallbacks are also not deleted, to delete them, use the delete_fallback_assets_by_path function.

After performing this operation, one must set the canister’s certified data (ic_cdk::api::set_certified_data()) to the new root hash of the tree.

Source

pub fn delete_fallback_assets_by_path<'path>( &mut self, asset_paths: impl IntoIterator<Item = &'path str>, )

Deletes multiple fallback assets from the router by path, including certification for those assets.

This function will only delete fallbacks, to delete standard assets, use the delete_assets_by_path function.

After performing this operation, one must set the canister’s certified data (ic_cdk::api::set_certified_data()) to the new root hash of the tree.

Source

pub fn delete_all_assets(&mut self)

Deletes all assets from the router, including any certification for those assets.

After performing this operation, one must set the canister’s certified data (ic_cdk::api::set_certified_data()) to the new root hash of the tree.

Source

pub fn root_hash(&self) -> Hash

Returns the root hash of the underlying HttpCertificationTree.

Trait Implementations§

Source§

impl<'content> Debug for AssetRouter<'content>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for AssetRouter<'_>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<'content> Freeze for AssetRouter<'content>

§

impl<'content> !RefUnwindSafe for AssetRouter<'content>

§

impl<'content> !Send for AssetRouter<'content>

§

impl<'content> !Sync for AssetRouter<'content>

§

impl<'content> Unpin for AssetRouter<'content>

§

impl<'content> !UnwindSafe for AssetRouter<'content>

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
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.