pico-engine 1.9.4 → 1.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -0
  2. package/demos/bootstrap/README.md +12 -0
  3. package/demos/bootstrap/com.example.visitors.bootstrap.krl +97 -0
  4. package/demos/bootstrap/com.example.visitors.format.krl +25 -0
  5. package/demos/bootstrap/com.example.visitors.krl +228 -0
  6. package/demos/bootstrap/try-it.md +5 -0
  7. package/demos/child_tasks/README.md +12 -0
  8. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +85 -0
  9. package/demos/child_tasks/com.example.task_runner.krl +139 -0
  10. package/demos/child_tasks/com.example.task_worker.krl +45 -0
  11. package/demos/child_tasks/try-it.md +5 -0
  12. package/demos/collection/README.md +13 -0
  13. package/demos/collection/com.example.collection.bootstrap.krl +148 -0
  14. package/demos/collection/com.example.collection.krl +95 -0
  15. package/demos/collection/com.example.collection.report.krl +93 -0
  16. package/demos/collection/com.example.collection.room.krl +101 -0
  17. package/demos/collection/try-it.md +6 -0
  18. package/demos/echo/README.md +11 -0
  19. package/demos/echo/com.example.echo.bootstrap.krl +81 -0
  20. package/demos/echo/com.example.echo.krl +73 -0
  21. package/demos/echo/try-it.md +5 -0
  22. package/demos/guard_rules/README.md +12 -0
  23. package/demos/guard_rules/com.example.archive.bootstrap.krl +95 -0
  24. package/demos/guard_rules/com.example.archive.krl +213 -0
  25. package/demos/guard_rules/com.example.archive_store.krl +36 -0
  26. package/demos/guard_rules/try-it.md +5 -0
  27. package/demos/kblog/README.md +14 -0
  28. package/demos/kblog/com.example.kblog.bootstrap.krl +132 -0
  29. package/demos/kblog/com.example.kblog.config.krl +50 -0
  30. package/demos/kblog/com.example.kblog.data.krl +75 -0
  31. package/demos/kblog/com.example.kblog.krl +184 -0
  32. package/demos/kblog/com.example.kblog.posting.krl +109 -0
  33. package/demos/kblog/try-it.md +6 -0
  34. package/demos/layered_rulesets/README.md +13 -0
  35. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +84 -0
  36. package/demos/layered_rulesets/com.example.invitations.krl +164 -0
  37. package/demos/layered_rulesets/com.example.invitations.short_links.krl +45 -0
  38. package/demos/layered_rulesets/com.example.invitations.welcome.krl +39 -0
  39. package/demos/layered_rulesets/try-it.md +5 -0
  40. package/demos/moving_picos/README.md +15 -0
  41. package/demos/moving_picos/io.picolabs.club_gear_demo.krl +650 -0
  42. package/demos/moving_picos/io.picolabs.ride_coordinator_demo.krl +331 -0
  43. package/demos/score_tracker/README.md +11 -0
  44. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +104 -0
  45. package/demos/score_tracker/com.example.score_tracker.krl +162 -0
  46. package/demos/score_tracker/try-it.md +5 -0
  47. package/demos/secrets/README.md +12 -0
  48. package/demos/secrets/com.example.hook_service.krl +120 -0
  49. package/demos/secrets/com.example.notifier.bootstrap.krl +127 -0
  50. package/demos/secrets/com.example.notifier.krl +138 -0
  51. package/demos/secrets/try-it.md +5 -0
  52. package/demos/try-it-order.json +1 -0
  53. package/demos/two_picos/README.md +12 -0
  54. package/demos/two_picos/com.example.two_picos.answerer.krl +125 -0
  55. package/demos/two_picos/com.example.two_picos.asker.krl +124 -0
  56. package/demos/two_picos/com.example.two_picos.bootstrap.krl +131 -0
  57. package/demos/two_picos/try-it.md +5 -0
  58. package/demos/xmlui/README.md +17 -0
  59. package/demos/xmlui/com.example.contacts.krl +132 -0
  60. package/demos/xmlui/com.example.fav_color.krl +39 -0
  61. package/demos/xmlui/com.example.guestbook.krl +61 -0
  62. package/demos/xmlui/com.example.hello.krl +19 -0
  63. package/demos/xmlui/com.example.temperature_sensors_view.krl +105 -0
  64. package/demos/xmlui/com.example.thermostat.bootstrap.krl +92 -0
  65. package/demos/xmlui/com.example.thermostat.krl +124 -0
  66. package/demos/xmlui/temperature_sensors.krl +56 -0
  67. package/demos/xmlui/try-it.md +5 -0
  68. package/dist/bundledKrl.js +97 -12
  69. package/dist/cli.js +2 -0
  70. package/dist/engineConfig.js +19 -0
  71. package/dist/index.js +1 -0
  72. package/dist/server.js +14 -0
  73. package/krl/io.picolabs.xmlui.krl +3 -2
  74. package/mcp/docs/CLAUDE.md +3 -2
  75. package/mcp/docs/pico-engine.md +3 -0
  76. package/package.json +6 -3
  77. package/public/.DS_Store +0 -0
  78. package/public/pico-engine-ui.css +1 -1
  79. package/public/pico-engine-ui.js +23 -22
  80. package/src/bundledKrl.ts +118 -12
  81. package/src/cli.ts +2 -0
  82. package/src/engineConfig.ts +28 -0
  83. package/src/index.ts +8 -0
  84. package/src/server.ts +15 -0
