pico-engine 1.9.5 → 1.10.0
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.
- package/README.md +11 -5
- package/demos/bootstrap/com.example.visitors.bootstrap.krl +9 -5
- package/demos/child_tasks/com.example.task_runner.bootstrap.krl +10 -7
- package/demos/echo/com.example.echo.bootstrap.krl +10 -7
- package/demos/guard_rules/com.example.archive.bootstrap.krl +10 -7
- package/demos/json_query/README.md +11 -0
- package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
- package/demos/json_query/com.example.json_query.krl +162 -0
- package/demos/json_query/try-it.md +5 -0
- package/demos/kblog/com.example.kblog.bootstrap.krl +10 -7
- package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +10 -7
- package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +10 -7
- package/demos/secrets/com.example.notifier.bootstrap.krl +10 -7
- package/demos/try-it-order.json +1 -1
- package/demos/two_picos/com.example.two_picos.bootstrap.krl +5 -2
- package/demos/xmlui/com.example.thermostat.bootstrap.krl +10 -7
- package/dist/cli.js +5 -1
- package/dist/engineConfig.js +1 -1
- package/dist/identity/portableMove.js +5 -1
- package/dist/index.js +44 -12
- package/dist/internalAccess.js +110 -0
- package/dist/oauth/OAuthService.js +172 -10
- package/dist/oauth/acg.js +194 -24
- package/dist/oauth/cimd.js +381 -0
- package/dist/oauth/discovery.js +175 -0
- package/dist/runMcp.js +1 -1
- package/dist/server.js +197 -48
- package/dist/subtreeWrangler.js +8 -5
- package/dist/uiChannelPolicies.js +2 -0
- package/krl/io.picolabs.pds.krl +109 -21
- package/krl/io.picolabs.pico-engine-ui.krl +13 -7
- package/krl/io.picolabs.wrangler.krl +21 -9
- package/mcp/devResources.js +52 -0
- package/mcp/devTools.js +40 -9
- package/mcp/docs/CLAUDE.md +3 -2
- package/mcp/docs/cookbook/README.md +23 -0
- package/mcp/docs/cookbook/bootstrap/README.md +23 -0
- package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
- package/mcp/docs/cookbook/child_tasks/README.md +20 -0
- package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
- package/mcp/docs/cookbook/collection/README.md +21 -0
- package/mcp/docs/cookbook/collection/instructions.md +93 -0
- package/mcp/docs/cookbook/echo/README.md +19 -0
- package/mcp/docs/cookbook/echo/instructions.md +59 -0
- package/mcp/docs/cookbook/guard_rules/README.md +22 -0
- package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
- package/mcp/docs/cookbook/json_query/README.md +26 -0
- package/mcp/docs/cookbook/json_query/instructions.md +64 -0
- package/mcp/docs/cookbook/kblog/README.md +60 -0
- package/mcp/docs/cookbook/kblog/instructions.md +102 -0
- package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
- package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
- package/mcp/docs/cookbook/moving_picos/README.md +44 -0
- package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
- package/mcp/docs/cookbook/score_tracker/README.md +19 -0
- package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
- package/mcp/docs/cookbook/secrets/README.md +25 -0
- package/mcp/docs/cookbook/secrets/instructions.md +98 -0
- package/mcp/docs/cookbook/two_picos/README.md +20 -0
- package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
- package/mcp/docs/cookbook/xmlui/README.md +23 -0
- package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
- package/mcp/docs/developing/README.md +28 -0
- package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
- package/mcp/docs/developing/arrays-and-maps.md +77 -0
- package/mcp/docs/developing/converting-time-formats.md +28 -0
- package/mcp/docs/developing/cookies-and-redirects.md +81 -0
- package/mcp/docs/developing/decoding-form-data.md +67 -0
- package/mcp/docs/developing/engine-log-files.md +34 -0
- package/mcp/docs/developing/event-loop.md +77 -0
- package/mcp/docs/developing/events-from-email.md +80 -0
- package/mcp/docs/developing/initializing-entity-variables.md +83 -0
- package/mcp/docs/developing/mcp-ai-tools.md +98 -0
- package/mcp/docs/developing/misconceptions.md +467 -0
- package/mcp/docs/developing/names-and-scope.md +44 -0
- package/mcp/docs/developing/postman.md +159 -0
- package/mcp/docs/developing/querying-another-pico.md +47 -0
- package/mcp/docs/developing/singleton-picos.md +36 -0
- package/mcp/docs/developing/tabular-data.md +67 -0
- package/mcp/docs/developing/tips.md +251 -0
- package/mcp/docs/developing/webhook-signatures.md +56 -0
- package/mcp/docs/developing/workflow.md +106 -0
- package/mcp/docs/exp/README.md +46 -0
- package/mcp/docs/exp/event.md +110 -0
- package/mcp/docs/exp/query.md +94 -0
- package/mcp/docs/lessons/README.md +59 -0
- package/mcp/docs/lessons/events-and-queries.md +247 -0
- package/mcp/docs/lessons/gossip.md +28 -0
- package/mcp/docs/lessons/modules-and-apis.md +270 -0
- package/mcp/docs/lessons/pico-based-systems.md +470 -0
- package/mcp/docs/lessons/pico-state.md +267 -0
- package/mcp/docs/lessons/pico-views.md +290 -0
- package/mcp/docs/lessons/quickstart.md +157 -0
- package/mcp/docs/lessons/relationships.md +530 -0
- package/mcp/docs/lessons/scatter-gather.md +362 -0
- package/mcp/docs/pico-engine.md +7 -5
- package/mcp/docs/pico-overview.md +3 -3
- package/mcp/docs/wrangler/README.md +47 -0
- package/mcp/docs/wrangler/channels.md +235 -0
- package/mcp/docs/wrangler/oauth.md +56 -0
- package/mcp/docs/wrangler/pds.md +423 -0
- package/mcp/docs/wrangler/portable-subtree.md +44 -0
- package/mcp/docs/wrangler/relationships.md +297 -0
- package/mcp/docs/wrangler/wrangler.md +253 -0
- package/mcp/docs/wrangler/xmlui.md +60 -0
- package/mcp/engineClient.js +57 -5
- package/mcp/mcpScopes.js +118 -0
- package/mcp/meshHttp.js +151 -45
- package/mcp/runStdio.js +2 -0
- package/mcp/subtreeTools.js +184 -0
- package/mcp/tryItTools.js +202 -0
- package/package.json +14 -8
- package/public/pico-engine-ui.js +26 -26
- package/src/cli.ts +6 -2
- package/src/engineConfig.ts +5 -2
- package/src/identity/portableMove.ts +6 -1
- package/src/index.ts +469 -430
- package/src/internalAccess.ts +127 -0
- package/src/oauth/OAuthService.ts +243 -11
- package/src/oauth/acg.ts +289 -25
- package/src/oauth/cimd.ts +508 -0
- package/src/oauth/discovery.ts +233 -0
- package/src/runMcp.ts +3 -1
- package/src/server.ts +252 -52
- package/src/subtreeWrangler.ts +17 -5
- package/src/uiChannelPolicies.ts +2 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# Pico State
|
|
2
|
+
|
|
3
|
+
A pico that forgets everything between events isn't much use. This lesson teaches the pico to remember: you'll store a name, store many names in a map, count visits, and clear it all again.
|
|
4
|
+
|
|
5
|
+
## Objectives
|
|
6
|
+
|
|
7
|
+
When you finish you will be able to:
|
|
8
|
+
|
|
9
|
+
- store and read **entity variables** (`ent:`)
|
|
10
|
+
- choose between `defaultsTo` and `||` for a missing value
|
|
11
|
+
- keep a nested map and update one part of it with a **path assignment**
|
|
12
|
+
- write a rule with one action block and a `fired` / `else` postlude
|
|
13
|
+
- delete a persistent variable with `clear`
|
|
14
|
+
- inspect a pico's state while you work
|
|
15
|
+
|
|
16
|
+
**Before you begin**, finish [Events and Queries](/lessons/events-and-queries). Make a new child pico for this lesson, so the ruleset below doesn't collide with the Quickstart's `io.picolabs.hello_world`. The Testing tab's default `self` channel allows everything, so you don't need a channel of your own. If you want to use `curl`, make a channel whose policies allow `hello` events (`{"allow": [{"domain": "hello", "name": "*"}], "deny": []}`) and this ruleset's queries (`{"allow": [{"rid": "io.picolabs.hello_world", "name": "*"}], "deny": []}`).
|
|
17
|
+
|
|
18
|
+
## Persistent variables
|
|
19
|
+
|
|
20
|
+
A KRL declaration like `x = 5` isn't an assignment, and it lives only as long as the rule evaluation. To remember something, use a **persistent variable**. There are two kinds:
|
|
21
|
+
|
|
22
|
+
- **Entity variables** (`ent:`) belong to one pico. The same ruleset running on two picos has two separate `ent:name`. They're how a pico has state.
|
|
23
|
+
- **Application variables** (`app:`) belong to the ruleset itself and are shared by every pico that has it installed. They're rarely what you want.
|
|
24
|
+
|
|
25
|
+
Entity variables:
|
|
26
|
+
|
|
27
|
+
- survive restarts and updates to the ruleset
|
|
28
|
+
- are private to the ruleset that uses them, on that pico. Other rulesets can't read your `ent:name`; they ask your ruleset through a shared function
|
|
29
|
+
- are **read** in any expression: a prelude, a condition, or a function
|
|
30
|
+
- are **written** only in a rule's **postlude**, the `fired`, `notfired`, `always`, or `else` block after the action
|
|
31
|
+
- are limited to about 1 MB each, and come back as copies: you can't hold a reference and change it. Large structures are slow to rewrite
|
|
32
|
+
|
|
33
|
+
Reading a variable that was never set gives `null`.
|
|
34
|
+
|
|
35
|
+
The [Persistent Variables](/krl/persistent-variables/) section of the KRL manual has the full story.
|
|
36
|
+
|
|
37
|
+
## Store a name
|
|
38
|
+
|
|
39
|
+
Start with the smallest case: one pico, one remembered name. Save this ruleset in a file, `hello_world_state.krl`, and install it on the new pico from a `file://` URL (so that flush rereads your file; see the [Quickstart](/lessons/quickstart)). It keeps the rid `io.picolabs.hello_world`, and you'll change this one file as the lesson goes on, flushing after each change:
|
|
40
|
+
|
|
41
|
+
```krl
|
|
42
|
+
ruleset io.picolabs.hello_world {
|
|
43
|
+
meta {
|
|
44
|
+
name "Hello World"
|
|
45
|
+
author "Phil Windley"
|
|
46
|
+
shares hello, name
|
|
47
|
+
}
|
|
48
|
+
global {
|
|
49
|
+
hello = function(obj) {
|
|
50
|
+
"Hello " + obj
|
|
51
|
+
}
|
|
52
|
+
name = function() {
|
|
53
|
+
ent:name.defaultsTo("Monkey")
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
rule store_name {
|
|
57
|
+
select when hello name name re#(.*)# setting(new_name)
|
|
58
|
+
send_directive("store_name", {"name": new_name})
|
|
59
|
+
always {
|
|
60
|
+
ent:name := new_name
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Then:
|
|
67
|
+
|
|
68
|
+
1. Query `name`. The pico hasn't stored anything, so `ent:name` is `null` and `defaultsTo` supplies `"Monkey"`.
|
|
69
|
+
2. Send the event `hello:name` with attribute `name` set to `Ada`. The rule answers with a `store_name` directive.
|
|
70
|
+
3. Query `name` again. It's `"Ada"`.
|
|
71
|
+
4. Restart the engine (stop it with Control-C and start it again) and query `name`. It's still `"Ada"`. That's what "persistent" means.
|
|
72
|
+
|
|
73
|
+
<img src="/lessons/_media/20742148-state_testing.png" alt="Sending hello:name with the name Bob on the Testing tab. The results show the store_name directive" width="50%">
|
|
74
|
+
|
|
75
|
+
<img src="/lessons/_media/20742148-state_testing2.png" alt="Querying name on the Testing tab. The result is Bob" width="50%">
|
|
76
|
+
|
|
77
|
+
The pieces:
|
|
78
|
+
|
|
79
|
+
- `select when hello name name re#(.*)# setting(new_name)` selects `hello:name` events whose `name` attribute matches the regular expression, and `setting` gives the captured text a name. The domain is `hello`, the type is `name`, and `name` is the attribute.
|
|
80
|
+
- The rule has one action, `send_directive`. Anything after the action runs in the **postlude**.
|
|
81
|
+
- `always { … }` runs whether or not an action ran. `ent:name := new_name` is the only place the variable changes.
|
|
82
|
+
|
|
83
|
+
Notice that the function `name` and the event attribute `name` share a word and nothing else. Names in KRL live in different places: [What's in a name?](/developing/names-and-scope) explains the one case where that bites.
|
|
84
|
+
|
|
85
|
+
You can check any entity variable without writing a query. On the **Testing** tab, pick the ruleset, find the **KRL console**, enter `ent:name`, and click **Evaluate**. It evaluates the expression inside that ruleset on that pico.
|
|
86
|
+
|
|
87
|
+
## defaultsTo and ||
|
|
88
|
+
|
|
89
|
+
Two ways to say "this, or if it's missing, that":
|
|
90
|
+
|
|
91
|
+
```krl
|
|
92
|
+
ent:name.defaultsTo("Monkey")
|
|
93
|
+
ent:name || "Monkey"
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
They differ in what counts as missing:
|
|
97
|
+
|
|
98
|
+
| Expression | `ent:name` is `null` | `ent:name` is `""` | `ent:name` is `0` or `false` |
|
|
99
|
+
|---|---|---|---|
|
|
100
|
+
| `ent:name.defaultsTo("Monkey")` | `"Monkey"` | `""` | `0` / `false` |
|
|
101
|
+
| `ent:name \|\| "Monkey"` | `"Monkey"` | `"Monkey"` | `"Monkey"` |
|
|
102
|
+
|
|
103
|
+
`defaultsTo` replaces only `null`. `||` replaces anything false: `null`, the empty string, `0`, and `false`.
|
|
104
|
+
|
|
105
|
+
Try it. Send `hello:name` with `name` set to nothing at all (`...?name=`). The regular expression `(.*)` accepts an empty string, so the pico stores `""`. Query `name`:
|
|
106
|
+
|
|
107
|
+
- with `defaultsTo`, the answer is `""`. The stored empty string is a value.
|
|
108
|
+
- change the function to `ent:name || "Monkey"` and flush: the answer is `"Monkey"`.
|
|
109
|
+
|
|
110
|
+
Which is right depends on what the value means. For text where an empty string means "not set", use `||`. For counts, flags, and anywhere `0` or `false` is a real value, use `defaultsTo`. `ent:count || 5` can never give `0`. This is also the idiom for event attributes: `event:attr("name") || ent:name` falls back for a missing or empty attribute. See [event attributes](/krl/rulesets/rules/prelude/event-attributes).
|
|
111
|
+
|
|
112
|
+
## Many names: a map
|
|
113
|
+
|
|
114
|
+
One name isn't enough. To remember a name for each person, give each one an id and keep a map: `ent:users` maps an id to what we know about that person.
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{
|
|
118
|
+
"1": {"name": {"first": "Ada", "last": "Lovelace"}, "visits": 2},
|
|
119
|
+
"2": {"name": {"first": "Grace", "last": "Hopper"}}
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
To write inside the map, use a **path assignment**. The path is a list of keys, in `{[ … ]}` after the variable:
|
|
124
|
+
|
|
125
|
+
```krl
|
|
126
|
+
ent:users{[id, "name", "first"]} := first
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
That sets `first` under `id`, then `"name"`, then `"first"`. If `ent:users` or the maps along the path don't exist, they're created. You can read with the same path: `ent:users{[id, "name", "first"]}`. For one level, `ent:users{id}` works. For deeper keys, put them all in one list, and don't chain (`ent:users{id}{"name"}` isn't valid on the left of an assignment).
|
|
130
|
+
|
|
131
|
+
> **Older style:** you'll see `ent:users := ent:users.put([id, "name", "first"], first)` in older rulesets. It still works, but it reads the whole map, copies it, and writes it back. Prefer the path assignment.
|
|
132
|
+
|
|
133
|
+
## The full ruleset
|
|
134
|
+
|
|
135
|
+
Here's the whole ruleset, with names, visit counts, and a way to start over. Replace the contents of `hello_world_state.krl` with this one, and flush the ruleset:
|
|
136
|
+
|
|
137
|
+
```krl
|
|
138
|
+
ruleset io.picolabs.hello_world {
|
|
139
|
+
meta {
|
|
140
|
+
name "Hello World"
|
|
141
|
+
author "Phil Windley"
|
|
142
|
+
shares hello, name, users, visits
|
|
143
|
+
}
|
|
144
|
+
global {
|
|
145
|
+
hello = function(obj) {
|
|
146
|
+
"Hello " + obj
|
|
147
|
+
}
|
|
148
|
+
users = function() {
|
|
149
|
+
ent:users.defaultsTo({})
|
|
150
|
+
}
|
|
151
|
+
name = function(id) {
|
|
152
|
+
first = ent:users{[id, "name", "first"]}.defaultsTo("HAL")
|
|
153
|
+
last = ent:users{[id, "name", "last"]}.defaultsTo("9000")
|
|
154
|
+
first + " " + last
|
|
155
|
+
}
|
|
156
|
+
visits = function(id) {
|
|
157
|
+
ent:users{[id, "visits"]}.defaultsTo(0)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
rule store_name {
|
|
161
|
+
select when hello name
|
|
162
|
+
pre {
|
|
163
|
+
id = event:attr("id")
|
|
164
|
+
first = event:attr("first")
|
|
165
|
+
last = event:attr("last")
|
|
166
|
+
}
|
|
167
|
+
if id && first && last then send_directive("store_name", {"id": id, "name": first + " " + last})
|
|
168
|
+
fired {
|
|
169
|
+
ent:users{[id, "name", "first"]} := first
|
|
170
|
+
ent:users{[id, "name", "last"]} := last
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
error warn <<store_name needs id, first, and last>>
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
rule visit {
|
|
177
|
+
select when hello visit
|
|
178
|
+
pre {
|
|
179
|
+
id = event:attr("id")
|
|
180
|
+
}
|
|
181
|
+
if id then send_directive("hello", {"something": hello(name(id))})
|
|
182
|
+
fired {
|
|
183
|
+
ent:users{[id, "visits"]} := visits(id) + 1
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
error warn <<visit needs an id>>
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
rule clear_names {
|
|
190
|
+
select when hello clear_names
|
|
191
|
+
always {
|
|
192
|
+
clear ent:users
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Walk through what's new.
|
|
199
|
+
|
|
200
|
+
**`if … then action`.** A rule runs one action block, here the single `send_directive`, only when the condition is true. The condition `id && first && last` is false if any attribute is missing. `fired` runs when the condition was true and the action ran. `else` runs when it wasn't, here to log a warning: `error warn` raises a `system:error` event you can see in the Logging tab, and it doesn't stop anything else. If you had two things to do, use an `every { … }` block, not two `if … then` blocks.
|
|
201
|
+
|
|
202
|
+
**`pre`** declares `id`, `first`, and `last` once for the rule. You can't redeclare them.
|
|
203
|
+
|
|
204
|
+
**Functions read, rules write.** `users`, `name`, and `visits` read state with `defaultsTo`. Because `name(id)` falls back to `"HAL 9000"`, an unknown id doesn't produce an error. `visit` writes the visit count, but only in its postlude.
|
|
205
|
+
|
|
206
|
+
**`clear ent:users`** deletes the variable entirely. Afterward `ent:users` is `null` again, and `users()` shows `{}`. You could also assign an empty map, `ent:users := {}`, which keeps the variable but with nothing in it.
|
|
207
|
+
|
|
208
|
+
Now play with it from the Testing tab (or from `curl`, with the URLs from the last lesson):
|
|
209
|
+
|
|
210
|
+
1. Send `hello:name` with `id` `1`, `first` `Ada`, `last` `Lovelace`.
|
|
211
|
+
|
|
212
|
+
<img src="/lessons/_media/20742148-state_testing5.png" alt="The Testing tab hello:name form with id, first, and last fields" width="50%">
|
|
213
|
+
|
|
214
|
+
2. Send `hello:name` with `id` `2` and only `first`: the warning shows in the Logging tab and nothing is stored. The condition was false, so `else` ran.
|
|
215
|
+
3. Query `name` with `id` `1`: `"Ada Lovelace"`. With `id` `9`: `"HAL 9000"`.
|
|
216
|
+
|
|
217
|
+
<img src="/lessons/_media/20742148-state_testing4.png" alt="Querying name with an unknown id on the Testing tab, showing the default HAL 9000 greeting" width="50%">
|
|
218
|
+
|
|
219
|
+
4. Send `hello:visit` with `id` `1` twice. The directive says `Hello Ada Lovelace`. Query `visits` with `id` `1`: `2`.
|
|
220
|
+
|
|
221
|
+
<img src="/lessons/_media/20742148-state_testing6.png" alt="The Testing tab after hello:visit, showing the hello directive with the stored name" width="50%">
|
|
222
|
+
|
|
223
|
+
5. Query `users`: `{"1": {"name": {"first": "Ada", "last": "Lovelace"}, "visits": 2}}`.
|
|
224
|
+
|
|
225
|
+
<img src="/lessons/_media/20742148-state_testing7.png" alt="The users query on the Testing tab, with each stored user's name and visit count in the Results panel" width="50%">
|
|
226
|
+
|
|
227
|
+
6. Send `hello:clear_names`. Query `users`: `{}`. The visit count went too, because it lives in the same map.
|
|
228
|
+
|
|
229
|
+
<img src="/lessons/_media/20742148-state_testing3.png" alt="The users query after clear_names, showing an empty map" width="50%">
|
|
230
|
+
|
|
231
|
+
Over HTTP the same steps look like this:
|
|
232
|
+
|
|
233
|
+
```sh
|
|
234
|
+
curl -X POST "http://localhost:3000/sky/event/<eci>/none/hello/name?id=1&first=Ada&last=Lovelace"
|
|
235
|
+
curl -X POST "http://localhost:3000/sky/event/<eci>/none/hello/visit?id=1"
|
|
236
|
+
curl "http://localhost:3000/sky/query/<eci>/io.picolabs.hello_world/visits?id=1"
|
|
237
|
+
curl "http://localhost:3000/sky/query/<eci>/io.picolabs.hello_world/users"
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Check the channel's policy: it has to allow `hello` events and the functions you query.
|
|
241
|
+
|
|
242
|
+
Entity variables are per pico. Make a second pico, install the same ruleset on it, and query `users`. It's empty: the first pico's names are in the first pico.
|
|
243
|
+
|
|
244
|
+
## Exercises
|
|
245
|
+
|
|
246
|
+
1. **A greeting that remembers.** Add a rule that answers `hello:greet` with `Hello` and the name stored by the first, single-name version of this ruleset. Store with `ent:name`, and use `||` so an empty name falls back to `"Monkey"`.
|
|
247
|
+
2. **Last seen.** Record the time of each visit with `ent:users{[id, "last_visit"]} := time:now()`, and add a function that returns it. (`time:now()` is in the [time library](/krl/libraries/time).)
|
|
248
|
+
3. **Forget one.** Add a rule that selects `hello:forget` and removes just one id. A path assignment can set the visit count to `0` or a name to an empty string. To remove the whole entry, assign the map without it: `ent:users := ent:users.delete([id])`. Compare the two.
|
|
249
|
+
4. **Total visits.** Add a function, `total_visits`, that adds up every user's visits. You'll want `users().values()` (the [map operators](/krl/krl-expression-language/operators/map-operators)) and `reduce`. Use `defaultsTo(0)` for users who have never visited.
|
|
250
|
+
5. **A guard.** Make `visit` refuse an unknown id: do nothing, and log a warning, unless `ent:users{id}` exists. Where does the check go: the condition, the `pre`, or the postlude?
|
|
251
|
+
6. **A counter that can be zero.** Write `starting = ent:count || 5` for a counter, then store `0` in `ent:count`. What does `starting` give, and why? Fix it.
|
|
252
|
+
|
|
253
|
+
## What you learned
|
|
254
|
+
|
|
255
|
+
- `ent:` variables are a pico's memory: per pico, persistent, read anywhere, written only in the postlude.
|
|
256
|
+
- `defaultsTo` replaces `null`; `||` replaces anything false.
|
|
257
|
+
- `ent:users{[id, "name", "first"]} := first` updates one part of a nested map. `put` still works, but path assignment is the modern way.
|
|
258
|
+
- A rule has one action block. `fired` runs when it ran, `else` when the condition was false, `always` either way.
|
|
259
|
+
- `clear ent:x` deletes a variable.
|
|
260
|
+
|
|
261
|
+
## Next
|
|
262
|
+
|
|
263
|
+
[Modules and External APIs](/lessons/modules-and-apis) shows how to share code between rulesets and talk to services on the web. The [Score tracker](/cookbook/score_tracker/) demo is a small app built on this kind of state: a contest pico that keeps a leaderboard in entity variables.
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
<small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/20742148/Pico+State+Lesson) (last edited there 2021-02-18), and updated for this engine.</small>
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
# Pico Views
|
|
2
|
+
|
|
3
|
+
A pico can be the whole back end of an application: it keeps the state, enforces who may change it, and answers queries. This lesson adds the front end, and it lives in the pico too. You'll build a small **timing tracker** (start a timing, finish it later, see how long it took) and serve its page straight from the pico as a **pico view**.
|
|
4
|
+
|
|
5
|
+
This replaces the older Single Page Application lesson, which wrote the page by hand in Angular and called the pico with AJAX. That approach still works, and you'll see how at the end. A view is the engine-hosted way: no web server, no JavaScript build, no ECI pasted into a URL. You install a ruleset and open it.
|
|
6
|
+
|
|
7
|
+
## Objectives
|
|
8
|
+
|
|
9
|
+
When you finish you will be able to:
|
|
10
|
+
|
|
11
|
+
- write a ruleset that keeps timings in an entity variable and shares them with a query
|
|
12
|
+
- write rules for `timing:started` and `timing:finished` with attribute matching
|
|
13
|
+
- tag a shared function with `@view` so the engine serves it as a page
|
|
14
|
+
- read and write from the page with `ui:query` and `ui:event`
|
|
15
|
+
- create an app channel with `ui:create_app_channel`, and one channel per user so you can revoke one
|
|
16
|
+
- say when to use a view and when to use a classic single page application
|
|
17
|
+
|
|
18
|
+
**Before you begin**, finish [Pico State](/lessons/pico-state) and read [Pico views](/pico-views). You need a running engine. If you haven't seen a view yet, run the [Echo demo](/cookbook/echo/) first: it's the smallest one, and its [instructions](/cookbook/echo/instructions) take two minutes.
|
|
19
|
+
|
|
20
|
+
## The application
|
|
21
|
+
|
|
22
|
+
Each **timing** has a number (`n1`, `n2`, …) and a name. When a timekeeper starts a timing, the pico records the start time. When they finish it, the pico records the finish time and the page shows the elapsed time as `HH:MM:SS`.
|
|
23
|
+
|
|
24
|
+
Some rules of the game:
|
|
25
|
+
|
|
26
|
+
- There can be several timekeepers using the page at once, but only one of them starts a given number. A number can't be reused.
|
|
27
|
+
- Finishing a timing records the finish time. A later finish overwrites it. (Ignoring later finishes is an exercise.)
|
|
28
|
+
- A timing that has started but not finished shows a **Finished** button.
|
|
29
|
+
|
|
30
|
+
That's all the behavior. A pico already knows how to do every part: events change state, a shared function reads it, and a channel decides who can do either. The view only adds a way to see and click.
|
|
31
|
+
|
|
32
|
+
## The ruleset
|
|
33
|
+
|
|
34
|
+
Save this as `com.example.timing_tracker.krl`. The three rules `timing_first_use`, `timing_started`, and `timing_finished` are the heart of the application. The page (`timingPage`) and the channel rules come after them in this walk-through.
|
|
35
|
+
|
|
36
|
+
```krl
|
|
37
|
+
ruleset com.example.timing_tracker {
|
|
38
|
+
meta {
|
|
39
|
+
name "Timing tracker"
|
|
40
|
+
description "Start and finish times, each identified by a number and a name."
|
|
41
|
+
use module io.picolabs.xmlui alias ui
|
|
42
|
+
shares entries, timings, timingPage
|
|
43
|
+
}
|
|
44
|
+
global {
|
|
45
|
+
channel_tags = ["timing", "app"]
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Every timing, as stored.
|
|
49
|
+
* @returns Array of { ordinal, number, name, time_out, time_in }
|
|
50
|
+
*/
|
|
51
|
+
entries = function() {
|
|
52
|
+
ent:timings.defaultsTo({}).values()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
pad = function(n) {
|
|
56
|
+
n < 10 => "0" + n.as("String") | n.as("String")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// HH:MM:SS between the start and the finish of one timing
|
|
60
|
+
elapsed = function(timing) {
|
|
61
|
+
started = time:strftime(timing{"time_out"}, "%s").as("Number")
|
|
62
|
+
finished = time:strftime(timing{"time_in"}, "%s").as("Number")
|
|
63
|
+
secs = finished - started
|
|
64
|
+
hours = (secs - secs % 3600) / 3600
|
|
65
|
+
minutes = (secs % 3600 - secs % 60) / 60
|
|
66
|
+
pad(hours) + ":" + pad(minutes) + ":" + pad(secs % 60)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The timings, newest first, with the elapsed time of each finished one.
|
|
71
|
+
* @returns Array of { ordinal, number, name, time_out, time_in, elapsed }
|
|
72
|
+
*/
|
|
73
|
+
timings = function() {
|
|
74
|
+
entries()
|
|
75
|
+
.sort(function(a, b) { b{"ordinal"} <=> a{"ordinal"} })
|
|
76
|
+
.map(function(t) { t.put("elapsed", t{"time_in"} => elapsed(t) | "") })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Start and finish timings
|
|
81
|
+
* @view "Timing"
|
|
82
|
+
*/
|
|
83
|
+
timingPage = function() {
|
|
84
|
+
<<
|
|
85
|
+
<Component name="TimingPage">
|
|
86
|
+
#{ui:query("rows", "timings", {"rid": meta:rid})}
|
|
87
|
+
#{ui:event("startTiming", "timing", "started", {"refresh": ["rows"]})}
|
|
88
|
+
#{ui:event("finishTiming", "timing", "finished", {"refresh": ["rows"]})}
|
|
89
|
+
<PicoTheme>
|
|
90
|
+
<Card title="Timing" subtitle="Number a timing (n1, n2, ...), name it, and click Finished when it is over." />
|
|
91
|
+
<Form saveLabel="Timing started" onSubmit="(data) => startTiming.execute(data)">
|
|
92
|
+
<FormItem bindTo="number" label="Number" initialValue="n1" required />
|
|
93
|
+
<FormItem bindTo="name" label="Name" required />
|
|
94
|
+
</Form>
|
|
95
|
+
<Table data="{rows}">
|
|
96
|
+
<property name="noDataTemplate">
|
|
97
|
+
<Text value="No timings yet" variant="strong" />
|
|
98
|
+
</property>
|
|
99
|
+
<Column bindTo="number" header="Number" />
|
|
100
|
+
<Column bindTo="name" header="Name" />
|
|
101
|
+
<Column bindTo="time_out" header="Started" />
|
|
102
|
+
<Column bindTo="time_in" header="Finished" />
|
|
103
|
+
<Column bindTo="elapsed" header="Elapsed" />
|
|
104
|
+
<Column header="">
|
|
105
|
+
<Button label="Finished" when="{!$item.time_in}" onClick="finishTiming.execute({number: $item.number})" />
|
|
106
|
+
</Column>
|
|
107
|
+
</Table>
|
|
108
|
+
</PicoTheme>
|
|
109
|
+
</Component>
|
|
110
|
+
>>
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
rule timing_first_use {
|
|
115
|
+
select when timing started or timing finished
|
|
116
|
+
if ent:timings then noop()
|
|
117
|
+
notfired {
|
|
118
|
+
ent:timings := {}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Start a timing. A number that is already in use is ignored.
|
|
124
|
+
* @attr number String "n followed by digits, such as n1"
|
|
125
|
+
* @attr name String "who or what is being timed"
|
|
126
|
+
* @example "first timing" { "number": "n1", "name": "Nick Angell" }
|
|
127
|
+
*/
|
|
128
|
+
rule timing_started {
|
|
129
|
+
select when timing started number re#n0*(\d+)#i setting(ordinal_string)
|
|
130
|
+
pre {
|
|
131
|
+
key = "N" + ordinal_string
|
|
132
|
+
}
|
|
133
|
+
if ent:timings >< key then noop()
|
|
134
|
+
notfired {
|
|
135
|
+
ent:timings{key} := {
|
|
136
|
+
"ordinal": ordinal_string.as("Number"),
|
|
137
|
+
"number": event:attr("number"),
|
|
138
|
+
"name": event:attr("name"),
|
|
139
|
+
"time_out": time:now() }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Finish a timing. Later finishes overwrite the finish time.
|
|
145
|
+
* @attr number String "the number the timing was started with"
|
|
146
|
+
* @example "finish" { "number": "n1" }
|
|
147
|
+
*/
|
|
148
|
+
rule timing_finished {
|
|
149
|
+
select when timing finished number re#n0*(\d+)#i setting(ordinal_string)
|
|
150
|
+
pre {
|
|
151
|
+
key = "N" + ordinal_string
|
|
152
|
+
}
|
|
153
|
+
if ent:timings >< key then noop()
|
|
154
|
+
fired {
|
|
155
|
+
ent:timings{[key,"time_in"]} := time:now()
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Make a channel for one more timekeeper. Delete the channel to revoke access.
|
|
161
|
+
* @attr who String "the timekeeper's name"
|
|
162
|
+
* @example "Ada" { "who": "Ada" }
|
|
163
|
+
*/
|
|
164
|
+
rule new_timekeeper {
|
|
165
|
+
select when timing timekeeper_needed who re#(.+)# setting(who)
|
|
166
|
+
ui:create_app_channel(channel_tags.append(who), ["timing"], null, meta:rid)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
rule create_app_channel {
|
|
170
|
+
select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
|
|
171
|
+
ui:create_app_channel(channel_tags, ["timing"], null, meta:rid)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### The state and the rules
|
|
177
|
+
|
|
178
|
+
`ent:timings` is a map. Each key is a normalized number such as `N1`, and each value is a map of that timing's data. `entries` returns the values as an array, with `ordinal`, `number`, `name`, `time_out`, and `time_in` in each. It uses `defaultsTo({})`, so a query before anything has been timed returns an empty array instead of failing.
|
|
179
|
+
|
|
180
|
+
**`timing_first_use`** selects *both* `timing:started` and `timing:finished`. If `ent:timings` already holds something, the rule fires and does nothing (`noop()`). Otherwise the `notfired` postlude initializes it to an empty map. Rules in one ruleset that select the same event run in the order they're written, so this one runs before the other two and they can count on the map being there. (It's belt and braces here, since `entries` already defaults the value, but it's a good habit to have an initializing rule for each entity variable.)
|
|
181
|
+
|
|
182
|
+
**`timing_started`** selects `timing:started` when the event has a `number` attribute that matches the regular expression `n0*(\d+)` (case-insensitive). That's the letter `n`, any leading zeros, and at least one digit. `setting(ordinal_string)` binds what the parentheses captured, so `n007` gives `"7"`. The prelude builds a normalized key, `"N" + ordinal_string`. Then the condition asks whether `ent:timings` already has that key. If it **doesn't** (`notfired`), the postlude adds the entry with `time:now()` as the start. If it does, nothing happens, which is how a number can't be reused.
|
|
183
|
+
|
|
184
|
+
**`timing_finished`** selects `timing:finished` with the same pattern and builds the same key. If the timing exists (`fired`), it sets `time_in` with a *path assignment*: `ent:timings{[key,"time_in"]} := time:now()` changes one part of one entry and leaves the rest alone.
|
|
185
|
+
|
|
186
|
+
A rule with `if X then noop()` runs `fired` when `X` is true and `notfired` when it's false. The two rules use that opposite ways on purpose: `timing_started` acts when the key is *missing*, `timing_finished` when it's *present*.
|
|
187
|
+
|
|
188
|
+
### The elapsed time
|
|
189
|
+
|
|
190
|
+
The pico does the arithmetic, not the page. `timings` is a second shared function: the same data sorted newest first, with an `elapsed` string added to each finished timing. `time:strftime(t, "%s")` turns an ISO 8601 time into seconds since 1970, so `elapsed` subtracts two of them and formats the difference. Keeping the logic in KRL means the page only displays strings.
|
|
191
|
+
|
|
192
|
+
### The view
|
|
193
|
+
|
|
194
|
+
`timingPage` is tagged `@view "Timing"`, so the engine serves it as a page, and `shares` lists it so it can be queried. It returns one XMLUI `<Component>`. The only KRL inside the heredoc is the `#{…}` helpers from `io.picolabs.xmlui`, which run when the page is generated and return markup:
|
|
195
|
+
|
|
196
|
+
| In the page | What it does |
|
|
197
|
+
|-------------|--------------|
|
|
198
|
+
| `ui:query("rows", "timings", {"rid": meta:rid})` | A `DataSource` named `rows` that calls the shared function `timings` on this channel. The `rid` option is needed because inside the helper `meta:rid` would be the helper's own |
|
|
199
|
+
| `ui:event("startTiming", "timing", "started", {"refresh": ["rows"]})` | An `APICall` named `startTiming` that sends `timing:started` with the form's fields as attributes, then refetches `rows` |
|
|
200
|
+
| `ui:event("finishTiming", "timing", "finished", {"refresh": ["rows"]})` | The same for `timing:finished` |
|
|
201
|
+
|
|
202
|
+
After that it's XMLUI. The `Form` calls `startTiming.execute(data)` on submit; its `FormItem`s are named `number` and `name`, so those become the event attributes your rule matches. The `Table` shows `rows`. Its last column puts a `Button` in each row, shown `when` the row has no `time_in`, and its `onClick` runs `finishTiming.execute({number: $item.number})`. `$item` is the row. Nothing on the page talks about ECIs or URLs: the shell the engine serves already knows which channel it was opened on.
|
|
203
|
+
|
|
204
|
+
> **Note:** `#{…}` is for markup and constants only. Never put `ent:` variables or query results inside it. Values that change belong in a `DataSource`, as `rows` does here. [Pico views](/pico-views) explains why, and `krl check` warns when you slip.
|
|
205
|
+
|
|
206
|
+
Put `<Component …>` on its own line after `<<`, as above. The component name must be the function name with a capital first letter: `timingPage` becomes `TimingPage`.
|
|
207
|
+
|
|
208
|
+
## The app channel
|
|
209
|
+
|
|
210
|
+
Look at the last rule:
|
|
211
|
+
|
|
212
|
+
```krl
|
|
213
|
+
rule create_app_channel {
|
|
214
|
+
select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
|
|
215
|
+
ui:create_app_channel(channel_tags, ["timing"], null, meta:rid)
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`wrangler:ruleset_installed` is the first event a ruleset sees, and every ruleset on the pico sees it when *any* ruleset is installed, so the `where` clause selects only your own install. `ui:create_app_channel(tags, domains, queries, app_rid)` makes a channel that:
|
|
220
|
+
|
|
221
|
+
- allows events only in the `timing` domain
|
|
222
|
+
- allows queries on `com.example.timing_tracker` (`null` means every shared function) plus `io.picolabs.xmlui`'s `file`, which the page shell needs
|
|
223
|
+
- is tagged `timing` and `app`
|
|
224
|
+
|
|
225
|
+
Whoever holds that channel can record timings and read them, and nothing else. They can't install a ruleset, create a child, or see another ruleset's state. That policy is what the old lesson did by hand with a "channel for each timekeeper".
|
|
226
|
+
|
|
227
|
+
### One channel per timekeeper
|
|
228
|
+
|
|
229
|
+
The old lesson gave every timekeeper a separate channel so you could cut one person off without bothering the others. You can still do that. The rule `new_timekeeper` makes another app channel with the person's name as an extra tag:
|
|
230
|
+
|
|
231
|
+
```
|
|
232
|
+
timing:timekeeper_needed who=Ada
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
Raise it on the Testing tab. Give each person the page opened on their own channel, and to revoke someone, delete their channel on the **Channels** tab. Their page stops working at once. The others are unaffected.
|
|
236
|
+
|
|
237
|
+
## Try it
|
|
238
|
+
|
|
239
|
+
1. Create a child pico on the **About** tab. Call it "Timing".
|
|
240
|
+
2. On its **Rulesets** tab, install `io.picolabs.xmlui` from your engine:
|
|
241
|
+
|
|
242
|
+
```
|
|
243
|
+
http://localhost:3000/krl/io.picolabs.xmlui.krl
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The engine ships this ruleset but doesn't install it anywhere by default. It builds the page shell and the `ui:` helpers.
|
|
247
|
+
3. Install `com.example.timing_tracker`. Use the **Browse…** button (as in the [Quickstart](/lessons/quickstart)) or a `file://` URL to your saved file.
|
|
248
|
+
4. Click **View** next to the ruleset and choose the channel tagged `timing, app`. The page opens at `/ui/{eci}/com.example.timing_tracker/`.
|
|
249
|
+
5. Enter `n1` and a name, click **Timing started**, wait a few seconds, then click **Finished**. The elapsed time appears. Start `n2` and leave it running.
|
|
250
|
+
6. Start `n1` again. Nothing changes: the number is taken.
|
|
251
|
+
|
|
252
|
+
<img src="/lessons/_media/32640450-timing1.png" alt="The timing tracker page with number and name fields and a Timing started button" width="50%">
|
|
253
|
+
|
|
254
|
+
<img src="/lessons/_media/32640450-timing2.png" alt="The timing tracker page listing n2 as running and n1 as finished, with its elapsed time" width="50%">
|
|
255
|
+
|
|
256
|
+
The same events work without the page. This is why a view is a front end and not a different kind of pico:
|
|
257
|
+
|
|
258
|
+
```sh
|
|
259
|
+
curl -X POST "http://localhost:3000/sky/event/<eci>/none/timing/started?number=n3&name=Grace"
|
|
260
|
+
curl "http://localhost:3000/sky/query/<eci>/com.example.timing_tracker/entries"
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
Use the ECI of the `timing, app` channel. Reload the page and `n3` is there. On the Testing tab, `timing:started` and `timing:finished` show up as forms, because their rules have documentation comments with `@attr` and `@example`.
|
|
264
|
+
|
|
265
|
+
If the page can't find something, check the channel's policy first. A view fails closed: a channel that can't call a function doesn't get that page, and a channel that can't send an event can't click that button.
|
|
266
|
+
|
|
267
|
+
## Exercises
|
|
268
|
+
|
|
269
|
+
1. Make `timing_finished` ignore a second finish, so the first finish time stays.
|
|
270
|
+
2. Add a `timing:cleared` rule that deletes every timing, and a **Clear** button that sends it. Which channel policy does it need?
|
|
271
|
+
3. Add a second page, `/summary`, that shows how many timings are finished and how many are running. Read [Pico views](/pico-views) on `@view` paths.
|
|
272
|
+
|
|
273
|
+
## Views and classic single page applications
|
|
274
|
+
|
|
275
|
+
Everything a view does, an ordinary web page can do, because everything goes over [Sky](/exp/): `POST /sky/event/{eci}/{eid}/{domain}/{type}` to send an event and `GET /sky/query/{eci}/{rid}/{function}` to ask a question. A page written in Angular, React, or plain HTML and `fetch` that is served from anywhere can use the timing tracker with no change to the ruleset. The old lesson did exactly that and read the ECI from the page's query string. If your front end already exists, or has to run somewhere other than the engine, do that.
|
|
276
|
+
|
|
277
|
+
Prefer a pico view when the page belongs to the pico: you want to install an app and open it, you want the channel policy to be what limits the page, or you want no other server. The pieces to explore next:
|
|
278
|
+
|
|
279
|
+
- [Pico views](/pico-views): paths and detail pages, `@component`, themes and settings, OAuth-protected meshes
|
|
280
|
+
- [Echo](/cookbook/echo/): events, directives, and an app channel that allows only `echo` events
|
|
281
|
+
- [Pico view demos](/cookbook/xmlui/): guestbook, contacts, thermostat, and a view over another pico's data
|
|
282
|
+
- [Event Exchange Protocol](/exp/): the HTTP side of events and queries
|
|
283
|
+
|
|
284
|
+
## Next
|
|
285
|
+
|
|
286
|
+
[Pico-Based Systems](/lessons/pico-based-systems) shows picos making other picos: the parent and child tree, and how a parent keeps track of its children.
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
<small>Ported from the [Pico Labs wiki](https://picolabs.atlassian.net/wiki/spaces/docs/pages/32640450) (Single Page Application lesson, last edited there 2021-01-07), rewritten for pico views and this engine.</small>
|