# AOS Release 2.0.0 (AOS 2.0.0) :wave: Hey Developers, we hear you, AOS needs a DX upgrade and this release delivers! ## Install instructions for AOS 2.0.0 ```shell! npm i -g https://get_ao.g8way.io ``` > Use `.update` to update earlier aos processes. See the note below on what features are not supported on earlier processes. Cool features: * Receive the `await` of aos * REQ/RES semantics with References * default actions for handlers. ## `Receive()` the await of aos Meet `Lua Coroutines`, they are very similar to `await` or `generators`, coroutines are now added to aos handlers! > Coroutines are like taking turns playing a game with your friends. Each friend (coroutine) has a turn to play (do some work), but they don't finish all at once. Instead, they pause their turn (yield) so the next friend can play. When it's their turn again, they continue from where they left off (resume). This means you can send a message then `wait` using `Receive` method and when a message is send to your process that matches the pattern, you can get the result and resume your logic. Easier to show, than tell. ```lua= .editor Send({Target = ao.id, Data = "Hello"}) local res = Receive({Data = "Hello"}) print(res.Data) .done ``` The global Receive function yields until a msg is returned that matches that pattern, then it resumes executing the rest of the code. > NOTE: This feature is only available for AOS 2 processes, even if your process is upgraded to 2, coroutines can not be supported. ## REQUEST/RESPONSE semantics with References Often times, you want to receive a reply from the process as a response to the specific message you sent. aos 2.0 makes this pattern intuitive and seamless. setup the server handler _notice the msg.reply_ ```lua= .editor Handlers.add("Greeting-Name", { Action = "Greeting"}, function (msg) msg.reply({Data = "Hello " .. msg.Data or "bob"}) print('server: replied to ' .. msg.Data or "bob") end) .done ``` setup the client ```lua= .editor local greeting = Send({Target = ao.id, Action = "Greeting", Data = "George"}).receive().Data print("client: " .. greeting) .done ``` output ``` server: replied to George client: Hello George ``` When building complex workflows, developers need a request/response system that provides guarentees. ie returning message is that is directly referenced and handled. This works using built-in reference tags and using the `msg.reply` function on the server. try another example: ```lua= .editor local greeting = Send({Target = ao.id, Action = "Greeting", Data = "Spongebob"}).receive().Data print(greeting .. " Squarepants") ``` > NOTE: This feature is only available for AOS 2 processes, even if your process is upgraded to 2, coroutines can not be supported. ## default Action Handlers Handlers are a core design component when creating aos processes, they give developers a powerful pipeline for managing messages. The `Action` tag has become the common tag name to describe the intent of the incoming message. Now you can just supply a `value` to the pattern argument and it will infer `{ Action = [value] }` as your pattern matcher for this handler. Before AOS 2.0 ```lua Handlers.add("Get-Balance", function (msg) return msg.Action == "Balance", doBalance) ``` After AOS 2.0 ```lua Handlers.add("Get-Balance", "Balance", doBalance) ``` > If your pattern matcher is matching on Action = "xxx", you can just supply the string ## FYI Breaking Changes * The 'ao' module is now '.ao' - this allows us to update dynamically in the future. If you `require('ao')` in your code base, you will need to change to `require('.ao')` in AOS 2 processes. * Authority tags are required for all processes. Messages will not be trusted by default, any Spawn MUST supply Authority tags if they plan to receive messages from MUs. The new test MU is `fcoN_xJeisVsPXA-trzVAuIiqO3ydLQxM-L4XbrQKzY` * Message Tag `Ref_` has been replaced for `Reference` - aos 2.0 process will always use the 'Reference' tag as a unique message counter. * No more `result.Output.data.output`, aos processes always return a consistent `Output.data` shape: ```lua Output = { data = String, prompt = String, print = Boolean } ``` # Handlers version 0.0.5 Handlers increase the ability to manage messages, but the previous versions did not address complex logic flows between processes, in this version we leverage erlang style patterns to improve the handlers lua module to provide a powerful toolkit for developers to handle complex logic flows between their processes. ## Handlers.once Handlers.once is like `Handlers.add` but for handling only one message. This function allows you to supply a pattern and handle function and the next time it is matched AOS will process this handler, then remove it from the `Handlers.list`. ```lua Handlers.once( "onetime", { Action = "Run-Once"}, function (msg) print("This handler will only run once!") end ) ``` ## MaxRuns Optional `MaxRuns` argument for each handler, letting you choose the number of runs before it removes itself. default is infinite. ```lua Handlers.add( "example-handler", { Action = "Example" }, function(msg) print("Handler executed") end, 3 -- MaxRuns is set to 3 ) ``` ## \* Sending Messages .receive() > NOTE: This will only work with new AOS 2 processes not with upgraded processes. With `.receive` you can yield code execution, until a message is returned. The receive function takes an optional target? argument. ## \* Sending Messages .onReply() `.onReply` is a function returned from a message function call, that enables developers to provide a callback function. This is an alternative strategy and can be useful if you have generic composable functions. ```lua Handlers.once( { Test = "1" }, function(m) print("Got message! Replying...") m.reply({ Test = "1-reply", Status = "Success" }) end ) ``` ```lua function printMsg(prop) return function (m) print(m[prop]) end end Send({ Target = target, Test = "1" }).onReply(printMsg('Test')) ``` ## msg.forward(target, fwdMsg) REQUEST/RESPONSE is cool, but what about if I want to receive a message from C when I send a message to B and B sends a message to C. In this scenario or any other multi-forwarding scenario, we have a `msg.forward` function. The forward function takes a target and a partial message to overwrite any of the message you want to forward. example: this example requires three processes: lastname process ```sh aos lastname ``` ```lua= .editor Handlers.add("Greeting", "Greeting", function (msg) msg.forward(msg['X-Origin'], { Data = msg.Data .. " Squarepants"}) end) .done ``` greeting process ```sh aos greeting ``` ```lua= .editor local lastname = "your lastname process id above" Handlers.add("Greeting", "Greeting", function (msg) msg.forward(lastname, { Data = "Hello " .. msg.Data }) end) .done ``` client process ```sh aos spongebob ``` ```lua= .editor local Greeting = "your greeting process id" local res = Send({Target = Greeting, Action = "Greeting", Data = "SpongeBob"}).receive("your lastname process id above") print(res.Data) .done ``` > The receive function can take a `target` process id to handle the target that will return the message. The `forward` and `receive` methods can be used to create `A -> B -> C -> A` message passing scenarios. ## Message object enhancements: `.reply(newMsg)` and `.forward(target, newMsg)` All messages received by handlers now have .reply() and .forward() functions which allow the process to easily return a response to the user without having to manually deal with the X-Reference and Target values. This mechanism also allows the developer to easily build pipelines that process a request through many processes, then eventually return to the user. The reply method takes a partial message table. The forward function takes a target property and a partial message table. ## Pattern Matchers and Resolvers The Handler functions takes four arguments, | Name | Type | Description | | ---- | ---- | ----------- | | name | string | Handler Unique Identifier | | pattern | string \| table \| function | the pattern lets the process pipeline know if it should invoke and break, or skip, or invoke and continue. | | handle | function | a function that processes the message | | MaxRuns | number? (optional) | the number of max runs before the handler is removed automatically. Only available using `Handlers.add()`. ### Pattern Matching More expressive and easy to use matches. As well as functions, handlers now supports: * Strings as match, checking against the Action tag. * 'MessageMatchSpecs': Partially described messages. In this mode, each tag given in the 'spec' is checked against the value in the message. It allows you to: * Wildcard (`_`): Is the tag given at all? * Function: Run a function against the tag value (optional second argument is the full message) * String: Exact match * String: Lua matching syntax ```lua Handlers.add("token.transfer", { Action = "Transfer" Quantity = "%d+", Recipient = "_" }, doTransfer) ``` ### Resolvers Resolvers are tables in which each key is a pattern matching table and the value is a function that is executed based on the matching key. This allows developers to create case like statements in the resolver property. ```lua Handlers.add("foobarbaz", { Action = "Update" }, { [{ Status = "foo" }] = function (msg) print("foo") end, [{ Status = "bar" }] = function (msg) print("bar") end, [{ Status = "baz" }] = function (msg) print("baz") end }) ``` In this example, if a message with an Action of `Update` and the resolver looks at the `Status` tag on the message and executes the function based on the matching Status Value. ## Using Receive with Spawn > NOTE: This will only work with new AOS 2 processes not with upgraded processes. When you spawn a message you get back a success message with an action of Spawned. ```lua= .editor Spawn(ao.env.Module.Id, { }) local m = Receive({ Action = "Spawned" }) print(m['Process']) .done ``` Or if you want to get Spawned by reference using .receive > NOTE: This will only work with new AOS 2 processes not with upgraded processes. ```lua= .editor local msg = Spawn(ao.env.Module.Id, {}).receive() print(msg.Process) .done ``` # Updates ## Assignment Checks With this update, it is important to update all AOS processes to add Assignment Check Handler, this handler will be prepended to your process and add whitelisted assignment protection for all of your processes. Just run `.update` on AOS Client Version 2.0.0 ```lua Handlers.prepend("Assignment-Check", function (msg) return ao.isAssignment(msg) and not ao.isAssignable(msg) end, function (msg) Send({Target = msg.From, Data = "Assignment is not trusted by this process!"}) print('Assignment is not trusted! From: ' .. msg.From .. ' - Owner: ' .. msg.Owner) end) ``` ## \* os.time `os.time` will now return the timestamp provided by the Message Assignment in the Scheduling Unit (SU). ## CLI Updates External editor as a scratch pad ``` .pad ``` Toggle dryrun mode ``` .dryrun ``` Short cut for launching a sqlite module ```sh aos [name] --sqlite ``` Creates a new SQLite aos process ## now you can [.delete] the previous line in the built in editor ```lua .editor local x = 1 print(x) .delete ``` The .delete command deletes the previous line and allows you to continue to edit. ## PRs * Improved processid identification - https://github.com/permaweb/aos/pull/301 * update: assignable package installer - https://github.com/permaweb/aos/pull/302 ## Appendix "*" - These features tagged with an "\*" are only available on new processes that were spawned with AOS Client Version 1.12.1 and AOS version 0.2.2. ## Summary AOS 2 is a huge shift in DX, we are releasing as a Release Candidate to get feedback and refine the functionality and correct any bugs before we fully launch to general availability.