• Stars
    star
    210
  • Rank 187,585 (Top 4 %)
  • Language
    Rust
  • License
    Other
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Hot-reloading loadable and reloadable resources

warmy, hot-reloading loadable and reloadable resources

Build Status dependency status crates.io docs.rs License

Hot-reloading, loadable and reloadable resources.

Foreword

Resources are objects that live in a store and can be hot-reloaded – i.e. they can change without you interacting with them. There are currently two types of resources supported:

  • Filesystem resources, which are resources that live on the filesystem and have a real representation (i.e. a file for short).
  • Logical resources, which are resources that are computed and don’t directly require any I/O.

Resources are referred to by keys. A key is a typed index that contains enough information to uniquely identify a resource living in a store.

This small introduction will give you enough information and examples to get your feet wet with warmy. If you want to know more, feel free to visit the documentation of submodules.

Feature-gates

Here’s an exhaustive list of feature-gates available:

  • "arc": changes the internal representation of resources in order to use Arc and Mutex, allowing for cross-thread sharing of resources. This is a current patch in the waiting of a better asynchronous solution.
  • "json": provides a Json type that you can use as loading method to automatically load any type that implements serde::Deserialize and encoded as JSON. You don’t even have to implement Load by your own! Enabled by default
  • "ron-impl": provides a Ron type that you can use as loading method to automatically load any type that implemetns serde::Deserialize and encoded as RON.
  • "toml-impl": provides a Toml type that you can use as loading method to automatically load any type that implements serde::Deserialize and encoded as TOML.

Loading a resource

Loading is the action of getting an object out of a given location. That location is often your filesystem but it can also be a memory area – mapped files or memory parsing. In warmy, loading is implemented per-type: this means you have to implement a trait on a type so that any object of that type can be loaded. The trait to implement is Load. We’re interested in four items:

  • The Store, which holds and caches resources.
  • The Key type variable, used to tell warmy which kind of resource your store knows how to represent and what information the key must contain.
  • The Load::Error associated type, that is the error type used when loading fails.
  • The Load::load method, which is the method called to load your resource in a given store.

Store

A Store is responsible for holding and caching resources. Each Store is associated with a root, which is a path on the filesystem all filesystem resources will come from. You create a Store by giving it a StoreOpt, which is used to customize the Store – if you don’t need it nor care about it for the moment, just use Store::default.

use warmy::{SimpleKey, Store, StoreOpt};

let res = Store::<(), SimpleKey>::new(StoreOpt::default());

match res {
  Err(e) => {
    eprintln!("unable to create the store: {}", e);
  }

  Ok(store) => ()
}

As you can see, the Store has two type variables. These type variables refer to the types of context you want to use with your resources and the type of keys. For now we’ll use () for the context as we don’t want contexts – but more to come – and the common SimpleKey type for keys. Keep on reading.

The Key type variable

The key type must implement Key, which is the class of types recognized as keys by warmy. In theory, you shouldn’t worry about that trait because warmy already ships with some key types.

If you really want to implement Key, have a look at its documentation for further details.

Keys are a core concept in warmy as they are objects that uniquely represent resources – should they be on a filesystem or in memory. You will refer to your resources with those keys.

Special case: simple keys

A simple key (a.k.a. SimpleKey) is a key used to express common situations in which you might have resources from the filesystem and from logical locations. It’s provided for convenience, so that you don’t have to write that type and implement Key. In most situations, it should be enough for you – of course, if you need more details, feel free to define your own key type.

The Load::Error associated type

