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,75 @@
|
|
|
1
|
+
# Bootstrap and channels: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/bootstrap/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Bootstrap and channels**, then **Run in a new child pico**. The stage names each ruleset as it is installed. When it shows **ready**, open **Visitor log**.
|
|
8
|
+
|
|
9
|
+
## By hand
|
|
10
|
+
|
|
11
|
+
Installing the app by hand is the job the bootstrap does for you:
|
|
12
|
+
|
|
13
|
+
1. Create a child pico and open its **Rulesets** tab.
|
|
14
|
+
2. Install `http://localhost:3000/krl/io.picolabs.xmlui.krl`.
|
|
15
|
+
3. Install `http://localhost:3000/krl/demos/bootstrap/com.example.visitors.format.krl`. It has to come before the app, which uses it as a module.
|
|
16
|
+
4. Install `http://localhost:3000/krl/demos/bootstrap/com.example.visitors.krl` with the configuration `{"greeting": "Welcome"}`. Leave the configuration out and visitors are greeted with "Hello".
|
|
17
|
+
5. Its install rule creates a channel tagged `visitors, app`. Click **View** next to `com.example.visitors` and open it on that channel.
|
|
18
|
+
|
|
19
|
+
## Try it
|
|
20
|
+
|
|
21
|
+
- Sign in. The greeting comes from the install configuration.
|
|
22
|
+
- **How the bootstrap set up this pico** lists the installed rulesets in install order. On the **Logging** tab, follow the `wrangler:ruleset_installed` events, each followed by the next install request.
|
|
23
|
+
- **This app's channel** shows the channel the install rule made, and the events its policy allows.
|
|
24
|
+
- Click **Run the channel rule again**. The answer is `set_up_channel`, and the channel's id is unchanged.
|
|
25
|
+
- Click **Make a duplicate, the naive way** twice: three channels with the same tags, the way a create-only install rule leaves a pico after a few reinstalls.
|
|
26
|
+
- Click **Clean up duplicates**. Every channel except the one this page uses is deleted.
|
|
27
|
+
|
|
28
|
+
## How it works
|
|
29
|
+
|
|
30
|
+
**The bootstrap** chains installs on `wrangler:ruleset_installed`. Each rule waits for the ruleset the next one needs:
|
|
31
|
+
|
|
32
|
+
```krl
|
|
33
|
+
rule install_app {
|
|
34
|
+
select when wrangler ruleset_installed where event:attr("rids") >< format_rid
|
|
35
|
+
always {
|
|
36
|
+
raise wrangler event "install_ruleset_request" attributes
|
|
37
|
+
{"absoluteURL": meta:rulesetURI, "rid": app_rid, "config": {"greeting": "Welcome"}}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`absoluteURL: meta:rulesetURI` with a `rid` installs `<rid>.krl` from the folder the bootstrap came from, so the app installs the same way from the engine, from GitHub, or from a `file://` URL. `config` becomes the app's `meta:rulesetConfig`.
|
|
43
|
+
|
|
44
|
+
**The app's install rule** selects its own install (the `where` keeps it from running when other rulesets are installed later), and also an event you can send to run it again:
|
|
45
|
+
|
|
46
|
+
```krl
|
|
47
|
+
rule set_up_channel {
|
|
48
|
+
select when wrangler ruleset_installed where event:attr("rids") >< meta:rid
|
|
49
|
+
or visitor_channel check_requested
|
|
50
|
+
pre {
|
|
51
|
+
existing = wrangler:channels(channel_tags).head()
|
|
52
|
+
}
|
|
53
|
+
if existing then every {
|
|
54
|
+
wrangler:updateChannel(existing{"id"}, channel_tags, eventPolicy(), queryPolicy())
|
|
55
|
+
send_directive("set_up_channel", {"result": "updated", "id": existing{"id"}})
|
|
56
|
+
}
|
|
57
|
+
notfired {
|
|
58
|
+
raise visitor_setup event "channel_missing"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
When there is no channel yet, `create_channel` makes one. `updateChannel` keeps the id, so links and pages that use the channel keep working.
|
|
64
|
+
|
|
65
|
+
**The policy** comes from the ruleset's schema, `wrangler:rulesetSchema(meta:rid)`. Its `operations` list the events each rule selects, and its `queries` list the shared functions. Both include only rules and functions with doc comments. `eventPolicy()` allows those events, except `wrangler`'s. `queryPolicy()` allows those functions plus what the page shell needs from `io.picolabs.xmlui`. `create_channel` has no doc comment, so the event that starts it isn't on the channel.
|
|
66
|
+
|
|
67
|
+
**Flushing** reloads a ruleset's code, but it doesn't raise `wrangler:ruleset_installed` again, because the ruleset was already installed. Channels made on install keep their old policy until the install rule runs again. That's what **Run the channel rule again** is for.
|
|
68
|
+
|
|
69
|
+
## Change it and watch
|
|
70
|
+
|
|
71
|
+
The **Try It!** window lists each file with its path on disk. Edit a file there, click **Flush**, and use the page.
|
|
72
|
+
|
|
73
|
+
- Add a documented rule to `com.example.visitors.krl` that selects `visitor waved`. After **Flush**, `visitor/waved` on the page's channel is refused. Click **Run the channel rule again**: now it is allowed.
|
|
74
|
+
- Change the greeting word in the bootstrap's `install_app`, and run the demo again in a new child.
|
|
75
|
+
- Make the bootstrap uninstall itself when it's done, by raising `wrangler:uninstall_ruleset_request` with `{"rid": meta:rid}` after the app is installed. The app still works. The Try It! tab loses track of it, though, because it asks the bootstrap's `tryIt()` for progress.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Child pico tasks
|
|
2
|
+
|
|
3
|
+
A pattern for work that takes a while: give each job its own child pico. The parent creates a child, hands it the task, and goes back to handling events. The child does the work, sends the result to its parent, and asks to be deleted. Nothing waits on a timer. Each step is an event that starts the next one.
|
|
4
|
+
|
|
5
|
+
The task here is counting the primes up to `n`, which is slow enough for large `n` that you can watch the children come and go in the developer UI.
|
|
6
|
+
|
|
7
|
+
To run it, follow the [instructions](/cookbook/child_tasks/instructions).
|
|
8
|
+
|
|
9
|
+
## The rulesets
|
|
10
|
+
|
|
11
|
+
| Ruleset | File | What it shows |
|
|
12
|
+
|---------|------|---------------|
|
|
13
|
+
| Task runner | [`com.example.task_runner.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/child_tasks/com.example.task_runner.krl) | `wrangler:new_child_request` with extra attributes, `wrangler:child_initialized`, installing a ruleset on a child with `event:send`, and `wrangler:child_deleted`. Has a Tasks `@view` |
|
|
14
|
+
| Task worker | [`com.example.task_worker.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/child_tasks/com.example.task_worker.krl) | Doing the work when it is installed, reporting with `event:send` to `wrangler:parent_eci()`, and deleting itself with `wrangler:ready_for_deletion` |
|
|
15
|
+
| Task runner bootstrap | [`com.example.task_runner.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/child_tasks/com.example.task_runner.bootstrap.krl) | Sets up the demo on a new pico and starts tasks for 1,000, 10,000, and 30,000. The developer UI's **Try It!** tab runs it |
|
|
16
|
+
|
|
17
|
+
## What you need
|
|
18
|
+
|
|
19
|
+
- A running pico engine (1.9.4 or later for the page, which uses the shared `PicoTheme` component).
|
|
20
|
+
- `io.picolabs.xmlui` on the task runner pico for the page. The bootstrap installs it. The workers don't need it.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Child pico tasks: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/child_tasks/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Child pico tasks**, then **Run in a new child pico**. The bootstrap starts three tasks. When it shows **ready**, open **Tasks**. The three tasks are done: 168 primes up to 1,000, 1,229 up to 10,000, and 3,245 up to 30,000. Each worker is marked "(deleted)".
|
|
8
|
+
|
|
9
|
+
## By hand
|
|
10
|
+
|
|
11
|
+
1. Create a child pico and open its **Rulesets** tab.
|
|
12
|
+
2. Install `io.picolabs.xmlui` from the engine: `http://localhost:3000/krl/io.picolabs.xmlui.krl`.
|
|
13
|
+
3. Install the task runner: `http://localhost:3000/krl/demos/child_tasks/com.example.task_runner.krl`. You don't install the worker. The runner installs it on each child from the same folder.
|
|
14
|
+
4. Installing it creates a channel tagged `task_runner, app`. Click **View** next to `com.example.task_runner` and open it on that channel.
|
|
15
|
+
|
|
16
|
+
## Try it
|
|
17
|
+
|
|
18
|
+
- Start a task with the default `n` of 20,000. It finishes in well under a second: 2,262 primes.
|
|
19
|
+
- Start one with `n` set to 200,000, which takes about ten seconds on a laptop. The table shows it as **working**. In the developer UI, the task runner pico has a child named after the task. When the task is done, the child is gone and the table says "(deleted)".
|
|
20
|
+
- Start several large tasks one after another. Each gets its own child, and the runner keeps taking new tasks while they work.
|
|
21
|
+
|
|
22
|
+
## How it works
|
|
23
|
+
|
|
24
|
+
The runner never does the work itself. It is a chain of events:
|
|
25
|
+
|
|
26
|
+
1. **`task:start`.** `start_task` records the task as `starting` and asks wrangler for a child. It passes extra attributes, the task id and `n`, along with the name:
|
|
27
|
+
|
|
28
|
+
```krl
|
|
29
|
+
raise wrangler event "new_child_request" attributes
|
|
30
|
+
{"name": "Task " + key, "task_id": key, "n": n}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
2. **`wrangler:child_initialized`.** Wrangler raises this on the parent when the child is set up. It carries the same extra attributes, plus `eci`, the parent's channel to the child. `hand_off_task` selects on it only when `task_id` is present, so it ignores children created for other reasons. Then it sends the child an `install_ruleset_request` for the worker, again with `task_id` and `n`:
|
|
34
|
+
|
|
35
|
+
```krl
|
|
36
|
+
event:send({
|
|
37
|
+
"eci": child,
|
|
38
|
+
"domain": "wrangler",
|
|
39
|
+
"type": "install_ruleset_request",
|
|
40
|
+
"attrs": {"absoluteURL": meta:rulesetURI, "rid": worker_rid, "task_id": key, "n": event:attr("n")}
|
|
41
|
+
})
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`absoluteURL: meta:rulesetURI` with a `rid` installs `com.example.task_worker.krl` from the folder the runner came from.
|
|
45
|
+
|
|
46
|
+
3. **`wrangler:ruleset_installed`, on the child.** The attributes of the install request come through on this event. `do_task` in the worker selects on its own install, counts the primes, sends `task:done` to `wrangler:parent_eci()`, and raises `wrangler:ready_for_deletion`.
|
|
47
|
+
|
|
48
|
+
4. **`task:done`, on the parent.** `task_done` records the result.
|
|
49
|
+
|
|
50
|
+
5. **`wrangler:child_deleted`, on the parent.** `ready_for_deletion` asks the parent's wrangler to delete the child. Once it is gone, wrangler raises `child_deleted` with the child's `eci`. `worker_deleted` finds the task with that `worker_eci` and marks the worker deleted.
|
|
51
|
+
|
|
52
|
+
Every pico has its own event queue. While a worker is counting, its parent can keep starting tasks, and the developer UI keeps working.
|
|
53
|
+
|
|
54
|
+
## Change it and watch
|
|
55
|
+
|
|
56
|
+
The **Try It!** window lists each file with its path on disk. Edit a file there, click **Flush**, and start a new task.
|
|
57
|
+
|
|
58
|
+
- In `com.example.task_worker.krl`, comment out `raise wrangler event "ready_for_deletion"`. Workers now stay around after they finish, and you can open one in the developer UI to see the worker ruleset and its parent channel. Delete them from the UI when you are done.
|
|
59
|
+
- Have the worker report more. Add `"largest": …` to the `task:done` attributes, store it in `task_done`, and add a column to the Tasks page in `com.example.task_runner.krl`.
|
|
60
|
+
- Give the worker a different job, such as summing the numbers up to `n`. The runner doesn't care what the work is.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# Collection
|
|
2
|
+
|
|
3
|
+
A pico that keeps track of a group of other picos is a pattern you will use often: the rooms in a building, the vehicles in a fleet, the sensors in a field. The best practice is a **relationship** with each member, labeled with roles: the collection pico plays `collection`, and each member plays `member`. Because roles label each relationship, the collection pico can have other relationships too, and tell them apart.
|
|
4
|
+
|
|
5
|
+
Keep the collection ruleset small. Its only job is managing the collection: accept members, turn away requests in other roles, remove members, and provide the members to other rulesets. Other rulesets on the same pico use the members. Here, a report ruleset asks each room for its temperature over its relationship and averages them.
|
|
6
|
+
|
|
7
|
+
To run it, follow the [instructions](/cookbook/collection/instructions). For one-to-one relationships first, see [Two picos talking](/cookbook/two_picos/).
|
|
8
|
+
|
|
9
|
+
## The rulesets
|
|
10
|
+
|
|
11
|
+
| Ruleset | File | What it shows |
|
|
12
|
+
|---------|------|---------------|
|
|
13
|
+
| Collection | [`com.example.collection.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/collection/com.example.collection.krl) | Accepting relationship requests by role and rejecting the rest (`inbound_rejection`), removing a member, raising `collection:member_added` and `member_removed`, and `provides members` for other rulesets |
|
|
14
|
+
| Room | [`com.example.collection.room.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/collection/com.example.collection.room.krl) | A member that asks to join through the collection's well-known channel, and can leave (`subscription_cancellation`) and rejoin |
|
|
15
|
+
| Room report | [`com.example.collection.report.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/collection/com.example.collection.report.krl) | `use module com.example.collection`, querying every member with `subscription:queryOnSub`, and a Rooms `@view` with a **Remove** button per member |
|
|
16
|
+
| Bootstrap | [`com.example.collection.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/collection/com.example.collection.bootstrap.krl) | Creates a Rooms collection pico and five room picos. Four join as members; Stranger asks as a visitor and is turned away. The developer UI's **Try It!** tab runs it |
|
|
17
|
+
|
|
18
|
+
## What you need
|
|
19
|
+
|
|
20
|
+
- A running pico engine (1.9.4 or later for the page, which uses the shared `PicoTheme` component).
|
|
21
|
+
- `io.picolabs.xmlui` on the collection pico for the page. The bootstrap installs it. The rooms don't need it.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Collection: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/collection/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Collection**, then **Run in a new child pico**. The bootstrap creates six children: Rooms (the collection), and Kitchen, Office, Garage, Bedroom, and Stranger. The stage counts rooms as they join. When it shows **ready**, open **Rooms**: four rooms averaging 69.5 F, and Stranger under **Turned away**.
|
|
8
|
+
|
|
9
|
+
To see what the demo built, leave the **Try It!** tab and close the pico, so the developer UI shows the pico tree. The new child has six children of its own: Rooms, the four rooms, and Stranger. Click into each one and open its **Relationships** tab. Rooms has a relationship with each of the four rooms, with Rooms in the role `collection` and each room in the role `member`. Each room has the same relationship, seen from its side. Stranger has none.
|
|
10
|
+
|
|
11
|
+
Then see if you can work out from the code why Stranger was turned away. Start with the `accept_member` rule in `com.example.collection.krl`, then look at how the bootstrap set Stranger up.
|
|
12
|
+
|
|
13
|
+
<details>
|
|
14
|
+
<summary>Why Stranger was turned away</summary>
|
|
15
|
+
|
|
16
|
+
The bootstrap gives Stranger `"as": "visitor"`. Stranger's `join` rule puts that in its request as its own role, `"Rx_role": "visitor"`. At Rooms, the request arrives from Rooms' point of view, with Stranger's role as `Tx_role`. `accept_member` accepts only `Rx_role` `collection` and `Tx_role` `member`, so it raises `wrangler:inbound_rejection`. Wrangler removes the pending request on Rooms and tells Stranger, which removes it too. That's why Stranger's **Relationships** tab is empty.
|
|
17
|
+
|
|
18
|
+
</details>
|
|
19
|
+
|
|
20
|
+
## By hand
|
|
21
|
+
|
|
22
|
+
1. Create a pico for the collection. On its **Rulesets** tab, install, in this order:
|
|
23
|
+
- `http://localhost:3000/krl/io.picolabs.xmlui.krl`
|
|
24
|
+
- `http://localhost:3000/krl/demos/collection/com.example.collection.krl`
|
|
25
|
+
- `http://localhost:3000/krl/demos/collection/com.example.collection.report.krl` (it uses the collection ruleset as a module, so install it second)
|
|
26
|
+
2. On its **Channels** tab, copy the id of the channel tagged `wellknown_rx, tx_rx`.
|
|
27
|
+
3. Create a pico for each room and install `http://localhost:3000/krl/demos/collection/com.example.collection.room.krl` on it.
|
|
28
|
+
4. On each room's **Testing** tab, raise `room` `new_temperature` with a `temperature`, then `collection` `join_requested` with `wellKnown_Tx` set to the id from step 2.
|
|
29
|
+
5. To see a request turned away, raise `join_requested` on one room with `as` set to `visitor` as well.
|
|
30
|
+
6. Open the report on the collection's `collection, app` channel (**View** next to `com.example.collection.report`).
|
|
31
|
+
|
|
32
|
+
## Try it
|
|
33
|
+
|
|
34
|
+
- Click **Remove** next to a room. The collection cancels that relationship, and the room leaves the table and the average.
|
|
35
|
+
- Open Office in the developer UI. On its **Testing** tab, raise `collection` `leave_requested`. Office leaves the table. The member ended the relationship this time.
|
|
36
|
+
- Still on Office, raise `room` `new_temperature` with `temperature` set to `80`, then `collection` `rejoin_requested`. Office is back, at 80 F.
|
|
37
|
+
- Look at the **Relationships** tab on Rooms and on a room. Each side has its own channel, and the roles say who is who.
|
|
38
|
+
|
|
39
|
+
## How it works
|
|
40
|
+
|
|
41
|
+
**Members are relationships.** The collection ruleset doesn't keep a list. Its members are its relationships in which the other pico is a member:
|
|
42
|
+
|
|
43
|
+
```krl
|
|
44
|
+
members = function() {
|
|
45
|
+
subscription:established("Tx_role", "member")
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
It `provides members`, so another ruleset on the pico can `use module com.example.collection` and call `collection:members()`.
|
|
50
|
+
|
|
51
|
+
**Joining.** A room asks through the collection's well-known channel, naming both roles: `Rx_role` `member` for itself, `Tx_role` `collection` for the other side. The request arrives at the collection with the roles from its point of view. `accept_member` accepts it only in the right roles, and otherwise rejects it and remembers who asked:
|
|
52
|
+
|
|
53
|
+
```krl
|
|
54
|
+
rule accept_member {
|
|
55
|
+
select when wrangler inbound_pending_subscription_added
|
|
56
|
+
pre {
|
|
57
|
+
acceptable = event:attr("Rx_role") == "collection" && event:attr("Tx_role") == "member"
|
|
58
|
+
}
|
|
59
|
+
if acceptable then noop()
|
|
60
|
+
fired {
|
|
61
|
+
raise wrangler event "pending_subscription_approval" attributes event:attrs
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
ent:rejections := rejections().append({"name": event:attr("name"), "role": event:attr("Tx_role"), "time": time:now()})
|
|
65
|
+
raise wrangler event "inbound_rejection" attributes event:attrs
|
|
66
|
+
raise collection event "member_rejected" attributes event:attrs
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
A role is what the requesting pico says it is. Stranger could ask again as a member and be accepted. Roles sort relationships; they don't prove anything. A collection that must be choosy checks something it trusts as well, such as who introduced the pico, as the bootstrap does by sending each room the well-known channel.
|
|
72
|
+
|
|
73
|
+
**Leaving.** Either side can end a relationship with `wrangler:subscription_cancellation` and its `Id`. Both picos remove it, and both raise `wrangler:subscription_removed`. The collection turns that, and `subscription_added`, into its own `collection:member_removed` and `collection:member_added` events, for any ruleset that cares. `remove_member` only cancels relationships that are memberships, so the page's channel can't end any other relationship the pico has.
|
|
74
|
+
|
|
75
|
+
**Reporting.** The report asks each member for its `reading` over its relationship:
|
|
76
|
+
|
|
77
|
+
```krl
|
|
78
|
+
readingOf = function(bus) {
|
|
79
|
+
reading = subscription:queryOnSub(bus{"Id"}, room_rid, "reading")
|
|
80
|
+
row = {"Id": bus{"Id"}, "name": reading{"name"}, "temperature": reading{"temperature"}}
|
|
81
|
+
row
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**The bootstrap.** It creates Rooms first. When Rooms is initialized, it sends Rooms its three install requests, then creates the room picos. For each room, it sends the room ruleset install request, then `collection:join_requested`. A pico handles events one at a time, in the order they arrive, so each ruleset is installed before the event that needs it. Because the requests to Rooms were sent before any room existed, the collection is ready before the first request to join arrives.
|
|
86
|
+
|
|
87
|
+
## Change it and watch
|
|
88
|
+
|
|
89
|
+
The **Try It!** window lists each file with its path on disk. Edit a file there, click **Flush**, and use the page.
|
|
90
|
+
|
|
91
|
+
- Report the warmest room too: in `com.example.collection.report.krl`, add the room with the highest temperature to the map `report()` returns, and show it in the subtitle.
|
|
92
|
+
- Accept visitors as well: in `com.example.collection.krl`, let `accept_member` also accept `Tx_role` `visitor`, and add a `visitors()` function like `members()`. Then on Stranger's **Testing** tab, raise `collection` `join_requested` with `wellKnown_Tx` (Rooms' well-known channel id) and `as` set to `visitor`. Stranger is accepted, and it is not counted in the report, which only asks members.
|
|
93
|
+
- Have the collection react to new members: add a rule that selects `collection:member_added` and records when each member joined.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Echo
|
|
2
|
+
|
|
3
|
+
The smallest useful pico: it answers events. An event arrives on a channel, a rule selects on it, and the rule's action is a **directive**, a named piece of data returned to whoever sent the event. Echo has two rules. `echo:hello` answers "Hello World", and `echo:message` answers with whatever `input` it was sent.
|
|
4
|
+
|
|
5
|
+
A page served by the pico sends both events and shows the answer. The same events work from `curl`, which shows that a pico's events are plain HTTP.
|
|
6
|
+
|
|
7
|
+
To run it, follow the [instructions](/cookbook/echo/instructions).
|
|
8
|
+
|
|
9
|
+
## The rulesets
|
|
10
|
+
|
|
11
|
+
| Ruleset | File | What it shows |
|
|
12
|
+
|---------|------|---------------|
|
|
13
|
+
| Echo | [`com.example.echo.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/echo/com.example.echo.krl) | `select when` with an attribute regex, `send_directive`, and a `@view` that reads directives from the event response. Creates an app channel that allows only `echo` events |
|
|
14
|
+
| Echo bootstrap | [`com.example.echo.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/echo/com.example.echo.bootstrap.krl) | Sets up the demo on a new pico. The developer UI's **Try It!** tab runs it |
|
|
15
|
+
|
|
16
|
+
## What you need
|
|
17
|
+
|
|
18
|
+
- A running pico engine (1.9.4 or later for the page, which uses the shared `PicoTheme` component).
|
|
19
|
+
- `io.picolabs.xmlui` on the pico for the page. The bootstrap installs it.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Echo: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/echo/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Echo**, then **Run in a new child pico**. When it shows **ready**, open **Echo page**.
|
|
8
|
+
|
|
9
|
+
## By hand
|
|
10
|
+
|
|
11
|
+
1. Create a child pico and open its **Rulesets** tab.
|
|
12
|
+
2. Install `io.picolabs.xmlui` from the engine: `http://localhost:3000/krl/io.picolabs.xmlui.krl`.
|
|
13
|
+
3. Install the echo ruleset: `http://localhost:3000/krl/demos/echo/com.example.echo.krl` (the engine's copy), or the raw GitHub file `https://raw.githubusercontent.com/Picolab/pico-engine/master/demos/echo/com.example.echo.krl`.
|
|
14
|
+
4. Installing it creates a channel tagged `echo, app`. Click **View** next to `com.example.echo` and open it on that channel.
|
|
15
|
+
|
|
16
|
+
## Try it
|
|
17
|
+
|
|
18
|
+
- Click **Say hello**. The page raises `echo:hello`, and the **The pico said** card shows `Hello World`.
|
|
19
|
+
- Type a message and click **Echo it**. The pico answers with your message.
|
|
20
|
+
- Copy the `curl` line at the bottom of the page into a terminal. The engine answers with JSON like this:
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{"eid": "...", "directives": [{"type": "directive", "name": "say", "options": {"something": "hello"},
|
|
24
|
+
"meta": {"rid": "com.example.echo", "rule_name": "echo", "txnId": "..."}}],
|
|
25
|
+
"ruleOutcomes": [{"rid": "com.example.echo", "rule": "echo", "status": "fired"}]}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- Change `echo/message` in that URL to `wrangler/new_child_request?name=x`. The answer is `{"error":"Error: Not allowed by channel policy"}`: this channel accepts only `echo` events.
|
|
29
|
+
- On the pico's **Testing** tab, raise `echo` `hello` and look at the response.
|
|
30
|
+
|
|
31
|
+
## How it works
|
|
32
|
+
|
|
33
|
+
An event has a domain and a type (`echo` and `message`) and some attributes. A rule's `select when` decides which events it runs on:
|
|
34
|
+
|
|
35
|
+
```krl
|
|
36
|
+
rule echo {
|
|
37
|
+
select when echo message input re#(.*)# setting(m)
|
|
38
|
+
send_directive("say", {"something": m})
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`input re#(.*)#` matches the `input` attribute against a regular expression, and `setting(m)` binds what it captured. `send_directive` adds a directive to the response. The engine collects the directives of every rule that ran and returns them to the sender, which is how the page and `curl` see the answer.
|
|
43
|
+
|
|
44
|
+
The page is a `@view` function. Its `APICall` posts the event and reads the answer from the response:
|
|
45
|
+
|
|
46
|
+
```xml
|
|
47
|
+
<APICall id="hello" method="post" url="#{hello_url}" headers="{appGlobals.auth}"
|
|
48
|
+
onSuccess="(result) => reply = result.directives[0].options.something" />
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
On install, `ui:create_app_channel` makes the `echo, app` channel. Its policy allows events in the `echo` domain and the page's queries, and nothing else. Someone holding that channel can make the pico echo but cannot change it.
|
|
52
|
+
|
|
53
|
+
## Change it and watch
|
|
54
|
+
|
|
55
|
+
The **Try It!** window lists each file with its path on disk. Edit `com.example.echo.krl` there, click **Flush**, and reload the page.
|
|
56
|
+
|
|
57
|
+
- Change `"Hello World"` in `hello_world` to your own greeting.
|
|
58
|
+
- Make the echo shout: `send_directive("say", {"something": m.uc()})`.
|
|
59
|
+
- Add a rule that answers a new event, such as `echo goodbye`. The app channel already allows every `echo` event, so the page and `curl` can send it right away.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Guard rules
|
|
2
|
+
|
|
3
|
+
Events can arrive more than once: a person clicks twice, a script retries, two picos ask for the same thing. A rule that reacts to an event is **idempotent** when running it again has no further effect. A **guard rule** is the usual way to get there. It responds to the event, tests a condition, and only then raises the event that a second rule listens for to do the real work.
|
|
4
|
+
|
|
5
|
+
This demo's pico needs exactly one child pico, its Archive. Ask for the archive as often as you like: the guard lets one request through.
|
|
6
|
+
|
|
7
|
+
It also shows a **gate rule**: a rule placed before others that selects the same event, and stops them with `last` when they can't run yet. Here, notes go into the archive, so the gate refuses them until the archive exists. This is the shape of the "authorize, then use" pattern, where the gate starts an authorization instead of refusing.
|
|
8
|
+
|
|
9
|
+
To run it, follow the [instructions](/cookbook/guard_rules/instructions).
|
|
10
|
+
|
|
11
|
+
## The rulesets
|
|
12
|
+
|
|
13
|
+
| Ruleset | File | What it shows |
|
|
14
|
+
|---------|------|---------------|
|
|
15
|
+
| Archive keeper | [`com.example.archive.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/guard_rules/com.example.archive.krl) | The guard rule `archive_needed` and the rule it raises an event for, the gate rule `require_archive` with `last`, and an Archive `@view` that counts requests |
|
|
16
|
+
| Archive store | [`com.example.archive_store.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/guard_rules/com.example.archive_store.krl) | Installed on the Archive child; keeps the notes and shares them |
|
|
17
|
+
| Bootstrap | [`com.example.archive.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/guard_rules/com.example.archive.bootstrap.krl) | Sets up the demo, asks for the archive five times, and adds a note before and after the archive exists. The developer UI's **Try It!** tab runs it |
|
|
18
|
+
|
|
19
|
+
## What you need
|
|
20
|
+
|
|
21
|
+
- A running pico engine (1.9.4 or later for the page, which uses the shared `PicoTheme` component).
|
|
22
|
+
- `io.picolabs.xmlui` on the pico for the page. The bootstrap installs it.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Guard rules: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/guard_rules/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Guard rules**, then **Run in a new child pico**. The bootstrap raises `archive:needed` five times in a row and adds a note before the archive exists. When it shows **ready**, open **Archive**. The counts read: 1 archive pico, 5 requests, 4 ignored, 1 note refused. The archive holds the one note added after it was created.
|
|
8
|
+
|
|
9
|
+
## By hand
|
|
10
|
+
|
|
11
|
+
1. Create a child pico and open its **Rulesets** tab.
|
|
12
|
+
2. Install `io.picolabs.xmlui` from the engine: `http://localhost:3000/krl/io.picolabs.xmlui.krl`.
|
|
13
|
+
3. Install the archive keeper: `http://localhost:3000/krl/demos/guard_rules/com.example.archive.krl`. It installs `com.example.archive_store` on the Archive child itself, from the same folder.
|
|
14
|
+
4. Installing it creates a channel tagged `archive, app`. Click **View** next to `com.example.archive` and open it on that channel.
|
|
15
|
+
|
|
16
|
+
## Try it
|
|
17
|
+
|
|
18
|
+
- Click **Add a note** before anything else. The gate refuses it: "Note: refused, no archive yet".
|
|
19
|
+
- Click **Request the archive**. "Guard: go ahead", and in a moment the archive is **ready**. The pico has a child named Archive.
|
|
20
|
+
- Click **Request the archive** again, several times. Each one says "Guard: already have one, ignored". **Requests** and **Ignored** go up; **Archive picos** stays at 1.
|
|
21
|
+
- Add a note. It is stored in the Archive child and listed on the page.
|
|
22
|
+
- **Start over** deletes the archive and resets the counts.
|
|
23
|
+
|
|
24
|
+
## How it works
|
|
25
|
+
|
|
26
|
+
**The guard.** `archive_needed` answers every `archive:needed` event, but raises `archive:creation_approved` only when there is no archive and none is being created:
|
|
27
|
+
|
|
28
|
+
```krl
|
|
29
|
+
rule archive_needed {
|
|
30
|
+
select when archive needed
|
|
31
|
+
pre {
|
|
32
|
+
allowed = not ent:archive_eci && not ent:creating
|
|
33
|
+
}
|
|
34
|
+
if allowed then send_directive("archive", {"result": "creating"})
|
|
35
|
+
fired {
|
|
36
|
+
ent:creating := true
|
|
37
|
+
raise archive event "creation_approved"
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
ent:ignored := ent:ignored.defaultsTo(0) + 1
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
ent:requests := ent:requests.defaultsTo(0) + 1
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`create_archive` selects `archive:creation_approved` and asks wrangler for the child. Nothing else raises that event, so the work happens once. When wrangler raises `child_initialized`, `archive_initialized` records the archive, installs the store ruleset on it, and raises `archive:archive_created`.
|
|
49
|
+
|
|
50
|
+
**Why `ent:creating`.** The archive doesn't exist until `child_initialized` arrives, which is a separate event that comes later. The five requests the bootstrap raises are all handled before then. Checking only `ent:archive_eci` would let all five through. The flag is set the moment the guard approves, so the second request already sees it.
|
|
51
|
+
|
|
52
|
+
**The gate.** `require_archive` and `store_note` both select `archive:note_added`. Rules in one ruleset that select the same event run in the order they are written, so the gate runs first. When there is no archive, it answers and runs `last`:
|
|
53
|
+
|
|
54
|
+
```krl
|
|
55
|
+
rule require_archive {
|
|
56
|
+
select when archive note_added
|
|
57
|
+
if not ent:archive_eci then send_directive("note", {"result": "refused, no archive yet"})
|
|
58
|
+
fired {
|
|
59
|
+
ent:gated := ent:gated.defaultsTo(0) + 1
|
|
60
|
+
last
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`last` stops the rest of this ruleset's rules for this event, so `store_note` doesn't run. It doesn't stop rules in other rulesets, which is why the gate and the rule it guards are in the same ruleset.
|
|
66
|
+
|
|
67
|
+
## Change it and watch
|
|
68
|
+
|
|
69
|
+
The **Try It!** window lists each file with its path on disk. Edit `com.example.archive.krl` there, click **Flush**, and use the page.
|
|
70
|
+
|
|
71
|
+
- Remove the flag from the guard: make it `allowed = not ent:archive_eci`. Click **Start over**, then run the demo again from **Try It!**: the five quick requests now make five Archive picos. Put the flag back.
|
|
72
|
+
- Move `require_archive` below `store_note` in the file. Click **Start over**, then **Add a note**. Nothing is stored and the event fails with `TypeError: eci was null instead of a string` (in the response, and on the **Logging** tab): `store_note` ran first and tried to send the note to an archive that doesn't exist. Move it back.
|
|
73
|
+
- Give the guard a second condition, such as a limit of three notes per archive, by adding a guard rule for `note_added` in the same style.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Querying JSON
|
|
2
|
+
|
|
3
|
+
Picos often hold large, nested data: API responses, sensor histories, a fleet's trips and fill-ups. KRL's [`query()`](/krl/krl-expression-language/operators/query-operator) operator finds values in that data with a [JSONPath](https://www.rfc-editor.org/rfc/rfc9535) expression, instead of a chain of `get()`, `map()`, and `filter()` calls.
|
|
4
|
+
|
|
5
|
+
This demo's pico holds the vehicles, trips, and fill-ups of a small fleet, the kind of data Fuse, a pico-based connected-car platform, kept for each vehicle. Its page shows the data and runs four queries against it, each showing a different part of JSONPath. You can also type your own.
|
|
6
|
+
|
|
7
|
+
| Query | Path | Shows |
|
|
8
|
+
|-------|------|-------|
|
|
9
|
+
| Every vehicle's name | `$.vehicles[*].name` | Child selectors and the wildcard |
|
|
10
|
+
| All the miles, at any depth | `$..miles` | The descendant selector |
|
|
11
|
+
| Business trips over 25 miles | `$.vehicles[*].trips[?@.category == 'business' && @.miles > 25]` | A filter with two tests |
|
|
12
|
+
| Each vehicle's latest fill-up | `$.vehicles[?count(@.fillups[*]) > 0].fillups[-1]` | A filter function and a negative index |
|
|
13
|
+
|
|
14
|
+
To run it, follow the [instructions](/cookbook/json_query/instructions).
|
|
15
|
+
|
|
16
|
+
## The rulesets
|
|
17
|
+
|
|
18
|
+
| Ruleset | File | What it shows |
|
|
19
|
+
|---------|------|---------------|
|
|
20
|
+
| Querying JSON | [`com.example.json_query.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/json_query/com.example.json_query.krl) | The data as a global map, `query()` in a shared function, and a `@view` that sends the path as a query parameter and shows the results. Creates an app channel that allows the page's queries and no events |
|
|
21
|
+
| Querying JSON bootstrap | [`com.example.json_query.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/json_query/com.example.json_query.bootstrap.krl) | Sets up the demo on a new pico. The developer UI's **Try It!** tab runs it |
|
|
22
|
+
|
|
23
|
+
## What you need
|
|
24
|
+
|
|
25
|
+
- A running pico engine with the `query()` operator (after 1.9.5).
|
|
26
|
+
- `io.picolabs.xmlui` on the pico for the page. The bootstrap installs it.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# Querying JSON: instructions
|
|
2
|
+
|
|
3
|
+
These steps use the developer UI of a running engine at `http://localhost:3000`. Replace that with your engine's URL. See the [overview](/cookbook/json_query/) for what the demo shows.
|
|
4
|
+
|
|
5
|
+
## The quick way: Try It!
|
|
6
|
+
|
|
7
|
+
On the root pico in the developer UI, open the **Try It!** tab, click **Querying JSON**, then **Run in a new child pico**. When it shows **ready**, open **Query page**.
|
|
8
|
+
|
|
9
|
+
## By hand
|
|
10
|
+
|
|
11
|
+
1. Create a child pico and open its **Rulesets** tab.
|
|
12
|
+
2. Install `io.picolabs.xmlui` from the engine: `http://localhost:3000/krl/io.picolabs.xmlui.krl`.
|
|
13
|
+
3. Install the demo ruleset: `http://localhost:3000/krl/demos/json_query/com.example.json_query.krl`.
|
|
14
|
+
4. Installing it creates a channel tagged `json_query, app`. Click **View** next to `com.example.json_query` and open it on that channel.
|
|
15
|
+
|
|
16
|
+
## Try it
|
|
17
|
+
|
|
18
|
+
- Click **Show the JSON**. The fleet data appears beside the queries.
|
|
19
|
+
- Click each query button. The card shows the path, what it uses, and the values `query()` found.
|
|
20
|
+
- Type your own path and click **Run it**:
|
|
21
|
+
- `$.owner.email`: one value, still in an array
|
|
22
|
+
- `$.vehicles[?@.year > 2020].name`: a filter on a number
|
|
23
|
+
- `$..cost`: every trip's cost
|
|
24
|
+
- `$.vehicles[0].trips[-1:]`: the last trip of the first vehicle, as a slice
|
|
25
|
+
- `$.vehicles[?match(@.make, 'T.*')].model`: a regular expression
|
|
26
|
+
- `$.nope`: no match, an empty array
|
|
27
|
+
- Type a broken path such as `$.vehicles[?@.year >`. The pico answers with the parse error.
|
|
28
|
+
- Run a query from a terminal. The path has to be URL-encoded:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
curl "http://localhost:3000/sky/query/<eci>/com.example.json_query/runQuery?path=%24..miles"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## How it works
|
|
35
|
+
|
|
36
|
+
The data is a map in the ruleset's `global` block, and one shared function queries it:
|
|
37
|
+
|
|
38
|
+
```krl
|
|
39
|
+
runQuery = function(path) {
|
|
40
|
+
result = fleet.query(path)
|
|
41
|
+
answer = {"path": path, "count": result.length(), "result": result}
|
|
42
|
+
answer
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`query()` always returns an array, even for one match, and an empty array when nothing matches. An invalid path is an error, which the engine returns to the page as `{"error": …}`.
|
|
47
|
+
|
|
48
|
+
The page fetches `runQuery` with a `DataSource` whose `queryParams` send the path. `DataSource` URL-encodes it, which matters because JSONPath uses `$`, `?`, `&&`, and quotes:
|
|
49
|
+
|
|
50
|
+
```xml
|
|
51
|
+
<DataSource id="run" url="#{run_url}" headers="{appGlobals.auth}" queryParams="{{path: path}}" when="{path}" />
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Each button sets `path`, and the `DataSource` fetches again whenever `path` changes. The canned queries come from another shared function, `cannedQueries()`, so the page doesn't have to put JSONPath strings in XML attributes.
|
|
55
|
+
|
|
56
|
+
The JSON is shown with `JSON.stringify(value, null, 2)` in a `Text` with `variant="mono"` and `preserveLinebreaks`.
|
|
57
|
+
|
|
58
|
+
## Change it and watch
|
|
59
|
+
|
|
60
|
+
The **Try It!** window lists each file with its path on disk. Edit `com.example.json_query.krl` there, click **Flush**, and reload the page.
|
|
61
|
+
|
|
62
|
+
- Add a fifth entry to `cannedQueries()`, for example the total of fuel bought: `$.vehicles[*].fillups[*].gallons`. Then sum the result in KRL with `.reduce(function(a, b) { a + b }, 0)`.
|
|
63
|
+
- Add a vehicle to `fleet`, and run the queries again.
|
|
64
|
+
- Write a function that uses `query()` for something useful, such as the business miles of one vehicle: `fleet.query("$.vehicles[?@.name == '" + name + "'].trips[?@.category == 'business'].miles")`. See the [`query()` page](/krl/krl-expression-language/operators/query-operator) on checking values before putting them in a path.
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# KBlog
|
|
2
|
+
|
|
3
|
+
A blog written in KRL, built from four rulesets on one pico. No ruleset knows how the others work. They cooperate by raising events, and each rule does one thing:
|
|
4
|
+
|
|
5
|
+
- **Pages** (`com.example.kblog`): Home, a page for each article, Contact, and Post.
|
|
6
|
+
- **Data** (`com.example.kblog.data`): stores the articles and provides them.
|
|
7
|
+
- **Posting** (`com.example.kblog.posting`): checks each post an author submits and passes it on.
|
|
8
|
+
- **Configuration** (`com.example.kblog.config`): the title and the fixed text.
|
|
9
|
+
|
|
10
|
+
Readers and authors use different channels on the same pico. The reader channel opens every page except Post and accepts no events. The author channel, which the posting ruleset creates when it is installed, adds the Post page and exactly two events. Each time an author posts, the Post page shows the path the post took through the rulesets.
|
|
11
|
+
|
|
12
|
+
To run it, follow the [instructions](/cookbook/kblog/instructions).
|
|
13
|
+
|
|
14
|
+
## The event hierarchy
|
|
15
|
+
|
|
16
|
+
Events are nouns: they say what happened. Rules are verbs: they say what the pico does about it. The write side of KBlog is a chain of them:
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
kblog:post_submitted (from the author channel)
|
|
20
|
+
├─ handle_submit posting ──▶ kblog:new_article_available
|
|
21
|
+
│ └─ add_article data ──▶ kblog:new_article_added
|
|
22
|
+
│ └─ show_new_article pages ──▶ kblog:front_page_updated
|
|
23
|
+
└─ reject_submit posting (no name or title: nothing is added)
|
|
24
|
+
|
|
25
|
+
kblog:clear_requested (from the author channel)
|
|
26
|
+
└─ clear_articles data ──▶ kblog:articles_cleared
|
|
27
|
+
└─ show_empty_blog pages ──▶ kblog:front_page_updated
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Every rule that changes something raises an event saying what is now true, even when nothing listens yet (`front_page_updated`). A ruleset added later can react without anyone editing these.
|
|
31
|
+
|
|
32
|
+
The read side is queries, not events. The Home page calls `articles()` and an article page calls `article(id)`, which the pages ruleset gets from the data ruleset as a module.
|
|
33
|
+
|
|
34
|
+
## From the 2011 KBlog
|
|
35
|
+
|
|
36
|
+
The [original KBlog](https://github.com/windley/KBlog) ran on the classic engine, which raised events from a browser and let rules paint the page. Its design is described in [Event Hierarchies: A Blog Written in KRL](https://www.windley.com/archives/2011/04/event_hierarchies_a_blog_written_in_krl.shtml). This version keeps its rulesets, rule names, and events where they still make sense:
|
|
37
|
+
|
|
38
|
+
| 2011 | Now |
|
|
39
|
+
|------|-----|
|
|
40
|
+
| KBlog (`a16x88`) painted the page with `replace_html` in response to `pageview` and `web:click` | `com.example.kblog` serves XMLUI pages. Navigation and the back button come from the page routes (`/`, `/post/:id`, `/contact`, `/new`) |
|
|
41
|
+
| `show_home` raised `need_blog_data`; KBlog Data answered with `blog_data_ready` carrying the articles | The page queries `articles()`. Reading is a query; writing stays a chain of events |
|
|
42
|
+
| KBlog Data (`a16x89`) kept the articles in an application variable | `com.example.kblog.data` keeps them in an entity variable on the blog pico. `add_article` and `new_article_added` are unchanged |
|
|
43
|
+
| KBlog Posting (`a16x90`) ran only for people who had installed it in their browser | `com.example.kblog.posting` creates the author channel. The channel's policy, not who has the code, decides who can post |
|
|
44
|
+
| KBlog Configuration (`a16x93`) provided the title, about text, and shared actions | `com.example.kblog.config` provides the title and text. The page layout is a component (`BlogAbout`) |
|
|
45
|
+
| KBlog Tweeter (`a16x91`) tweeted new posts | Left out. A ruleset that selects `kblog:new_article_added` would be its place |
|
|
46
|
+
|
|
47
|
+
## The rulesets
|
|
48
|
+
|
|
49
|
+
| Ruleset | File | What it shows |
|
|
50
|
+
|---------|------|---------------|
|
|
51
|
+
| Pages | [`com.example.kblog.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/kblog/com.example.kblog.krl) | Four `@view`s with routes, including a detail page (`/post/:id`); a `@component` used on every page; Markdown rendered safely from data; a page whose form comes from another ruleset; the reader channel |
|
|
52
|
+
| Data | [`com.example.kblog.data.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/kblog/com.example.kblog.data.krl) | One ruleset owning the data: rules that change it raise events, and `provides` lets other rulesets read it |
|
|
53
|
+
| Posting | [`com.example.kblog.posting.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/kblog/com.example.kblog.posting.krl) | Checking input before raising the internal event; a `@component` another ruleset's page shows; a channel policy that names single events |
|
|
54
|
+
| Configuration | [`com.example.kblog.config.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/kblog/com.example.kblog.config.krl) | A module of settings other rulesets use |
|
|
55
|
+
| Bootstrap | [`com.example.kblog.bootstrap.krl`](https://github.com/Picolab/pico-engine/blob/master/demos/kblog/com.example.kblog.bootstrap.krl) | Installing rulesets in dependency order, each on the previous one's `ruleset_installed`, then submitting three posts. The developer UI's **Try It!** tab runs it |
|
|
56
|
+
|
|
57
|
+
## What you need
|
|
58
|
+
|
|
59
|
+
- A running pico engine (1.9.4 or later: the pages use components).
|
|
60
|
+
- `io.picolabs.xmlui` on the blog pico. The bootstrap installs it.
|