• Stars
    star
    203
  • Rank 192,890 (Top 4 %)
  • Language Reason
  • Created over 5 years ago
  • Updated over 4 years ago

Reviews

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

Repository Details

Milk 🥛 Stress-free serialization & deserialization for Reason/OCaml

Milk 🥛 : Stress-free serialization & deserialization for Reason/OCaml

🚧 Stability: settling 🚧 This is recently released, still settling down API n stuff, but I plan to maintain backwards compatability. Also I'm still working on documentation, so some things might be missing or unclear.

Usage: milk [config file] [options]

If no config file is provided, `types.json` will be used if it exists,
otherwise the `milk` section of esy.json or package.json will be used if
it exists.

Options:

- --init     : create a new config file for the current project

(rarely used)

- --override : Ignore current lockfile version, overriding conflicts.
               NOTE: This should only be passed if you have not stored any
               data using the currently generated serde, as it may now be
               unparseable.
- --upvert   : Convert a legacy config file (generated with a previous
               version of milk) to the current schema.

Configuration

This goes either in a separate JSON file (e.g. types.json), or in a "milk" section of your esy.json or package.json.

Example types.json:

{
  "milkSchemaVersion": 2,
  "version": 1,
  "engines": {
    "bs.json": {
      "output": "./src/Serde.re"
    }
  },
  "entries": [
    {
      "file": "./src/Types.re",
      "type": "config"
    },
    {
      "file": "./src/Node.re",
      "type": "t",
      "publicName": "node"
    }
  ]
}

See the types.json in this repo for another example, or this one over here.

Full spec:

  • milkSchemaVersion: int this is the milk config file schema version. The latest version is 2 (the one documented here).
  • version: int : this is the version of your types. When you serialize anything, it will have this version attached to it, so that the data can be deserialized in the future & migrated through any subsequent versions. When you make a "breaking change" (see below for details), you'll need to increment this version number, and provide any necessary migrator functions (see below for migration details).
  • lockedTypes: string : If you have multiple engines defined, then this is required, otherwise it's optional. This file is where all of the types for all of the versions that exist in your lockfile will be generated, for use by deserialization and migration functions.
  • engines: {[key: engine_name]: engineConfig} : a mapping of engine_name to engineConfig, where engine_name is one of rex_json, bs_json, ezjsonm, and yojson.
    • engineConfig: {output: string, helpers: option(string)}. Output is the file where the serializer & deserializer functions should be output to, and helpers is the name of the module that contains any necessary TransformHelpers (see below)
  • entries: list(entry) : the list of your "entry point" types. These are the types that you want to be able to serialize & deserialize.
    • file: string the source file where this type is defined
    • type: string the name of the type within the file, including containing submodules. e.g. someType if it's at the top level, or SomeModule.InnerModule.t if it's nested.
    • publicName: string the name that will be used in the externally usable serialization & deserialization functions. e.g. if your type name is t, having a function called deserializeT won't be super helpful, so you can put publicName: "animal" and you'll get deserializeAnimal
  • custom: list(custom). "Custom" types are types for which you want to be treated as opaque -- milk will not generate ser/de functions for them, and you will provide those in the helpers module(s).
    • module: string the module name the contains the type you want to override. e.g. Animals
    • path: list(string) the path within the module, if there's nesting. If the type is Animals.Dogs.t, this would be ["Dogs"]
    • name: string the name of the type to override. e.g. t
    • args: int the number of type arguments that the type has.

How does it work?

Milk has two phases. 1) generate/update lockfile. 2) generate serialization, migration, and deserialization code for all known types & versions.

Generate/update lockfile

A lockfile consists of an array of "locked type maps", each corresponding to a "version" of your types. A "locked type map" is a map from a "module path" (like MyModule.SubModule.typename) to a serialization of the type declaration, including any @attributes.

Milk first creates a "locked type map" for the current state of your types, starting with your "entry types", and recursively following any type references down to their definitions. Then, if there's a current lockfile & the version in types.json has not been incremented, it checks for incompatible changes & errors out in that case. If the changes are compatible (see below), it overwrites the locked type map, and if the version number has been incremented since the last type Milk was run, it appends the type map to the array. The whole array is then written out to the lockfile.

Generate code!

First, the "locked types" are generated. For each version, a TypesN module is created that contains the type definition for every type needed to fully define all of the entry types for that version. The final (current) version also aliases those type definitions to the definitions used in the rest of your app. Also, migration functions are auto-generated (if possible), or referenced (if defined as decorators, see below). If a migration function cannot be auto-generated, and has not been provided, Milk errors out with a message indicating the migration function that's missing.

With the "locked types" modules, Milk is able to create type-safe deserializers for all previous versions of your types, after you have made changes to the types used in the rest of your app.

Next, deserialization functions are created (recursively) for all versions in the lockfile.

Then, serialization functions are created for the latest version.

Finally, "entry point" serializeThing and deserializeThing functions are created, with the deserialize function checking the schema version of the data passed in, and performing any necessary migrations to get it up to the current version of the type.

