lily/store

In Lily, the Store holds your model (application state) and message update logic. The same store within your shared package should be used on both frontend and backend. Each message updates the model, with the standard case of the update function being update(model: Model, message: Message) -> Model that uses pattern matching over potential messages:

pub type Model {
  Model(count: Int)
}

pub type Message {
  Increment
  Decrement
}

pub fn update(model: Model, message: Message) -> Model {
  case message {
    Increment -> Model(count: model.count + 1)
    Decrement -> Model(count: model.count - 1)
  }
}

Within your client/frontend code, you can then add the following to initialise the store:

let store = store.new(init: Model(count: 0), update: update)

This can then be passed onto client.start to begin a client-only app with a set store. To sync with a server, pipe it through sync, changing its type so that you can connect it on the frontend with client.connect and server.new on the backend.

The route function says where each message goes, to this connection’s session, to a shared topic, or staying on the client that sent it (Local).

Build one store in your shared package and hand the same value to both the client and the server:

import lily/store
import lily/transport

pub fn store() -> store.Store(Model, Message, store.Synced) {
  store.new(init: initial_model(), update: update)
  |> store.sync(
    route: fn(message) {
      // match on your message type's constructors
      case message {
        Chat(_) -> store.Topic("chat")
        Profile(_) -> store.Session
        Hover(_) -> store.Local
      }
    },
    modules: [transport.module("shared")],
  )
  |> store.session(
    get: fn(model) { model.session },
    set: fn(model, session) { Model(..model, session:) },
  )
  |> store.topic(
    id: "chat",
    get: fn(model) { model.chat },
    set: fn(model, chat) { Model(..model, chat:) },
    access: store.Open,
  )
}

The server runs update against its own copy of the model, one per connection and one per topic, and the client keeps only the slice that the get and set pair describes. Every copy starts from the initial model. A topic whose state lives somewhere else, like a database, can start from its own model with server.load_topic.

A snapshot carries just the slice, which relies on get(set(init, x)) giving back x. Topic messages reach every subscriber as they were sent, so keep what one subscriber mustn’t see out of them.

Keep update pure. A client replays its own unconfirmed messages through it on top of each fresh copy the server sends, which is how clients agree again after concurrent edits (see client).

Topics are basically shared stores with Access rules for subscriptions. topic declares one with a fixed id and topic_family a family of them whose ids share a prefix. An exact id beats any prefix, and among families the longest matching prefix wins, meaning a prefix should end with a separator (e.g. a colon). The server will start a topic the first time someone subscribes to it or the server dispatches to it with server.dispatch_to_topic. A topic stopped with server.stop_topic starts the same way, and the clients that held it are subscribed again when it does.

Access only says who may subscribe, what a client may send is up to authorise. Its rule gets the sender’s session and the copy the message would change, and on the server each knows nothing of the other, so read who’s sending only from the first.

Which topics a client subscribes/listens to is a function of its model under subscriptions. Lily compares it after every update and subscribes and unsubscribes to match.

A server that renders the first page can embed the model the client starts from with embed using the same serialiser the store syncs with.

Types

Who can subscribe to a topic, passed to topic and topic_family.

Allow gets the client id, the topic id and that client’s session model, which holds whatever the server wrote into it. A client it refuses sees a SubscriptionRejected.

A client can send any message routed to Session, so whatever Allow reads, identity above all, must be written by a message routed Local. The server drops a client’s Local message but applies one it sends itself, through a seed on server.connect_as or server.admit_as, or through server.dispatch_to.

pub type Access(model) {
  Open
  Allow(fn(String, String, model) -> Bool)
}

Constructors

  • Open

    Anyone can subscribe

  • Allow(fn(String, String, model) -> Bool)

    Only clients the function returns True for, given the client id, the topic id and the client’s session model, in that order

Where a message goes.

pub type Route {
  Session
  Topic(id: String)
  Local
}

Constructors

  • Session

    This client’s own session on the server

  • Topic(id: String)

    The shared topic with this id

  • Local

    Stays on this client and doesn’t go to the server

A store that doesn’t sync, for a client-only app.

pub type Standalone

Your model and update logic, shared by the client (client.start) and the server (server.new).

Create one with new.

pub opaque type Store(model, message, mode)

A store that syncs with a server, from sync. client.connect and server.new need one.

pub type Synced

Values

pub fn authorise(
  store: Store(model, message, Synced),
  rule rule: fn(model, model, message) -> Bool,
) -> Store(model, message, Synced)

Has the server drop a client message that rule turns down, one rule for every message a client sends to its session or a topic.

