How to use Conf struct in macroquad? - rust

I am trying to customize the behavior of macroquad in my Rust application, but I am having trouble understanding how to use the Conf struct. The documentation refers me to miniquad, but I'm not sure if I need to export both or how to fill in the fields of the Conf struct. Specifically, I am trying to change the window icon and other settings but I don't know how to do it. I have searched for similar questions, but I couldn't find any answers. Can someone please explain how to use the Conf struct in macroquad and how to customize the window icon and other settings?

According to the examples on the macroquad repo, you can pass a function returning your Conf struct as argument to the main macro
use macroquad::prelude::*;
fn window_conf() -> Conf {
Conf {
window_title: "Window Conf".to_owned(),
fullscreen: true,
..Default::default()
}
}
#[macroquad::main(window_conf)]
async fn main() {
loop {
clear_background(WHITE);
next_frame().await
}
}

Related

Error handling for applications: how to return a public message error instead of all the chain of errors and tracing it at the same time?

PROLOGUE
I'm using async-graphql and I have hundreds of resolvers and for each resolver I would like to trace all the possible errors.
In each method of my app I'm using anyhow::{Error}.
Right now I have code similar to this for each resolver:
#[Object]
impl MutationRoot {
async fn player_create(&self, ctx: &Context<'_>, input: PlayerInput) -> Result<Player> {
let services = ctx.data_unchecked::<Services>();
let player = services
.player_create(input)
.await?;
Ok(player)
}
}
So I thought about using the below code (note the added line with .map_err()):
#[Object]
impl MutationRoot {
async fn player_create(&self, ctx: &Context<'_>, input: PlayerInput) -> Result<Player> {
let services = ctx.data_unchecked::<Services>();
let player = services
.player_create(input)
.await
.map_err(errorify)?;
Ok(player)
}
}
fn errorify(err: anyhow::Error) -> async_graphql::Error {
tracing::error!("{:?}", err);
err.into()
}
Now the error is traced along with all the error chain:
ERROR example::main:10: I'm the error number 4
Caused by:
0: I'm the error number 3
1: I'm the error number 2
2: I'm the error number 1
in example::async_graphql
QUESTION 1
Is there a way to avoid the .map_err() on each resolver?
I would like to use the ? alone.
Should I use a custom error?
Can we have a global "hook"/callback/fn to call on each error?
QUESTION 2
As you can see above the chain of the error is the inverse.
In my graphql response I'm getting as message the "I'm the error number 4" but I need to get the "I'm the error number 2" instead.
The error chain is created using anyhow like this:
main.rs: returns error with .with_context(|| "I'm the error number 4")?
call fn player_create() in graphql.rs: returns with .with_context(|| "I'm the error number 3")?
call fn new_player() in domain.rs: returns with .with_context(|| "I'm the error number 2")?
call fn save_player() in database.rs: returns with .with_context(|| "I'm the error number 1")?
How can I accomplish this?
I'm really new to Rust. I come from Golang where I was using a struct like:
type Error struct {
error error
public_message string
}
chaining it easily with:
return fmt.Errorf("this function is called but the error was: %w", previousError)
How to do it in Rust?
Do I necessarily have to use anyhow?
Can you point me to a good handling error tutorial/book for applications?
Thank you very much.
I would suggest you define your own error for your library and handle them properly by using thiserror crate.
It's like Go defining var ErrNotFound = errors.New(...) and use fmt.Errorf(..., err) to add context.
With the powerful tool enum in Rust, so you can handle every error properly by match arms. It also provides really convenient derive macro like #[from] or #[error(transparent)] to make error conversion/forwarding easy.
Edit 1:
If you want to separate public message and tracing log, you may consider defining you custom error struct like this:
#[derive(Error, Debug)]
pub struct MyError {
msg: String,
#[source] // optional if field name is `source`
source: anyhow::Error,
}
and implement Display trait for formatting its inner msg field.
Finally, you could use macro in tracing-attributes crate:
#[instrument(err(Debug))]
fn my_function(arg: usize) -> Result<(), std::io::Error> {
Ok(())
}
Is there a way to avoid the .map_err() on each resolver?
Yes, you should be able to remove it unless you really need to convert to async_graphql::Error.
Do I necessarily have to use anyhow?
No, but it makes this easier when using ? on different error types.
I'm really new to Rust. I come from Golang where I was using a struct like:
Take a look at thiserror which lets you build you own enum of error variants.

How to configure tower_http TraceLayer in a separate function?