Migrations!

When you make a backwards-incompatible change (see below) to a type, you must provide functions to migrate from the previous version to the current version, in the form of [@ decorators.

For a "whole type" migration, provide a function as a [@migrate ] decorator that takes data of the old type and returns data of the new type.

// previous type definition
type person = {name: string, age: int};
// new type, with decorator
[@migrate ({name, age}) => {name, age: float_of_int(age), favoriteColor: None}]
type person = {name: string, age: float, favoriteColor: option(string)};

Records

You can also provide migrator functions on an attribute basis, which is especially helpful if the type is large.

// previous type definition
type person = {name: string, age: int};
// new type, with decorator
[@migrate.age person => float_of_int(person.age)]
[@migrate.favoriteColor (_) => None]
type person = {name: string, age: float, favoriteColor: option(string)};

Note that the per-attribute migration function takes the whole previous record as the argument, so that you can provide migrators for newly added attributes as well.

Variants

If you remove a constructor from a variant, or modify a constuctor, you can provide a per-constructor migrator. The "function" that you're passing in actually gets dissected and turned into a case of a switch block, so keep that in mind (which is why I'm deconstructing the individual case in the function argument, which would usually cause problems).

// previous type definition
type animal = Dog(string) | Cat | Mouse;
// new type definition
[@migrate.Dog (Dog(breed)) => Dog(breed, None)]
[@migrate.Mouse (Mouse) => Cat] // yeah this doesn't make sense as a migration to me either
type animal = Dog(string, option(int)) | Cat;

Abstract Types

For abstract types that you want to support, add manual serialization and deserialization functions.

