tricu

A lazy functional language based on Tree Calculus
Log | Files | Refs | README | LICENSE

events.tri (2061B)


      1 !import bd2c14d6db6b69308a5252a8e839705a55d30e815f012900b094315263e08d81 *
      2 !import 3f70d95cf1bae0928ee89acd2a9e0cdd8287796efae32a9f08d33e3dd0149c55 *
      3 !export vendorA
      4 !export vendorB
      5 
      6 -- Event adapter: two producers, one consumer-facing record schema.
      7 -- vendorA accepts [eventName customer totalCents]. eventName is purchase/refund.
      8 -- vendorB accepts [customer refunded totalCents]. refunded is a Boolean.
      9 -- Both return schemaVersion, eventType, customer and amountCents.
     10 -- Try result = vendorA ["purchase" "James" 2499].
     11 -- Try result = vendorB ["James" false 2499] to describe the same event.
     12 -- A producer can publish the adapter hash alongside its event schema.
     13 -- Records use [fieldName tag value]: 0 = text, 1 = natural, 2 = Boolean.
     14 -- Base supplies arithmetic/Booleans; hostString? checks Unicode scalar text.
     15 
     16 failure message = [["status" 0 "error"] ["message" 0 message]]
     17 
     18 normalized event customer cents = case hostString? customer of
     19   ^true = case and? (isNat? cents) (lte_? cents 1000000) of
     20     ^true = [["schemaVersion" 1 1] ["eventType" 0 event]
     21       ["customer" 0 customer] ["amountCents" 1 cents]]
     22     _ = failure "amountCents must be a canonical natural <=1000000."
     23   _ = failure "customer must be scalar text."
     24 
     25 fromA "purchase" customer cents = normalized "order.created" customer cents
     26 fromA "refund" customer cents = normalized "order.refunded" customer cents
     27 fromA _ _ _ = failure "Unknown vendor A event."
     28 
     29 fromB customer ^true cents = normalized "order.refunded" customer cents
     30 fromB customer ^false cents = normalized "order.created" customer cents
     31 fromB _ _ _ = failure "refunded must be a canonical Boolean."
     32 
     33 -- Preserve list-shape diagnostics without inspecting any field before dispatch.
     34 unpack handler (t _) = failure "Expected a list."
     35 unpack handler [_ | (t _)] = failure "Expected a list."
     36 unpack handler [_ | [_ | (t _)]] = failure "Expected a list."
     37 unpack handler [a b c] = handler a b c
     38 unpack _ _ = failure "Expected exactly three fields."
     39 
     40 vendorA values = unpack fromA values
     41 vendorB values = unpack fromB values