I'm implementing a tokio/axum HTTP server. In the function where I run the server, I configure routing, add shared application services and add tracing layer.
My tracing configuration looks like this:
let tracing_layer = TraceLayer::new_for_http()
.make_span_with(|_request: &Request<Body>| {
let request_id = Uuid::new_v4().to_string();
tracing::info_span!("http-request", %request_id)
})
.on_request(|request: &Request<Body>, _span: &Span| {
tracing::info!("request: {} {}", request.method(), request.uri().path())
})
.on_response(
|response: &Response<BoxBody>, latency: Duration, _span: &Span| {
tracing::info!("response: {} {:?}", response.status(), latency)
},
)
.on_failure(
|error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
tracing::error!("error: {}", error)
},
);
let app = Router::new()
// routes
.layer(tracing_layer)
// other layers
...
Trying to organize the code a bit I move the tracing layer configuration to a separate function. The trick is to provide a compiling return type for this function.
The first approach was to move the code as is and let an IDE generate the return type:
TraceLayer<SharedClassifier<ServerErrorsAsFailures>, fn(&Request<Body>) -> Span, fn(&Request<Body>, &Span), fn(&Response<BoxBody>, Duration, &Span), DefaultOnBodyChunk, DefaultOnEos, fn(ServerErrorsFailureClass, Duration, &Span)>
Which is completely unreadable, but the worst is it does not compile: "expected fn pointer, found closure"
In the second approach I changed fn into impl Fn that would mean a closure type. Again, I get an error that my closures are not Clone.
Third, I try to extract closures into separate functions. But then I get "expected fn pointer, found fn item".
What can I do 1) to make it compile and 2) to make it more readable?
Speaking from experience, breaking up the code like that is very hard due to all the generics. I would instead recommend functions that accept and return axum::Routers. That way you bypass all the generics:
fn add_middleware(router: Router) -> Router {
router.layer(
TraceLayer::new_for_http().make_span_with(...)
)
}

What does `::parse()` do on a struct?

I'm learning rust, and the best way to learn a programming language is obviously reading and understanding other's code. Now I faced this line I am not able to understand even after reading docs, other source files and googling for it :
In zoxide's main file, there's this line :
if let Err(e) = App::parse().run() { ... }
What does App::parse() mean ? App is a structure and not a variable, so I understand why it's not .parse(), but why ::parse() and what does it do ? (I couldn't find its definition in app's source code (nor in this file))
First, both the files you mentioned are not the App that zoxide is including. zoxide's main.rs file says use crate::app::{App, Run};, so it's including App from src/app/mod.rs, which exports App from src/app/_app.rs
In that file, we can see the declaration of App:
#[derive(Debug, Clap)]
#[clap(
bin_name = env!("CARGO_PKG_NAME"),
about,
author,
after_help = ENV_HELP,
global_setting(AppSettings::ColoredHelp),
global_setting(AppSettings::DisableHelpSubcommand),
global_setting(AppSettings::DisableVersionForSubcommands),
global_setting(AppSettings::PropagateVersion),
version = option_env!("ZOXIDE_VERSION").unwrap_or_default()
)]
pub enum App {
Add(Add),
Import(Import),
Init(Init),
Query(Query),
Remove(Remove),
}
The key in this case is #[derive(Clap)]. If you look at the clap crate you'll see that it's a crate for parsing command line parameters, and deriving from Clap adds a parse method to the structure.

How to make macro import/use struct in any place it's used?

Suppose I have the following code inside a module:
struct A{
}
#[macro_export]
macro_rules! profile {
($variable_name:tt, $expression:expr) => {
let a = A{};
}
}
so it'd be in a/a.rs, to the side of a/mod.rs which exports a::A and also exports the macro.
The problem is that when I use this macro on other modules like b/b.rs, I'd have to use super::a::A before using the macro.
I could change let a = A{}; on the macro to let a = self::a::A{};. However, it'd not work on all modules, and certainly not for users of this library that use this library in their code.
How can I specify let a = something::something::A{}; in a way that it works anywhere inside my library as well for users of this lib?
In declarative macros specifically, you can use the $crate metavariable to reference the crate the macro is defined in, and then use the absolute path of the item. This will work both inside and outside of your library. For example, if your struct A is defined in your library at the path module_a::module_b::A, you would use:
struct A{
}
#[macro_export]
macro_rules! profile {
($variable_name:tt, $expression:expr) => {
let a = $crate::module_a::module_b::A{};
}
}
Here's the relevant section of the Rust reference guide.

Defining a struct member with private module types

I've been using a bunch of modules that have a build() function which returns a struct. However, when I try to create my own "super" struct to bundle them together, I run into the error module `xxx` is private rustc(E0603). If there is a trait I can pass the individual variable as a parameter but cannot figure out how to define/box it up for a struct.
The current example of this I'm hitting is when creating a hyper client.
// Error due to privacy and cannot use the trait to define the member type
// Both the "hyper_rustls::connector" and "hyper::client::connect::http" modules are private.
struct SecureClient {
client: hyper::client::Client<
hyper_rustls::connector::HttpsConnector<hyper::client::connect::http::HttpConnector>>
}
// Works, but passing the client everywhere as an individual variable is not realistic.
fn use_client(client: hyper::client::Client<impl hyper::client::connect::Connect>) -> () {
()
}
let https_conn = hyper_rustls::HttpsConnector::new(4);
let client: hyper::client::Client<_, hyper::Body> = hyper::Client::builder().build(https_conn);
Being newish to Rust, I'm struggling to figure out what the proper jargon is for what I'm trying to do, let alone make it work. Links to any docs or code examples about this would be appreciated.
Thanks
I'm not sure what you want to do, but you can use the public re-export hyper_rustls::HttpsConnector instead of the private hyper_rustls::connector::HttpsConnector and the public re-export hyper::client::HttpConnector instead of the private hyper::client::connect::http::HttpConnector.
You can read about re-exports here: https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-with-the-use-keyword.html#re-exporting-names-with-pub-use

Resources