cellplatform / platform-0.2.0

/sys (shared system modules)
Other
4 stars 2 forks source link

Cmd: type refactor #197

Closed philcockfield closed 4 months ago

philcockfield commented 4 months ago

Cmd (Command)

Distributed function execution via CRDT sync (aka. "Command" invokation).
Provides a way to invoke functions remotely via a principled API.
Beyond it's direct use, Cmd provides the foundations for a basic "actor system" implementation.

Command instantiation:

const cmd = Cmd.create<C>(crdt);
const events = cmd.events(dispose$);

Sample command type definitions:

type P = { a: number; b: number };
type R = { sum: number };
type E = t.CmdError & { code: number; type: 'bounds' };

type C = C1 | C2 | C3;
type C1 = t.CmdType<'add', P, C2, E>;
type C2 = t.CmdType<'add:res', R>;
type C3 = t.CmdType<'foo', { msg?: string }>;

Invoke, no response:

cmd.invoke('foo', { msg: "👋" });
cmd.invoke('add', { a: 1, b: 2 }); // NB: doesn't make sense, as the response would be useful.

Invoke response async/await:

const res = await cmd.invoke(['add', 'add:res'], { a: 1, b: 2 }).promise()

Invoke response with callback:

cmd.invoke(['add', 'add:res'], { a: 1, b: 2 }, (e) => {
  e.error; /* handle error */
  e.result /* do something with result */
});

Sample chained invocation call:

await cmd
  .invoke(['add', 'add:res'], { a: 1, b: 2 })
  .onError((e) => /* log error */)
  .onComplete((e) => /* success */)
  .promise();

Sample command implementation (service):

const sum = ({ a, b }: P): R => ({ sum: a + b });
const cmd = Cmd.create<C>(crdt);
const events = cmd.events(dispose$);

events
  .on('add')
  .subscribe((e) => cmd.invoke('add:res', sum(e.params), e.tx));

image