package/README.md CHANGED
@@ -135,6 +135,8 @@ The server is configured via some environment variables.
135
135
  - `PICO_ENGINE_ALLOW_LOCALHOST_C` - Set to `"0"` to require passkey session on `/c/*` even from localhost (default: allow localhost without session for in-engine HTTP loops). Full registry: repo `MEMORY.md` § Engine environment variables.
136
136
  - `PICO_ENGINE_LOG_FILE` - Log file path. Set to `stdout`, `-`, or `0` for **stdout only** (recommended on Fargate + EFS; use CloudWatch for retention). Default: `$PICO_ENGINE_HOME/pico-engine.log`.
137
137
  - `PICO_ENGINE_LOG_MIRROR` - When stdout-only: **`true`/`1`** (default) mirrors structured JSON to **`$PICO_ENGINE_HOME/pico-engine.log`** so **`ctx:logs`** and the Developer UI **Logging** tab work; set **`false`/`0`** to skip the mirror file (e.g. avoid EFS log churn). **Config:** `logMirror` in `config.json` (see `config.example.json`).
138
+ - `PICO_ENGINE_SHOW_TRYIT_MENU` - Where the Developer UI shows the **Try It!** tab: `off`, `root_only` (default), or `all` (config: `show_tryit_menu`).
139
+ - `PICO_ENGINE_DEMOS_DIR` - A directory to serve as `demos/` instead of the copy shipped with the engine, such as the `demos/` folder of a pico-engine checkout you're editing.
138
140
 
139
141
  The `PORT` is the only value used in setting up the engine’s [nodejs http server](https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback). We only specify the `port` so it listens listens to all traffic on that port, it will not filter by host.
140
142
 