Make sure to list the module that provides the serialize and deserialize functions in the "helpers" section of your types.json file:

   "version": 1,
   "engines": {
     "Js.Json": {
-      "output": "src/TypesEncoder.re"
+      "output": "src/TypesEncoder.re",
+      "helpers": "EncoderHelpers"
     }
   },
   "entries": [

Then define the serialize and deserialize functions. Here is an example of the function signatures to support a StringMap.t('a):

/* EncoderHelpers.re */
let serialize_StringMap____t = map => /* ... */
let deserialize_StringMap____t = json => /* ... */
let deserialize_StringMap____t = (migrator, json) => /* ... */

Here are some real-world examples:

What type changes are "compatible"

(e.g. don't require a version bump)

  • adding a constructor to a variant type
  • adding a row to a polymorphic variant type (TODO not yet supported)
  • adding a new "entry" type
  • adding an optional attribute for a record (will default to None)
  • removing an attribute from a record

More Repositories

1

hexo-admin

An Admin Interface for Hexo
JavaScript
1,763
star
2

treed

Powerful Tree Editor
JavaScript
1,710
star
3

reason-language-server

A language server for reason, in reason
OCaml
659
star
4

gravitron

a little game
OCaml
490
star
5

rxvision

visualizer debugger for reactive streams
HTML
425
star
6

qmoji

🙃 Like mojibar, but written in swift
Swift
294
star
7

vim-debug

A plugin for VIM that creates an Integrated Debugging Environment :) Currently works with PHP and Python
Python
283
star
8

github-issues-viewer

A gitub issues viewer build in react + backbone
JavaScript
239
star
9

local-first

data syncing, storage, and collaboration. that works
JavaScript
220
star
10

veoluz

"I see light" - visualize the paths of millions of light rays through reflection, refraction and diffusion
Rust
153
star
11

redoc

A clean & easy documentation generator for reason/bucklescript/ocaml
JavaScript
117
star
12

stylecleanup

Find & fix unused styles in react native and aphrodite
JavaScript
114
star
13

fluid

OCaml
110
star
14

reason-macros

Template-based macros for Reason/OCaml
OCaml
106
star
15

codetalker

A succinct, pythonic parser + translator solution
Python
100
star
16

let-anything

Deprecated, use the reasonml-community one
OCaml
99
star
17

ohai

easy setup from ocaml/reason native projects
OCaml
98
star
18

a-reason-react-tutorial

included code for A ReasonReact Tutorial
CSS
92
star
19

django-appsettings

A unified settings system for reusable django apps
Python
88
star
20

hooks-experimental

An experiment using react's new "hooks" with ReasonReact
OCaml
75
star
21

pack.re

a simple js bundler for reason
OCaml
72
star
22

reason-cli-tools

A cross-platform collection of useful utilities for making cli's in reason
OCaml
68
star
23

unison.rs

Scheme
65
star
24

reason_async

OCaml
65
star
25

reprocessing-scripts

OCaml
64
star
26

reepl

The cljs Read-eval-print-loop that really understands you
Clojure
63
star
27

reason-websocket

A websocket library for reason native
OCaml
57
star
28

django-feedback

A reusable django app to add an AJAX "feedback" tab to your site
Python
57
star
29

PJs

kinda like pyjamas, but quicker, cleaner, and easier. has the goal of generating readable, usable *robust* javascript code from python code
JavaScript
53
star
30

isomagic-todos

OCaml
51
star
31

terraform

rust + usgs data = 3d-printable models of mountains, canyons, etc.
Rust
51
star
32

myntax

OCaml
50
star
33

reprocessing-example-cross-platform

A boilerplate example for getting cross-platform reprocessing games off the ground
OCaml
50
star
34

purple-maze

A maze game written in reasonml
OCaml
45
star
35

rex-json

A simple cross-target JSON parser for Reason/OCaml
OCaml
45
star
36

reason-simple-server

A simple server library for native reason
OCaml
42
star
37

get_in_ppx

Reason
40
star
38

clevercss2

A complete rewrite of clevercss, utilizing the codetalker library
Python
39
star
39

pydbgp

A fork of Activestate's PyDBGp server
Python
37
star
40

reason-lisp-example

An example of using the lisp syntax for reason/ocaml
35
star
41

js_deep_ppx

[@js.deep] for immutably updating nested javascript objects in Reason/OCaml
OCaml
35
star
42

jerd

TypeScript
35
star
43

demobox

Demo Page Generator & Live Editor Component
JavaScript
35
star
44

minimist.re

A no-frills cli argument parser for reason
OCaml
34
star
45

f3d

OCaml
34
star
46

react-router

An integrated router for react
JavaScript
33
star
47

rusty-automata

Cellular Automata in Rust
Rust
29
star
48

vscode-background-terminal-notifier

Get a notification when a long-running terminal process completes in the background.
JavaScript
27
star
49

ppx_autoserialize

OCaml
27
star
50

hexo-renderer-handlebars

JavaScript
26
star
51

hexium

CSS
25
star
52

grow

Generative art
Rust
23
star
53

belt

Bucklescript's belt library packaged for native ocaml / dune / esy
OCaml
22
star
54

ocaml-cross-mobile

Shell
19
star
55

css

A small, fast css parser in python that utilizes the codetalker library
Python
16
star
56

drupal2django

A tool for migrating a blog from drupal to django; supports nodes, users, redirects, and more
Python
16
star
57

rsnpaint

experimenting with animations + reasonml
OCaml
15
star
58

mocha-selenium

Run selenium tests in parallel using mocha
JavaScript
15
star
59

lost-ranger

OCaml
15
star
60

reason_async_example

OCaml
15
star
61

hybrid-logical-clocks-example

JavaScript
14
star
62

tutorial-cljs

Clojure
14
star
63

reason-docker-server

An example cohttp server w/ dockerfile for deploying to now.sh
Dockerfile
14
star
64

esyi

OCaml
13
star
65

django-restive

A library for enabling the easy and intuitive creating of RESTful services in django
Python
13
star
66

react-teleporter

Make teleportable components
JavaScript
12
star
67

Contruct

the free open-source game creator by scirra
C++
12
star
68

babytux

A game based on babysmash, for occupying small children at the computer
Python
12
star
69

j3

Another attempt to realize my programming language
TypeScript
10
star
70

jaredly.github.io

node.js python data science golang philosophy faith. in no particular order
JavaScript
10
star
71

reason-bucklescript-example

Very bare bones starter pack for reason and bucklescript
OCaml
10
star
72

flame-rsn

OCaml
9
star
73

ssh-keypair

JavaScript
8
star
74

reason-docs

This is the old version: go to
JavaScript
7
star
75

letop-bs-example

OCaml
7
star
76

cowcow

http://cowcow.surge.sh/
OCaml
7
star
77

jfcom

repository for my website
Python
6
star
78

pbj

python build jelly - a simple, extensible pythonic build framework
Python
6
star
79

jnew

JavaScript
6
star
80

reactconf

Relay, Redux, Om/next Oh my!
JavaScript
6
star
81

type-safe-react-native

JavaScript
5
star
82

redu

A disk usage analyser, that's just a simple GUI on top of `du -sh`
OCaml
5
star
83

geometricart

TypeScript
5
star
84

advent-2017

OCaml
5
star
85

rocks

Go
5
star
86

itreed

Notablemind:repl a tree-based interface for iPython and Gorilla-repl
JavaScript
5
star
87

coqdocs

The docs I wish I had while learning Coq
Coq
5
star
88

blender

My blender scripts
Python
5
star
89

graphql-flow

Generate flowtypes for your graphql queries
JavaScript
4
star
90

ppx_guard

early returns for ocaml/reason
OCaml
4
star
91

j2

TypeScript
4
star
92

ppx_import

OCaml
4
star
93

type-safe-react

JavaScript
4
star
94

ferver

fe(a)rver - versioning for those of us who only care about breaking changes
4
star
95

pyjamas

a git clone of the sourceforge repo @ https://pyjamas.svn.sourceforge.net/svnroot/pyjamas
Python
4
star
96

move-over-electron

JavaScript
3
star
97

example-reason-codemod

OCaml
3
star
98

cowsay

A repo demonstrating the serializer generator "milk"
OCaml
3
star
99

code-review-checker

Sits in your mac menu par, checking for code reviews
Reason
3
star
100

bees

OCaml
3
star