
PipelineBehaviors.pudu
Pudu69 lines2.9 KB
1/** @Examples.PipelineBehaviors.Program — open and per-kind behaviors, pre- and post-processors */2module PipelineBehaviors34import Std.Io as Io5import Std.Time as Time6import PuduLangMediator.Context as Context7import PuduLangMediator.Mediator as Mediator8import PuduLangMediator.Message as Message9import PuduLangMediator as Messaging10import PuduLangMediator.Open as Open11import PuduLangMediator.Registration as Registration12import PuduLangMediator.Request as Request1314/** @Examples.PipelineBehaviors.Timing — an open behavior that times every request */15type Timing = {}1617impl Open.Behavior for Timing {18 19 fn handleRequest[Q, R, E](self: &Self, request: &Q, info: &Message.Info, context: Context.Context, next: Request.Next[R, E]) -> Messaging.Outcome[R, E] {20 let began = Time.elapsed()21 let outcome = next(context)22 let _said = Io.writeLine(info.name + " took " + show(Time.elapsed() - began) + " ms")23 outcome24 }25}2627/** @Examples.PipelineBehaviors.Audit — an open pre-processor that prints every request */28type Audit = {}2930impl Open.PreProcessor for Audit {31 32 fn beforeRequest[Q, E](self: &Self, request: &Q, info: &Message.Info, context: Context.Context) -> Messaging.Outcome[(), E] {33 let _said = Io.writeLine("audit: " + info.name + " " + show(*request))34 Ok(())35 }36}373839fn main() -> Int {40 let quote: Request.Kind[Str, Int, Str] = Request.kind("prices.quote")41 let cache: Context.Key[Int] = Context.key("cached")42 let built = Mediator.build([43 Registration.openBehavior(Timing{}),44 Registration.openPreProcessor(Audit{}),45 Registration.behavior("e, fn(item: Str, context: Context.Context, next: Request.Next[Int, Str]) -> Messaging.Outcome[Int, Str] {46 if item == "free sample" { Ok(0) } else { next(context) }47 }),48 Registration.postProcessor("e, fn(item: Str, price: Int, context: Context.Context) -> Messaging.Outcome[(), Str] {49 Context.set(&context, &cache, price)50 let _said = Io.writeLine("cached " + item + " at " + show(price))51 Ok(())52 }),53 Registration.handler("e, |item: Str, _context: Context.Context| if item == "tea" { Ok(4) } else { Messaging.raise("no price for " + item) })54 ])55 let mediator = match built {56 case Ok(found) => found57 case Err(invalid) => {58 let _said = Io.writeErrorLine(Mediator.explain(&invalid))59 return 160 }61 }62 let context = Context.create()63 let tea = Mediator.sendWith(&mediator, "e, "tea", context)64 let sample = Mediator.send(&mediator, "e, "free sample")65 let gold = Mediator.send(&mediator, "e, "gold")66 let _said = Io.writeLine(Messaging.summarize(&gold))67 if tea == Ok(4) && sample == Ok(0) && Context.get(&context, &cache) == Some(4) && gold == Err(Messaging.Raised("no price for gold")) { 0 } else { 1 }68}69