Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-mediator

In-process messaging for Pudu: requests, notifications, streams, pipeline behaviors, processors, and exception handling

0.1.0Apache-2.01

InstallClose

UntypedDispatch.pudu

Pudu44 lines2.0 KB

GitHub ↗
1/** @Examples.UntypedDispatch.Program — envelopes routed by a component that names no types */2module UntypedDispatch34import Std.Io as Io5import PuduLangMediator.Context as Context6import PuduLangMediator.Mediator as Mediator7import PuduLangMediator.Message as Message8import PuduLangMediator as Messaging9import PuduLangMediator.Notification as Notification10import PuduLangMediator.Registration as Registration11import PuduLangMediator.Request as Request1213/// Runs every envelope of a queue through the mediator, as a job runner that names no types would.14fn drain(mediator: &Mediator.Mediator, queue: Array[Message.Envelope]) -> Array[Message.Answer] {15  queue.map(fn(envelope: Message.Envelope) -> Message.Answer {16      match envelope.info.shape {17        case Message.Event => Mediator.broadcast(mediator, envelope)18        case _ => Mediator.dispatch(mediator, envelope)19      }20    })21}2223/// Queues three envelopes of different types and reads each answer back with its kind.24fn main() -> Int {25  let square: Request.Kind[Int, Int, Str] = Request.kind("math.square")26  let shout: Request.Kind[Str, Str, Str] = Request.kind("text.shout")27  let ticked: Notification.Kind[Int, Str] = Notification.kind("clock.ticked")28  let mediator = match Mediator.build([29      Registration.handler(&square, |n: Int, _context: Context.Context| Ok(n * n)),30      Registration.handler(&shout, |text: Str, _context: Context.Context| Ok(text.toUpper() + "!"))31    ]) {32    case Ok(found) => found33    case Err(invalid) => panic(Mediator.explain(&invalid))34  }35  let answers = drain(&mediator, [Request.envelope(&square, 12), Request.envelope(&shout, "hello"), Notification.envelope(&ticked, 1)])36  for answer in answers {37    let _said = Io.writeLine(answer.info.name + " -> " + answer.summary)38  }39  let squared = Request.answerOf(&square, &answers[0])40  let shouted = Request.answerOf(&shout, &answers[1])41  let heard = Notification.answerOf(&ticked, &answers[2])42  if squared == Some(Ok(144)) && shouted == Some(Ok("HELLO!")) && heard == Some(Ok(())) { 0 } else { 1 }43}44