This associated type must be set to the type of error your loading implementation might generate. For instance, if you load something with serde-json, you might want to set it to °serde_json::Error`. This way of doing is very common in Rust; you shouldn’t feel uncomfortable with it.

On a general note, you should always try to stick to precise and accurate errors types. Avoid simple types such as String or u64 and prefer to use detailed, algebraic datatypes.

The Load::load method

This is the entry-point method. Load::load must be implemented in order for warmy to know how to read the resource. Let’s implement it for two types: one that represents a resource on the filesystem, one computed from memory.

use std::fmt;
use std::fs::File;
use std::io::{self, Read};
use warmy::{Load, Loaded, SimpleKey, Storage};

// Possible errors that might happen.
#[derive(Debug)]
enum Error {
  CannotLoadFromFS,
  CannotLoadFromLogical,
  IOError(io::Error)
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    match *self {
      Error::CannotLoadFromFS => f.write_str("cannot load from file system"),
      Error::CannotLoadFromLogical => f.write_str("cannot load from logical"),
      Error::IOError(ref e) => write!(f, "IO error: {}", e),
    }
  }
}

// The resource we want to take from a file.
struct FromFS(String);

// The resource we want to compute from memory.
struct FromMem(usize);

impl<C> Load<C, SimpleKey> for FromFS {
  type Error = Error;

  fn load(
    key: SimpleKey,
    storage: &mut Storage<C, SimpleKey>,
    _: &mut C
  ) -> Result<Loaded<Self, SimpleKey>, Self::Error> {
    // as we only accept filesystem here, we’ll ensure the key is a filesystem one
    match key {
      SimpleKey::Path(path) => {
        let mut fh = File::open(path).map_err(Error::IOError)?;
        let mut s = String::new();
        fh.read_to_string(&mut s);

        Ok(FromFS(s).into())
      }

      SimpleKey::Logical(_) => Err(Error::CannotLoadFromLogical)
    }
  }
}

impl<C> Load<C, SimpleKey> for FromMem {
  type Error = Error;

  fn load(
    key: SimpleKey,
    storage: &mut Storage<C, SimpleKey>,
    _: &mut C
  ) -> Result<Loaded<Self, SimpleKey>, Self::Error> {
    // ensure we only accept logical resources
    match key {
      SimpleKey::Logical(key) => {
        // this is a bit dummy, but why not?
        Ok(FromMem(key.len()).into())
      }

      SimpleKey::Path(_) => Err(Error::CannotLoadFromFS)
    }
  }
}

As you can see here, there’re a few new concepts:

  • Loaded: A type you have to wrap your object in to express dependencies. Because it implements From<T> for Loaded<T>, you can use .into() to state you don’t have any dependencies.
  • Storage: This is the minimal structure that holds and caches your resources. A Store is actually the interface structure you will handle in your client code.

Express your dependencies with Loaded

An object of type Loaded gives information to warmy about your dependencies. Upon loading – i.e. your resource is successfully loaded – you can tell warmy which resources your loaded resource depends on. This is a bit tricky, though, because a difference is important to make there.

When you implement Load::load, you are handed a Storage. You can use that Storage to load additional resources and gather them in your resources. When those additional resources get reloaded, if you directly embed the resources in your object, you will automatically see the automated resources – that is the whole point of this crate! However, if you don’t express a dependency relationship to those resources, your former resource will not reload – it will just use automatically-synced resources, but it will not reload itself. This is a bit touchy but let’s take an example of a typical situation where you might want to use dependencies and then dependency graphs:

  1. You want to load an object that is represented by aggregation of several values / resources.
  2. You choose to use a logical resource and guess all the files to load from.
  3. When you implement Load::load, you open several files, load them into memory, compose them and finally end up with your object.
  4. You return your object from Load::load with no dependencies (i.e. you use .into() on it).

What is going to happen here is that if any file your resource depends on changes, since they don’t have a proper resource in the store, your object will see nothing. A typical solution there is to load those files as proper resources and put those keys in the returned Loaded object to express that you depend on the reloading of the objects referred by these keys. It’s a bit touchy but you will eventually find yourself in a situation when this Loaded thing will help you. You will then use Loaded::with_deps. See the documentation of Loaded for further information.

Fun fact: logical resources were introduced to solve that problem along with dependency graphs.

Let’s get some things!

When you have implemented Load, you’re set and ready to get (cached) resources. You have several functions to achieve that goal:

  • Store::get, used to get a resource. This will effectively load it if it’s the first time it’s asked. If it’s not, it will use a cached version.
  • Store::get_proxied, a special version of Store::get. If the initial loading (non-cached) fails to load (missing resource, fail to parse, whatever), a proxy will be used – passed in to Store::get_proxied. This value is lazy though, so if the loading succeeds, that value won’t ever be evaluated.

Let’s focus on Store::get for this tutorial.

use std::fmt;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use warmy::{Load, Loaded, SimpleKey, Store, StoreOpt, Storage};

// Possible errors that might happen.
#[derive(Debug)]
enum Error {
  CannotLoadFromFS,
  CannotLoadFromLogical,
  IOError(io::Error)
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    match *self {
      Error::CannotLoadFromFS => f.write_str("cannot load from file system"),
      Error::CannotLoadFromLogical => f.write_str("cannot load from logical"),
      Error::IOError(ref e) => write!(f, "IO error: {}", e),
    }
  }
}

// The resource we want to take from a file.
struct FromFS(String);

impl<C> Load<C, SimpleKey> for FromFS {
  type Error = Error;

  fn load(
    key: SimpleKey,
    storage: &mut Storage<C, SimpleKey>,
    _: &mut C
  ) -> Result<Loaded<Self, SimpleKey>, Self::Error> {
    // as we only accept filesystem here, we’ll ensure the key is a filesystem one
    match key {
      SimpleKey::Path(path) => {
        let mut fh = File::open(path).map_err(Error::IOError)?;
        let mut s = String::new();
        fh.read_to_string(&mut s);

        Ok(FromFS(s).into())
      }

      SimpleKey::Logical(_) => Err(Error::CannotLoadFromLogical)
    }
  }
}

fn main() {
  // we don’t need a context, so we’re using this mutable reference to unit
  let ctx = &mut ();
  let mut store: Store<(), SimpleKey> = Store::new(StoreOpt::default()).expect("store creation");

  let my_resource = store.get::<FromFS>(&Path::new("/foo/bar/zoo.json").into(), ctx);

  // …

  // imagine that you’re in an event loop now and the resource has changed
  store.sync(ctx); // synchronize all resources (e.g. my_resource)
}

Reloading a resource

Most of the interesting concept of warmy is to enable you to hot-reload resources without having to re-run your application. This is done via two items:

  • Load::reload, a method called whenever an object must be reloaded.
  • Store::sync, a method to synchronize a Store.

The Load::reload function is very straight-forward: it’s called when the resource changes. This situation happens:

  • Either when the resource is on the filesystem (the file changes).
  • Or if it’s a dependent resource of one that has reloaded.

See the documentation of Load::reload for further details.

Context inspection

A context is a special value you can access to via a mutable reference when loading or reloading. If you don’t need any, it’s highly recommended not to use () when implementing Load<C> but leave it as type variable so that it compose better – i.e. impl<C> Load<C>.

If you’re writing a library and need to have access to a specific value in a context, it’s also recommended not to set the context type variable to the type of your context directly. If you do that, no one will be able to use your library because types won’t match – or people will accept to be restrained to your only types. A typical way to deal with that is by constraining a type variable. The Inspect trait was introduced for this very purpose. For instance:

use std::fmt;
use std::io;
use warmy::{Inspect, Load, Loaded, SimpleKey, Store, StoreOpt, Storage};

// Possible errors that might happen.
#[derive(Debug)]
enum Error {
  CannotLoadFromFS,
  CannotLoadFromLogical,
  IOError(io::Error)
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    match *self {
      Error::CannotLoadFromFS => f.write_str("cannot load from file system"),
      Error::CannotLoadFromLogical => f.write_str("cannot load from logical"),
      Error::IOError(ref e) => write!(f, "IO error: {}", e),
    }
  }
}

struct Foo;

struct Ctx {
  nb_res_loaded: usize
}

impl<C> Load<C, SimpleKey> for Foo where Foo: for<'a> Inspect<'a, C, &'a mut Ctx> {
  type Error = Error;

  fn load(
    key: SimpleKey,
    storage: &mut Storage<C, SimpleKey>,
    ctx: &mut C
  ) -> Result<Loaded<Self, SimpleKey>, Self::Error> {
    Self::inspect(ctx).nb_res_loaded += 1; // magic happens here!

    Ok(Foo.into())
  }
}

fn main() {
  use warmy::{Res, Store, StoreOpt};

  let mut store: Store<Ctx, SimpleKey> = Store::new(StoreOpt::default()).unwrap();
  let mut ctx = Ctx { nb_res_loaded: 0 };

  let r: Res<Foo> = store.get(&"test-0".into(), &mut ctx).unwrap();
}

In this example, because the context value we want is the same as the Store’s context, a universal implementor of Inspect enables you to directly inspect the context. However, if you wanted to inspect it more precisely, like with &mut usize, you would need to write an implementation of Inspect for your types:

use std::fmt;
use std::io;
use warmy::{Inspect, Load, Loaded, SimpleKey, Store, StoreOpt, Storage};

// Possible errors that might happen.
#[derive(Debug)]
enum Error {
  CannotLoadFromFS,
  CannotLoadFromLogical,
  IOError(io::Error)
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
    match *self {
      Error::CannotLoadFromFS => f.write_str("cannot load from file system"),
      Error::CannotLoadFromLogical => f.write_str("cannot load from logical"),
      Error::IOError(ref e) => write!(f, "IO error: {}", e),
    }
  }
}

struct Foo;

struct Ctx {
  nb_res_loaded: usize
}

// this implementor states how the inspection should occur for Foo when the context has type
// Ctx: by targetting a mutable reference on a usize (i.e. the counter)
impl<'a> Inspect<'a, Ctx, &'a mut usize> for Foo {
  fn inspect(ctx: &mut Ctx) -> &mut usize {
    &mut ctx.nb_res_loaded
  }
}

// notice the usize instead of Ctx here
impl<C> Load<C, SimpleKey> for Foo where Foo: for<'a> Inspect<'a, C, &'a mut usize> {
  type Error = Error;

  fn load(
    key: SimpleKey,
    storage: &mut Storage<C, SimpleKey>,
    ctx: &mut C
  ) -> Result<Loaded<Self, SimpleKey>, Self::Error> {
    *Self::inspect(ctx) += 1; // direct access to the counter

    Ok(Foo.into())
  }
}

Load methods

warmy supports load methods. Those are used to specify several ways to load an object of a given type. By default, Load is implemented with the default method – which is (). If you want more methods, you can set the type parameter to something else when implementing Load.

You can also find several methods centralized in here, but you definitely don’t have to use them.

Universal JSON support

The crate supports universal JSON implementation. You can use it via the Json type.

Universal JSON support is feature-gated with "json".

Universal JSON can help and make your life and implementations easier. Basically, it means that any type that implements serde::Deserialize can be loaded and hot-reloaded by warmy with zero boilerplate from your side, just by asking warmy to get the given scarse resource. This is done with the Store::get_by or Store::get_proxied_by methods.

use serde::Deserialize;
use warmy::{Res, SimpleKey, Store, StoreOpt};
use warmy::json::Json;
use std::thread::sleep;
use std::time::Duration;

#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
struct Dog {
  name: String,
  gender: Gender
}

impl Default for Dog {
  fn default() -> Self {
    Dog {
      name: "Norbert".to_owned(),
      gender: Gender::Male
    }
  }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
enum Gender {
  Female,
  Male
}

fn main() {
  let mut store: Store<(), SimpleKey> = Store::new(StoreOpt::default()).unwrap();
  let ctx = &mut ();

  let resource: Result<Res<Dog>, _> = store.get_by(&SimpleKey::from_path("/dog.json"), ctx, Json);

  match resource {
    Ok(dog) => {
      loop {
        store.sync(ctx);

        println!("Dog is {} and is a {:?}", dog.borrow().name, dog.borrow().gender);
        sleep(Duration::from_millis(1000));
      }
    }

    Err(e) => eprintln!("{}", e)
  }
}

Universal TOML support

The crate also supports universal TOML implementation. That implementation is available via the Toml type.

Universal TOML support is feature-gated with "toml-impl".

The working mechanism is the same as with universal JSON support.

Resource discovery

Resource discovery is available via a simple mechanism: every time a new resource is available on the filesystem, a closure of your choice is called. This closure is passed the Storage of your Store along with its associated context, enabling you to insert new resources on the fly.

This is a bit different than the first option: this enables you to populate the store with resources you don’t know yet – e.g. a texture is saved in the store’s root and gets automatically added and reacted to.

The feature is available via the StoreOpt object you have to create prior to generating a new Store. See the StoreOpt::set_discovery and StoreOpt::discovery functions for further details on how to use the resource discovery mechanism.

More Repositories

1

hop.nvim

Neovim motions on speed!
Lua
2,121
star
2

luminance-rs

Type-safe, type-level and stateless Rust graphics framework
Rust
1,073
star
3

mind.nvim

The power of trees at your fingertips.
Lua
704
star
4

this-week-in-neovim-contents

Contents of weekly news delivered by this-week-in-neovim.org.
261
star
5

this-week-in-neovim.org

this-week-in-neovim.org official webapp repository
Rust
183
star
6

glsl

GLSL parser for Rust
Rust
180
star
7

splines

Interpolation made easy.
Rust
131
star
8

spectra

Rust demoscene engine (currently on hold)
Rust
124
star
9

luminance

Type-safe, type-level and stateless Haskell graphics framework
Haskell
110
star
10

shades

Rust EDSL for shading languages
Rust
66
star
11

config

My main configuration files
Lua
65
star
12

cargo-sync-readme

Generate a Markdown section in your README based on your Rust documentation
Rust
55
star
13

toodoux

A task manager based on taskwarrior
Rust
51
star
14

mind

The power of trees at your fingertips
Rust
42
star
15

notisys.nvim

System-wide notifications for Neovim
Lua
40
star
16

do-notation

The Haskell’s do notation brought to Rust
Rust
39
star
17

cheddar

The Cheddar GLSL superset language
Rust
27
star
18

spline-editor

A simple spline editor for the splines crate
Rust
24
star
19

wavefront

Haskell Wavefront OBJ loader library
Haskell
19
star
20

bidule

Very simple and Rust FRP crate
Rust
18
star
21

poesie.nvim

Lua
16
star
22

stack-haddock-upload

A little script to upload documentation to Hackage within a stack-powered project
Shell
14
star
23

learn-luminance

11
star
24

luminance-gl-rs

DEPRECATED luminance-gl has been moved into https://github.com/phaazon/luminance-rs
Rust
11
star
25

celeri-remoulade

The Undead Sceners PC demo for Evoke 2016
Rust
10
star
26

smoothie

Smooth curves via several interpolation modes
Haskell
10
star
27

advent-of-code-2k18

https://adventofcode.com/2018
Rust
9
star
28

phaazon.net

Source code of phaazon.net.
Rust
8
star
29

kak-tree-sitter

tree-sitter meets Kakoune
Rust
8
star
30

try-guard

A guard! macro inspired by the guard Alternative function from Haskell.
Rust
6
star
31

luminance-samples

Luminance samples
Haskell
6
star
32

monad-journal

Pure logger typeclass and monad transformer
Haskell
6
star
33

outline-2017-invitro

Outline 2017 Invitation, by DESiRE and The Undead Sceners (code by @phaazon)
Rust
6
star
34

quaazar

Realtime 3D engine
Haskell
6
star
35

pixels-of-life

A GPU accelerated version of Conway’s Game of Life
Rust
5
star
36

save-z0r

Because those loops are too epic to let them go!
Rust
5
star
37

hsFModEx

FModEx Haskell API. Discontinued.
Haskell
4
star
38

hid

Haskell interface to hidapi
Haskell
4
star
39

any-cache

Cache with any key and any associated value
Rust
4
star
40

zero

Semigroups with absorbing element
Haskell
4
star
41

lightning-road-to-liquid-radiator

Official source code of Lightning Road To Liquid Radiator
C++
4
star
42

lqducul

Rust
4
star
43

cheddar-edit

A shader-toy-like project that aims to shader rapid prototyping
Rust
4
star
44

msi-kb-backlit

A command line tool to change backlit colors of your MSI keyboard
Haskell
3
star
45

reactant

FRP Haskell library
Haskell
3
star
46

non-empty

Efficient non-empty vectors in Rust
Rust
3
star
47

al

Haskell OpenAL raw binding
Haskell
3
star
48

glsl-quasiquote

The glsl! procedural macro for the glsl crate.
3
star
49

awoo

Rust
3
star
50

html-entities

Rust html entities utility functions
Rust
2
star
51

brainfarts

Pets de cerveaux.
2
star
52

kwak

The (in)famous bot you all love on IRC! (see her in action in #demofr@freenode)
Rust
2
star
53

luminance-windowing

Common windowing code for luminance (not an actual backend)
2
star
54

event

Monoidal, monadic and first-class events.
Haskell
2
star
55

par-soeur

Run away, nothing to see here!
Rust
2
star
56

advent-of-code-2021

https://adventofcode.com/
Rust
2
star
57

luminance-glutin

glutin support for luminance
Rust
2
star
58

proc-macro-faithful-display

A more faithful Display for proc-macro token types.
Rust
2
star
59

thunk

Some research project of mine about sharing thunks in Rust
Rust
2
star
60

tellbot

IRC bot with account simple tasks and tells function
Haskell
2
star
61

inject-function

Haskell package that lets you write regular functions with the extra feature to be able to inject parameters that can be shared over function composition
Haskell
2
star
62

leaf

A simple portfolio generator
Haskell
2
star
63

rust-gl-toy

As I’m learning rust, let’s play with OpenGL and GLFW here ;)
Rust
1
star
64

igl

Indexed OpenGL; a safer OpenGL implementation
Haskell
1
star
65

algo

Some famous algorithms, written with fun
Rust
1
star
66

conal_frp

An experiment at implementing FRP as described by its father, Conal Elliott. Paper here http://conal.net/papers/push-pull-frp/push-pull-frp.pdf
Haskell
1
star
67

heat-station

Official source code of Heat Station
C++
1
star
68

chronos

Simple FRP timeline. Designed to be used for demoscene purposes
Haskell
1
star
69

luminance-glfw

GLFW support for luminance
1
star
70

skp

skp D framework
D
1
star
71

advent-of-code-2020

Haskell
1
star
72

gltf

Haskell GLTF loader
Haskell
1
star
73

aur

All packages I maintain in AUR
Shell
1
star
74

codingame-unleash-the-geek

My contribution to Unleash The Geek (started on 7th of October 2019)
Rust
1
star
75

meta

Demoscene framework
Perl
1
star
76

fractalis

A Mandelbrot fractal viewer
C
1
star
77

leetify

Leetify some text!
Haskell
1
star
78

agui

Abstract GUI
Haskell
1
star
79

impersonate

An experimental Markov chain generator that learns how to speak as if it was someone else.
Rust
1
star
80

sdffont

A tool that generates signed distance fields fontmap from font file (.ttf, and so on).
Haskell
1
star
81

hush

Demoscene soft synthesizer designed to be embedded in intros.
Rust
1
star
82

iutbx1-ds

IUT Bordeaux 1 Dimitri Sabadie official repository
C++
1
star
83

atoi-data-dependency

A short and fun study of data dependency and compiler optimizations
Rust
1
star
84

rcpp

A Rust implementation of the C Preprocessor
Rust
1
star
85

colorscheme-gen

A little tool to generate color scheme for urxvt session and using the Text Export option of the colorscheme web site.
Shell
1
star
86

phraskell

Fractal set viewer.
Haskell
1
star
87

blog

phaazon.net blog articles
1
star
88

advent-of-code-2022

Advent of Code 2022 solutions
Rust
1
star