rule gets the sender’s session, the copy the message would change and the message. Read who’s sending only from the first, see store. The client runs it too, before applying its own message, and a rule that crashes refuses.

|> store.authorise(rule: fn(sender, target, message) {
  case message {
    DeleteNote(id:) -> note_author(target, id) == Some(sender.session.user)
    _ -> True
  }
})
pub fn embed(
  store: Store(model, message, Synced),
  model model: model,
) -> String

Embeds model in a server-rendered page as a <script> tag, letting client.start start from it.

It only carries the model, rendering the page’s HTML is up to you. A model that has no wire form, an Int past what JavaScript holds say, embeds nothing and logs why.

let body = "<!DOCTYPE html><html><body>"
  <> "<div id=\"app\">" <> rendered_html <> "</div>"
  <> store.embed(shared.store(), model: initial_model)
  <> "</body></html>"
pub fn new(
  init init: model,
  update update: fn(model, message) -> model,
) -> Store(model, message, Standalone)

Creates a store, with an init model (like Lustre’s init) and a function that updates the model for a given message.

store.new(init: Model(count: 0, user: "Someone"), update: update)
pub fn schema(
  store: Store(model, message, Synced),
  schema: transport.Schema,
) -> Store(model, message, Synced)

Has the server drop a client message whose shape doesn’t match schema, built with transport.schema.

store.sync(store, route:, modules: [transport.module("shared")])
|> store.schema(lily_schema.schema())
pub fn session(
  store: Store(model, message, Synced),
  get get: fn(model) -> slice,
  set set: fn(model, slice) -> model,
) -> Store(model, message, Synced)

Says which part of the model is this client’s session, through a get and set pair, making sure the server’s copy of it lands in the right place.

Needed whenever route sends anything to Session. Without it the server still applies those messages but its copy doesn’t reach the client, which warns once with a Diagnostic.

store.session(
  get: fn(model) { model.session },
  set: fn(model, session) { Model(..model, session:) },
)
pub fn subscriptions(
  store: Store(model, message, Synced),
  subscriptions: fn(model) -> List(String),
) -> Store(model, message, Synced)

The topic ids this client wants to subscribe to, as a function of its model.

Lily subscribes and unsubscribes after every update to match, sparing you from doing it by hand.

store.subscriptions(fn(model) {
  case model.joined_room {
    option.Some(room) -> ["room:" <> room]
    option.None -> []
  }
})
pub fn sync(
  store: Store(model, message, Standalone),
  route route: fn(message) -> Route,
  modules modules: List(transport.Module),
) -> Store(model, message, Synced)

Adds client-server synchronisation to the store.

route decides where each message goes (see Route) and modules names the modules that define the types you send, letting Lily serialise them for you.

store.new(init: initial_model(), update: update)
|> store.sync(route: route, modules: [transport.module("shared")])

Messages travel as JSON on localhost and MessagePack everywhere else, letting you read them in DevTools while developing. Use sync_with to pick one.

pub fn sync_with(
  store: Store(model, message, Standalone),
  route route: fn(message) -> Route,
  serialiser serialiser: transport.Serialiser(model, message),
) -> Store(model, message, Synced)

Syncs the store with a serialiser of your own, from transport.automatic or transport.serialiser.

pub fn topic(
  store: Store(model, message, Synced),
  id id: String,
  get get: fn(model) -> slice,
  set set: fn(model, slice) -> model,
  access access: Access(model),
) -> Store(model, message, Synced)

Declares a single topic shared between clients, matched by its exact id.

get and set read and write its part of the model and access says who can subscribe, see Access. Declaring the same id again replaces the earlier one.

store.topic(
  id: "chat",
  get: fn(model) { model.chat },
  set: fn(model, chat) { Model(..model, chat:) },
  access: store.Open,
)
pub fn topic_family(
  store: Store(model, message, Synced),
  prefix prefix: String,
  get get: fn(model, String) -> slice,
  set set: fn(model, String, slice) -> model,
  access access: Access(model),
) -> Store(model, message, Synced)

Declares a family of topics, every id that starts with prefix. Pair with subscriptions to join one by its full id.

get and set receive the rest of the id after the prefix. An exact topic id beats any family, and among families the longest matching prefix wins, meaning a prefix should end with a separator.

store.topic_family(
  prefix: "room:",
  get: fn(model, room) {
    dict.get(model.rooms, room) |> result.unwrap(new_room())
  },
  set: fn(model, room, state) {
    Model(..model, rooms: dict.insert(model.rooms, room, state))
  },
  access: store.Open,
)
✨ Search Document