@@ -0,0 +1,12 @@
1
+ # Bootstrap and channels demo
2
+
3
+ A bootstrap ruleset installs a small app in dependency order and configures it, and the app creates its own channel on install, with a policy built from its schema.
4
+
5
+ - Overview: [`docs/cookbook/bootstrap/README.md`](../../docs/cookbook/bootstrap/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/bootstrap/)
6
+ - Instructions: [`docs/cookbook/bootstrap/instructions.md`](../../docs/cookbook/bootstrap/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.visitors.bootstrap.krl` | The bootstrap: installs each ruleset when the one it needs is installed, and gives the app its install configuration |
11
+ | `com.example.visitors.format.krl` | A module the app uses, so it is installed first |
12
+ | `com.example.visitors.krl` | The app: reads its configuration, and creates or updates its channel on install. Its page shows the pico's rulesets and channels |
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Try It! bootstrap for the Bootstrap and channels demo. Install it on a new
3
+ * pico. It installs io.picolabs.xmlui, then com.example.visitors.format, then
4
+ * com.example.visitors with a greeting in its install configuration. Each step
5
+ * waits for the ruleset_installed event of the one before, because each needs
6
+ * the one before. The visitor log creates its own channel when it is
7
+ * installed. tryIt() reports progress and links to the visitor log.
8
+ *
9
+ * This ruleset does not use io.picolabs.xmlui as a module, because it is the
10
+ * one that installs it.
11
+ */
12
+ ruleset com.example.visitors.bootstrap {
13
+ meta {
14
+ name "Bootstrap and channels"
15
+ description "Shows a bootstrap ruleset installing an app in dependency order and configuring it, and an app ruleset that creates its own channel on install, with a policy built from its schema, updated in place instead of duplicated."
16
+ author "PICOLABS"
17
+
18
+ use module io.picolabs.wrangler alias wrangler
19
+
20
+ shares tryIt
21
+ }
22
+
23
+ global {
24
+ xmlui_rid = "io.picolabs.xmlui"
25
+ format_rid = "com.example.visitors.format"
26
+ app_rid = "com.example.visitors"
27
+
28
+ host = function() {
29
+ meta:host.defaultsTo("").replace(re#/$#, "")
30
+ }
31
+
32
+ /**
33
+ * Progress of this demo's setup, and the links to open when it is ready.
34
+ * @returns Map
35
+ */
36
+ tryIt = function() {
37
+ app = wrangler:channels(["visitors", "app"]).head()
38
+ ready = (ent:stage == "ready" && app) => true | false
39
+ status = {
40
+ "ready": ready,
41
+ "stage": ent:stage.defaultsTo("starting"),
42
+ "links": ready => [
43
+ {"label": "Visitor log", "url": host() + "/ui/" + app{"id"} + "/" + app_rid + "/"}
44
+ ] | []
45
+ }
46
+ status
47
+ }
48
+ }
49
+
50
+ // Step 1: a channel for tryIt(), and the views runtime (unless it's here).
51
+ rule start {
52
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
53
+ pre {
54
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
55
+ }
56
+ always {
57
+ ent:stage := "installing " + xmlui_rid
58
+ raise wrangler event "new_channel_request" attributes {
59
+ "tags": ["try_it"],
60
+ "eventPolicy": {"allow": [], "deny": []},
61
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
62
+ }
63
+ raise wrangler event "install_ruleset_request" attributes
64
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
65
+ if not has_xmlui
66
+ raise bootstrap event "xmlui_ready" if has_xmlui
67
+ }
68
+ }
69
+
70
+ // Step 2: the module the app uses.
71
+ rule install_format {
72
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
73
+ or bootstrap xmlui_ready
74
+ always {
75
+ ent:stage := "installing " + format_rid
76
+ raise wrangler event "install_ruleset_request" attributes
77
+ {"absoluteURL": meta:rulesetURI, "rid": format_rid}
78
+ }
79
+ }
80
+
81
+ // Step 3: the app, configured. Its own install rule creates its channel.
82
+ rule install_app {
83
+ select when wrangler ruleset_installed where event:attr("rids") >< format_rid
84
+ always {
85
+ ent:stage := "installing " + app_rid
86
+ raise wrangler event "install_ruleset_request" attributes
87
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid, "config": {"greeting": "Welcome"}}
88
+ }
89
+ }
90
+
91
+ rule app_installed {
92
+ select when wrangler ruleset_installed where event:attr("rids") >< app_rid
93
+ always {
94
+ ent:stage := "ready"
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Visitor log formatting: a module the visitor log uses, so it has to be
3
+ * installed first.
4
+ */
5
+ ruleset com.example.visitors.format {
6
+ meta {
7
+ name "Visitor log formatting"
8
+ description "Formats greetings for the visitor log."
9
+ author "PICOLABS"
10
+
11
+ provides greeting
12
+ }
13
+
14
+ global {
15
+ /**
16
+ * A greeting for a visitor.
17
+ * @param word String "the greeting word, such as Welcome"
18
+ * @param name String "the visitor's name"
19
+ * @returns String
20
+ */
21
+ greeting = function(word, name) {
22
+ word + ", " + name + "!"
23
+ }
24
+ }
25
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Visitor log: signs visitors in and greets them. Its greeting word comes from
3
+ * the configuration it was installed with, and it uses
4
+ * com.example.visitors.format as a module.
5
+ *
6
+ * On install it creates its own channel, with a policy built from this
7
+ * ruleset's schema: every event its documented rules select (except
8
+ * wrangler's) and every function it shares and documents. The schema is the
9
+ * ruleset's documented API, so undocumented rules stay off the channel. If the channel already exists, the same rule updates it
10
+ * in place, so the channel id, and every link that uses it, stays the same.
11
+ * Flushing doesn't run install rules again, so the page has a button that does.
12
+ */
13
+ ruleset com.example.visitors {
14
+ meta {
15
+ name "Visitor log"
16
+ description "Signs visitors in and greets them; creates its own channel on install."
17
+ author "PICOLABS"
18
+
19
+ use module com.example.visitors.format alias format
20
+ use module io.picolabs.wrangler alias wrangler
21
+ use module io.picolabs.xmlui alias ui
22
+
23
+ shares visitors, setup, visitorsPage
24
+ }
25
+
26
+ global {
27
+ channel_tags = ["visitors", "app"]
28
+ xmlui_rid = "io.picolabs.xmlui"
29
+
30
+ greetingWord = function() {
31
+ meta:rulesetConfig{"greeting"} || "Hello"
32
+ }
33
+
34
+ schema = function(rid) {
35
+ wrangler:rulesetSchema(rid).defaultsTo({})
36
+ }
37
+
38
+ unique = function(list) {
39
+ list.reduce(function(acc, item) { acc >< item => acc | acc.append([item]) }, [])
40
+ }
41
+
42
+ // Every event a documented rule selects, except wrangler's. The schema has
43
+ // only rules and functions with doc comments.
44
+ eventPolicy = function() {
45
+ allow = schema(meta:rid){"operations"}.defaultsTo([])
46
+ .map(function(op) { op{"entry"}.defaultsTo([]) })
47
+ .reduce(function(a, b) { a.append(b) }, [])
48
+ .filter(function(e) { e{"domain"} && e{"domain"} != "wrangler" })
49
+ .map(function(e) { {"domain": e{"domain"}, "name": e{"name"} || "*"} })
50
+ policy = {"allow": unique(allow), "deny": []}
51
+ policy
52
+ }
53
+
54
+ // Every function this ruleset shares, and what the page shell needs.
55
+ queryPolicy = function() {
56
+ mine = schema(meta:rid){"queries"}.defaultsTo([])
57
+ .map(function(q) { {"rid": meta:rid, "name": q{"name"}} })
58
+ shell = schema(xmlui_rid){"queries"}.defaultsTo([])
59
+ .filter(function(q) { not q{"component"}.isnull() })
60
+ .map(function(q) { {"rid": xmlui_rid, "name": q{"name"}} })
61
+ .append([{"rid": xmlui_rid, "name": "file"}])
62
+ policy = {"allow": mine.append(shell), "deny": []}
63
+ policy
64
+ }
65
+
66
+ /**
67
+ * Everyone signed in, oldest first.
68
+ * @returns Array of { name, message, time }
69
+ */
70
+ visitors = function() {
71
+ ent:visitors.defaultsTo([])
72
+ }
73
+
74
+ /**
75
+ * How this pico was set up: its rulesets, this ruleset's install
76
+ * configuration, and the channels tagged visitors, app.
77
+ * @returns Map
78
+ */
79
+ setup = function() {
80
+ channels = wrangler:channels(channel_tags).map(function(c) {
81
+ {
82
+ "id": c{"id"},
83
+ "events": c{["eventPolicy", "allow"]}.defaultsTo([])
84
+ .map(function(r) { r{"domain"} + ":" + r{"name"} }).join(", "),
85
+ "queries": c{["queryPolicy", "allow"]}.defaultsTo([]).length(),
86
+ "this_page": c{"id"} == meta:eci => "yes" | ""
87
+ }
88
+ })
89
+ result = {
90
+ "rulesets": wrangler:installedRIDs().map(function(rid) { {"rid": rid} }),
91
+ "config": meta:rulesetConfig.encode(),
92
+ "channels": channels
93
+ }
94
+ result
95
+ }
96
+
97
+ /**
98
+ * Sign in, and see how the bootstrap set this pico up.
99
+ * @view "Visitor log"
100
+ */
101
+ visitorsPage = function() {
102
+ setup_url = ui:query_url("setup", meta:rid, meta:eci)
103
+ visitors_url = ui:query_url("visitors", meta:rid, meta:eci)
104
+ arrived_url = ui:event_url("visitor", "arrived")
105
+ check_url = ui:event_url("visitor_channel", "check_requested")
106
+ duplicate_url = ui:event_url("visitor_channel", "duplicate_requested")
107
+ cleanup_url = ui:event_url("visitor_channel", "cleanup_requested")
108
+ <<
109
+ <Component name="VisitorsPage" var.said="">
110
+ <DataSource id="setup" url="#{setup_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
111
+ <DataSource id="visitors" url="#{visitors_url}" headers="{appGlobals.auth}" />
112
+ <APICall id="arrive" method="post" url="#{arrived_url}" headers="{appGlobals.auth}" body="{$param}"
113
+ onSuccess="(result) => { said = result.directives.length ? result.directives[0].options.message : ''; visitors.refetch(); }" />
114
+ <APICall id="check" method="post" url="#{check_url}" headers="{appGlobals.auth}"
115
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', '); setup.refetch(); }" />
116
+ <APICall id="duplicate" method="post" url="#{duplicate_url}" headers="{appGlobals.auth}"
117
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', '); setup.refetch(); }" />
118
+ <APICall id="cleanup" method="post" url="#{cleanup_url}" headers="{appGlobals.auth}"
119
+ onSuccess="(result) => { said = result.directives.map((d) => d.name).join(', ') || 'nothing to clean up'; setup.refetch(); }" />
120
+ <PicoTheme>
121
+ <Card title="Visitor log"
122
+ subtitle="A bootstrap ruleset installed this app: a formatting module first, then this ruleset with a greeting in its install configuration. On install, this ruleset made the channel this page uses." />
123
+ <Form saveLabel="Sign in" onSubmit="(data) => arrive.execute(data)">
124
+ <FormItem bindTo="name" label="Your name" initialValue="Ada" />
125
+ </Form>
126
+ <Card title="The pico said" subtitle="{said || '(nothing yet)'}" />
127
+ <Table data="{visitors}">
128
+ <Column bindTo="name" header="Visitor" />
129
+ <Column bindTo="message" header="Greeted with" />
130
+ </Table>
131
+
132
+ <Card title="How the bootstrap set up this pico"
133
+ subtitle="{'This ruleset was installed with the configuration ' + setup.value.config}" />
134
+ <Table data="{setup.value.rulesets}">
135
+ <Column bindTo="rid" header="Installed rulesets, in order" />
136
+ </Table>
137
+
138
+ <Card title="This app's channel"
139
+ subtitle="Its policy was built from this ruleset's schema when the ruleset was installed. Try the buttons and watch the table." />
140
+ <Table data="{setup.value.channels}">
141
+ <Column bindTo="id" header="Channel" />
142
+ <Column bindTo="events" header="Events it allows" />
143
+ <Column bindTo="queries" header="Queries" />
144
+ <Column bindTo="this_page" header="This page" />
145
+ </Table>
146
+ <HStack wrapContent="true">
147
+ <Button label="Run the channel rule again" onClick="check.execute({})" />
148
+ <Button label="Make a duplicate, the naive way" variant="outlined" onClick="duplicate.execute({})" />
149
+ <Button label="Clean up duplicates" variant="outlined" onClick="cleanup.execute({})" />
150
+ </HStack>
151
+ </PicoTheme>
152
+ </Component>
153
+ >>
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Sign a visitor in and greet them.
159
+ * @attr name String "the visitor's name"
160
+ * @example "Ada" { "name": "Ada" }
161
+ */
162
+ rule greet_visitor {
163
+ select when visitor arrived
164
+ name re#(\S.*)#
165
+ setting(name)
166
+ pre {
167
+ message = format:greeting(greetingWord(), name)
168
+ }
169
+ send_directive("greeting", {"message": message})
170
+ fired {
171
+ ent:visitors := visitors().append({"name": name, "message": message, "time": time:now()})
172
+ raise visitor event "greeted" attributes {"name": name}
173
+ }
174
+ }
175
+
176
+ /**
177
+ * On install, or when asked: update this app's channel if it exists, so its
178
+ * id stays the same. Otherwise raise visitor_setup:channel_missing.
179
+ */
180
+ rule set_up_channel {
181
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
182
+ or visitor_channel check_requested
183
+ pre {
184
+ existing = wrangler:channels(channel_tags).head()
185
+ }
186
+ if existing then every {
187
+ wrangler:updateChannel(existing{"id"}, channel_tags, eventPolicy(), queryPolicy())
188
+ send_directive("set_up_channel", {"result": "updated", "id": existing{"id"}})
189
+ }
190
+ notfired {
191
+ raise visitor_setup event "channel_missing"
192
+ }
193
+ }
194
+
195
+ // No doc comment, so it isn't in the schema, and the channel doesn't allow
196
+ // its event: only set_up_channel raises it.
197
+ rule create_channel {
198
+ select when visitor_setup channel_missing
199
+ every {
200
+ wrangler:createChannel(channel_tags, eventPolicy(), queryPolicy())
201
+ send_directive("create_channel")
202
+ }
203
+ }
204
+
205
+ /**
206
+ * The naive way: create a channel every time, whether or not one exists.
207
+ */
208
+ rule make_duplicate {
209
+ select when visitor_channel duplicate_requested
210
+ every {
211
+ wrangler:createChannel(channel_tags, eventPolicy(), queryPolicy())
212
+ send_directive("make_duplicate")
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Delete every channel tagged visitors, app except the one this request came
218
+ * in on, which is the one the page is using.
219
+ */
220
+ rule clean_up_channels {
221
+ select when visitor_channel cleanup_requested
222
+ foreach wrangler:channels(channel_tags).filter(function(c) { c{"id"} != meta:eci }) setting(channel)
223
+ every {
224
+ wrangler:deleteChannel(channel{"id"})
225
+ send_directive("clean_up_channels", {"deleted": channel{"id"}})
226
+ }
227
+ }
228
+ }
@@ -0,0 +1,5 @@
1
+ - Open **Visitor log** and sign in. The greeting word, "Welcome", came from the configuration the bootstrap installed the app with.
2
+ - Under **How the bootstrap set up this pico**, the installed rulesets are in install order: the bootstrap, then `io.picolabs.xmlui`, then `com.example.visitors.format` (a module), then `com.example.visitors`, which uses it. Open the child pico's **Logging** tab to follow the chain of `wrangler:ruleset_installed` events that drove each step.
3
+ - Under **This app's channel**, the policy lists the events of the app's documented rules. It doesn't list `wrangler:ruleset_installed`, which its install rule selects, or the event only `set_up_channel` raises.
4
+ - Click **Run the channel rule again**: the same channel is updated, and its id doesn't change. Click **Make a duplicate, the naive way** twice: three channels with the same tags. Click **Clean up duplicates**: only the channel this page uses is left.
5
+ - Add a documented rule to `com.example.visitors.krl` that selects `visitor waved`, and click **Flush**. Sending `visitor/waved` on the page's channel is refused: flushing doesn't run install rules again. Click **Run the channel rule again** and send it again. Now it works.
@@ -0,0 +1,12 @@
1
+ # Child pico tasks demo
2
+
3
+ A pico that never waits: each task runs in a new child pico, which reports back to its parent and then deletes itself.
4
+
5
+ - Overview: [`docs/cookbook/child_tasks/README.md`](../../docs/cookbook/child_tasks/README.md) (on the docs site: https://docs.picolabs.io/#/cookbook/child_tasks/)
6
+ - Instructions: [`docs/cookbook/child_tasks/instructions.md`](../../docs/cookbook/child_tasks/instructions.md)
7
+
8
+ | File | Shows |
9
+ |------|-------|
10
+ | `com.example.task_runner.krl` | The parent: creates a child per task, hands it the task, records the result, and notes when the child is gone. Has the Tasks page |
11
+ | `com.example.task_worker.krl` | The child: counts primes up to `n`, sends `task:done` to its parent, and asks to be deleted |
12
+ | `com.example.task_runner.bootstrap.krl` | Sets up the demo on a new pico and starts three tasks; the **Try It!** tab runs it |
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Try It! bootstrap for the child tasks demo. Install it on a new pico: it
3
+ * installs io.picolabs.xmlui and com.example.task_runner, then starts three
4
+ * tasks of different sizes. tryIt() reports progress and links to the Tasks
5
+ * page.
6
+ *
7
+ * This ruleset does not use io.picolabs.xmlui as a module, because it is the
8
+ * one that installs it.
9
+ */
10
+ ruleset com.example.task_runner.bootstrap {
11
+ meta {
12
+ name "Child pico tasks"
13
+ description "Shows the child pico lifecycle: creating a child with extra attributes, installing a ruleset on it, reporting to the parent, and deleting itself, so the parent never waits."
14
+ author "PICOLABS"
15
+
16
+ use module io.picolabs.wrangler alias wrangler
17
+
18
+ shares tryIt
19
+ }
20
+
21
+ global {
22
+ app_rid = "com.example.task_runner"
23
+ xmlui_rid = "io.picolabs.xmlui"
24
+ seed_tasks = ["1000", "10000", "30000"]
25
+
26
+ host = function() {
27
+ meta:host.defaultsTo("").replace(re#/$#, "")
28
+ }
29
+
30
+ /**
31
+ * Progress of this demo's setup, and the links to open when it is ready.
32
+ * @returns Map
33
+ */
34
+ tryIt = function() {
35
+ app = wrangler:channels(["task_runner", "app"]).head()
36
+ ready = (ent:stage == "ready" && app) => true | false
37
+ status = {
38
+ "ready": ready,
39
+ "stage": ent:stage.defaultsTo("starting"),
40
+ "links": ready => [
41
+ {"label": "Tasks", "url": host() + "/ui/" + app{"id"} + "/" + app_rid + "/"}
42
+ ] | []
43
+ }
44
+ status
45
+ }
46
+ }
47
+
48
+ rule start {
49
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
50
+ pre {
51
+ has_xmlui = wrangler:installedRIDs() >< xmlui_rid
52
+ }
53
+ always {
54
+ ent:stage := "installing"
55
+ raise wrangler event "new_channel_request" attributes {
56
+ "tags": ["try_it"],
57
+ "eventPolicy": {"allow": [], "deny": []},
58
+ "queryPolicy": {"allow": [{"rid": meta:rid, "name": "tryIt"}], "deny": []}
59
+ }
60
+ raise wrangler event "install_ruleset_request" attributes
61
+ {"url": host() + "/krl/" + xmlui_rid + ".krl"}
62
+ if not has_xmlui
63
+ raise wrangler event "install_ruleset_request" attributes
64
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
65
+ if has_xmlui
66
+ }
67
+ }
68
+
69
+ rule install_app {
70
+ select when wrangler ruleset_installed where event:attr("rids") >< xmlui_rid
71
+ always {
72
+ raise wrangler event "install_ruleset_request" attributes
73
+ {"absoluteURL": meta:rulesetURI, "rid": app_rid}
74
+ }
75
+ }
76
+
77
+ rule start_tasks {
78
+ select when wrangler ruleset_installed where event:attr("rids") >< app_rid
79
+ foreach seed_tasks setting(n)
80
+ always {
81
+ raise task event "start" attributes {"n": n}
82
+ ent:stage := "ready" on final
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Task runner: hands each task to a new child pico, so this pico never waits.
3
+ * task:start creates a child and installs com.example.task_worker on it with
4
+ * the task. The worker does the work, sends task:done back, and asks wrangler to
5
+ * delete it. This pico records the result and notes when the child is gone.
6
+ */
7
+ ruleset com.example.task_runner {
8
+ meta {
9
+ name "Task runner"
10
+ description "Runs each task in its own child pico, which reports back and deletes itself."
11
+ author "PICOLABS"
12
+
13
+ use module io.picolabs.wrangler alias wrangler
14
+ use module io.picolabs.xmlui alias ui
15
+
16
+ shares tasks, tasksPage
17
+ }
18
+
19
+ global {
20
+ channel_tags = ["task_runner", "app"]
21
+ worker_rid = "com.example.task_worker"
22
+
23
+ /**
24
+ * Every task, newest first.
25
+ * @returns Array of { id, n, status, primes, worker, started, finished }
26
+ */
27
+ tasks = function() {
28
+ ent:tasks.defaultsTo({}).values()
29
+ .sort(function(a, b) { b{"id"} <=> a{"id"} })
30
+ }
31
+
32
+ /**
33
+ * Start tasks and watch child picos do them.
34
+ * @view "Tasks"
35
+ */
36
+ tasksPage = function() {
37
+ tasks_url = ui:query_url("tasks", meta:rid, meta:eci)
38
+ start_url = ui:event_url("task", "start")
39
+ <<
40
+ <Component name="TasksPage">
41
+ <DataSource id="list" url="#{tasks_url}" headers="{appGlobals.auth}" pollIntervalInSeconds="2" />
42
+ <APICall id="start" method="post" url="#{start_url}" headers="{appGlobals.auth}" body="{$param}"
43
+ onSuccess="list.refetch()" />
44
+ <PicoTheme>
45
+ <Card title="Tasks"
46
+ subtitle="Each task counts the primes up to n in its own child pico. Watch the children appear in the developer UI and go away when they finish." />
47
+ <Form saveLabel="Start a task" onSubmit="(data) => start.execute(data)">
48
+ <FormItem bindTo="n" label="Count primes up to" type="integer" initialValue="20000" />
49
+ </Form>
50
+ <Table data="{list}">
51
+ <Column bindTo="id" header="Task" />
52
+ <Column bindTo="n" header="n" />
53
+ <Column bindTo="status" header="Status" />
54
+ <Column bindTo="primes" header="Primes" />
55
+ <Column bindTo="worker" header="Worker pico" />
56
+ </Table>
57
+ </PicoTheme>
58
+ </Component>
59
+ >>
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Start a task: count the primes up to n in a new child pico.
65
+ * @attr n Number "count primes up to this number"
66
+ * @example "twenty thousand" { "n": "20000" }
67
+ */
68
+ rule start_task {
69
+ select when task start
70
+ n re#^(\d+)$#
71
+ setting(n)
72
+ pre {
73
+ id = ent:next_id.defaultsTo(1)
74
+ key = id.as("String")
75
+ }
76
+ always {
77
+ ent:next_id := id + 1
78
+ ent:tasks{key} := {"id": id, "n": n.as("Number"), "status": "starting", "started": time:now()}
79
+ raise wrangler event "new_child_request" attributes
80
+ {"name": "Task " + key, "task_id": key, "n": n}
81
+ }
82
+ }
83
+
84
+ // The child is set up; give it the worker ruleset and the task.
85
+ rule hand_off_task {
86
+ select when wrangler child_initialized where event:attr("task_id")
87
+ pre {
88
+ key = event:attr("task_id")
89
+ child = event:attr("eci")
90
+ }
91
+ event:send({
92
+ "eci": child,
93
+ "domain": "wrangler",
94
+ "type": "install_ruleset_request",
95
+ "attrs": {
96
+ "absoluteURL": meta:rulesetURI,
97
+ "rid": worker_rid,
98
+ "task_id": key,
99
+ "n": event:attr("n")
100
+ }
101
+ })
102
+ always {
103
+ ent:tasks{[key, "status"]} := "working"
104
+ ent:tasks{[key, "worker"]} := event:attr("name")
105
+ ent:tasks{[key, "worker_eci"]} := child
106
+ }
107
+ }
108
+
109
+ /**
110
+ * A worker finished.
111
+ * @attr task_id String "the task"
112
+ * @attr primes Number "how many primes it found"
113
+ */
114
+ rule task_done {
115
+ select when task done
116
+ task_id re#(.+)#
117
+ setting(key)
118
+ always {
119
+ ent:tasks{[key, "status"]} := "done"
120
+ ent:tasks{[key, "primes"]} := event:attr("primes")
121
+ ent:tasks{[key, "finished"]} := time:now()
122
+ }
123
+ }
124
+
125
+ // Wrangler deleted a worker that asked to be deleted.
126
+ rule worker_deleted {
127
+ select when wrangler child_deleted
128
+ foreach ent:tasks.defaultsTo({}).values() setting(task)
129
+ if task{"worker_eci"} == event:attr("eci") then noop()
130
+ fired {
131
+ ent:tasks{[task{"id"}.as("String"), "worker"]} := task{"worker"} + " (deleted)"
132
+ }
133
+ }
134
+
135
+ rule create_app_channel {
136
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
137
+ ui:create_app_channel(channel_tags, ["task"], ["tasks", "tasksPage"], meta:rid)
138
+ }
139
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Task worker: installed on a new child pico with a task. It counts the primes
3
+ * up to n, sends task:done to its parent, and asks wrangler to delete it. The
4
+ * parent is never blocked while the work runs here.
5
+ */
6
+ ruleset com.example.task_worker {
7
+ meta {
8
+ name "Task worker"
9
+ description "Does one task, reports to its parent, and deletes itself."
10
+ author "PICOLABS"
11
+
12
+ use module io.picolabs.wrangler alias wrangler
13
+ }
14
+
15
+ global {
16
+ // True when no number from d up to the square root of k divides k.
17
+ noDivisorFrom = function(k, d) {
18
+ d * d > k => true |
19
+ k % d == 0 => false |
20
+ noDivisorFrom(k, d + 1)
21
+ }
22
+
23
+ countPrimes = function(n) {
24
+ n < 2 => 0 |
25
+ 2.range(n).filter(function(k) { noDivisorFrom(k, 2) }).length()
26
+ }
27
+ }
28
+
29
+ rule do_task {
30
+ select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
31
+ pre {
32
+ n = event:attr("n").as("Number")
33
+ primes = countPrimes(n)
34
+ }
35
+ event:send({
36
+ "eci": wrangler:parent_eci(),
37
+ "domain": "task",
38
+ "type": "done",
39
+ "attrs": {"task_id": event:attr("task_id"), "n": n, "primes": primes}
40
+ })
41
+ always {
42
+ raise wrangler event "ready_for_deletion"
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,5 @@
1
+ - Open **Tasks**. The three seeded tasks are done, and each worker pico is marked "(deleted)".
2
+ - Start a task with `n` set to 200000. It takes about ten seconds. While it runs, leave the **Try It!** tab, close the pico, and look at the pico tree: the task runner has a child named after the task. It disappears when the task is done.
3
+ - Start several large tasks one after another. Each gets its own child, and the runner keeps taking new tasks while they work.
4
+ - Open the task runner's **Logging** tab and follow one task: `task:start`, then `wrangler:child_initialized` from the new child, `task:done` from the worker, and its `wrangler:child_deletion_request`. That one shows `wrangler:child_deleted` under **Raised**.
5
+ - In `com.example.task_worker.krl`, comment out the line that raises `ready_for_deletion` and click **Flush**. New workers stay around after they finish, so you can open one and look inside.