on master help sign in
update eyre documentation

removes old documentation and adds a scry ref, data types ref, external & internal api ref, and examples.

commitebf879c4da247be2b6a5d6c973a7e6b619deec26 authortinnus-napbus <admin@tinnus-napbus.xyz> dateWed 9 Jun 2021, 00:11 (5 years ago) parentf99a557
9 files changed+1899−925
arvo/eyre/_index.md+18−3 arvo/eyre/data-types.md+290 arvo/eyre/examples.md+689 arvo/eyre/external-api-ref.md+399 arvo/eyre/eyre.md+26−690 arvo/eyre/scry.md+233 arvo/eyre/tasks.md+243 arvo/eyre/using-eyre.md−230 development/develop.md+1−2
arvo/eyre/_index.md+18−3
@@ -8,9 +8,24 @@ insert_anchor_links = "right"
88
99## [Overview](@/docs/arvo/eyre/eyre.md)
1010
11−A high-level overview of `eyre`, Urbit's HTTP server vane.
11+An overview of Eyre and its capabilities.
1212
13−## [Using Eyre](@/docs/arvo/eyre/using-eyre.md)
13+## [External API Reference](@/docs/arvo/eyre/external-api-ref.md)
1414
15−How to use Urbit's HTTP API.
15+Details of Eyre's external API including the channel system's JSON API.
1616
17+## [Internal API Reference](@/docs/arvo/eyre/tasks.md)
18+
19+The tasks Eyre takes and the gifts it returns.
20+
21+## [Scry Reference](@/docs/arvo/eyre/scry.md)
22+
23+The scry endpoints of Eyre.
24+
25+## [Data Types](@/docs/arvo/eyre/data-types.md)
26+
27+Reference documentation of the various data types used by Eyre.
28+
29+## [Examples](@/docs/arvo/eyre/examples.md)
30+
31+Practical examples of the different ways of using Eyre.
arvo/eyre/data-types.mdnew file+290
@@ -0,0 +1,290 @@
1++++
2+title = "Data Types"
3+weight = 5
4+template = "doc.html"
5++++
6+
7+# Introduction
8+
9+This document describes the data types used by Eyre as defined in `/sys/lull.hoon`. It's separated into two sections:
10+
11+- [Eyre](#eyre) - Eyre-specific data types.
12+- [HTTP](#http) - HTTP data types shared between Eyre and Iris.
13+
14+# Eyre
15+
16+## `$origin`
17+
18+```hoon
19++$ origin @torigin
20+```
21+
22+A single CORS origin as used in an HTTP Origin header and the [$cors-registry](#cors-registry).
23+
24+## `$cors-registry`
25+
26+```hoon
27++$ cors-registry
28+ $: requests=(set origin)
29+ approved=(set origin)
30+ rejected=(set origin)
31+ ==
32+```
33+
34+CORS origins categorised by approval status. The `requests` `set` contains all [$origin](#origin)s Eyre has received in the headers of HTTP requests that have not been explicitly approved or rejected. The `approved` and `rejected` `set`s are those that have been explicitly approved or rejected.
35+
36+## `$outstanding-connection`
37+
38+```hoon
39++$ outstanding-connection
40+ $: =action
41+ =inbound-request
42+ response-header=(unit response-header:http)
43+ bytes-sent=@ud
44+ ==
45+```
46+
47+An HTTP connection that is currently open. The [$action](#action) is how it's being handled (e.g. by a gall app, the channel system, etc). The [$inbound-request](#inbound-request) is the original request which opened the connection. The `response-header` contains the status code and headers of the initial response. The `bytes-sent` is the total bytes sent so far in response.
48+
49+## `$authentication-state`
50+
51+```hoon
52++$ authentication-state sessions=(map @uv session)
53+```
54+
55+This represents the authentication state of all sessions. It maps session cookies (without the `urbauth-<ship>=` prefix) to [$session](#session)s.
56+
57+## `$session`
58+
59+```hoon
60++$ session
61+ $: expiry-time=@da
62+ channels=(set @t)
63+ ==
64+```
65+
66+This represents server-side data about a session. The `expiry-time` is when the `session` expires and `channels` is the `set` of [$channel](#channel) names opened by the session.
67+
68+## `$channel-state`
69+
70+```hoon
71++$ channel-state
72+ $: session=(map @t channel)
73+ duct-to-key=(map duct @t)
74+ ==
75+```
76+
77+The state used by the channel system. The `session` is a `map` between channel names and [$channel](#channel)s and the `duct-to-key` `map`s `duct`s to `channel` names.
78+
79+## `$timer`
80+
81+```hoon
82++$ timer
83+ $: date=@da
84+ =duct
85+ ==
86+```
87+
88+A reference to a timer so it can be cancelled or updated. The `date` is when it will fire and the `duct` is what set the timer.
89+
90+## `$channel-event`
91+
92+```hoon
93++$ channel-event
94+ $% $>(%poke-ack sign:agent:gall)
95+ $>(%watch-ack sign:agent:gall)
96+ $>(%kick sign:agent:gall)
97+ [%fact =mark =noun]
98+ ==
99+```
100+
101+An unacknowledged event in the channel system.
102+
103+## `$channel`
104+
105+```hoon
106++$ channel
107+ $: state=(each timer duct)
108+ next-id=@ud
109+ last-ack=@da
110+ events=(qeu [id=@ud request-id=@ud =channel-event])
111+ unacked=(map @ud @ud)
112+ subscriptions=(map @ud [ship=@p app=term =path duc=duct])
113+ heartbeat=(unit timer)
114+ ==
115+```
116+
117+This is the state of a particular channel in the channel system. The `state` is either the expiration time or the duct currently listening. The `next-id` is the next event ID to be used in the event stream. The `last-ack` is the date of the last client ack and is used for clog calculations in combination with `unacked`. The `events` queue contains all unacked events - `id` is the server-set event ID, `request-id` is the client-set request ID and the [$channel-event](#channel-event) is the event itself. The `unacked` `map` contains the unacked event count per `request-id` and is used for clog calculations. The `subscriptions` `map` contains gall subscriptions by `request-id`. The `heartbeat` is the SSE heartbeat [$timer](#timer).
118+
119+## `$binding`
120+
121+```hoon
122++$ binding
123+ $: site=(unit @t)
124+ path=(list @t)
125+ ==
126+```
127+
128+A `binding` is a rule to match a URL `path` and optional `site` domain which can then be tied to an [$action](#action). A `path` of `/foo` will also match `/foo/bar`, `/foo/bar/baz`, etc. If the `site` is `~` it will be determined implicitly. A binding must be unique.
129+
130+## `$action`
131+
132+```hoon
133++$ action
134+ $% [%gen =generator] :: dispatch to a generator
135+ [%app app=term] :: dispatch to an application
136+ [%authentication ~] :: internal authentication page
137+ [%logout ~] :: internal logout page
138+ [%channel ~] :: gall channel system
139+ [%scry ~] :: gall scry endpoint
140+ [%four-oh-four ~] :: respond with the default file not found page
141+ ==
142+```
143+
144+The action to take when a [$binding](#binding) matches an incoming HTTP request.
145+
146+## `$generator`
147+
148+```hoon
149++$ generator
150+ $: =desk :: desk on current ship that contains the generator
151+ path=(list @t) :: path on :desk to the generator's hoon file
152+ args=* :: args: arguments passed to the gate
153+ ==
154+```
155+
156+This refers to a generator on a local ship that can handle requests. Note that serving generators via Eyre is not fully implmented and should not be used.
157+
158+## `$http-config`
159+
160+```hoon
161++$ http-config
162+ $: secure=(unit [key=wain cert=wain])
163+ proxy=_|
164+ log=?
165+ redirect=?
166+ ==
167+```
168+
169+The configuration of the http server itself. The `secure` field contains the PEM-encoded RSA private key and certificate or certificate chain if using HTTPS, otherwise is `~` for plain HTTP. The `proxy` field is not currently used. The `log` field turns on HTTP(s) access logs but is not currently implemented. The `redirect` field turns on 301 redirects to upgrade HTTP to HTTPS if the `key` and `cert` are set in `secure`.
170+
171+## `$http-rule`
172+
173+```hoon
174++$ http-rule
175+ $% [%cert cert=(unit [key=wain cert=wain])]
176+ [%turf action=?(%put %del) =turf]
177+ ==
178+```
179+
180+This is for updating the server configuration. In the case of `%cert`, a `cert` of `~` clears the HTTPS cert & key, otherwise `cert` contains the PEM-encoded RSA private key and certificate or certificate chain. In the case of `%turf`, a `%put` `action` sets a domain name and a `%del` `action` removes it. The [$turf](#turf) contains the domain name.
181+
182+## `$address`
183+
184+```hoon
185++$ address
186+ $% [%ipv4 @if]
187+ [%ipv6 @is]
188+ ==
189+```
190+
191+A client IP address.
192+
193+## `$inbound-request`
194+
195+```hoon
196++$ inbound-request
197+ $: authenticated=?
198+ secure=?
199+ =address
200+ =request:http
201+ ==
202+```
203+
204+An inbound HTTP request and metadata - this is what comes in when an external client makes a request to Eyre. The `authenticated` field says whether the request was made with a valid session cookie. The `secure` field says whether it was made with HTTPS. The [$address](#address) is the client's IP address. The [$request:http](#request-http) contains the HTTP request itself.
205+
206+# HTTP
207+
208+## `$header-list:http`
209+
210+```hoon
211++$ header-list (list [key=@t value=@t])
212+```
213+
214+An ordered list of HTTP headers. The `key` is the header name e.g `'Content-Type'` and the `value` is the value e.g. `text/html`.
215+
216+## `$method:http`
217+
218+```hoon
219++$ method
220+ $? %'CONNECT'
221+ %'DELETE'
222+ %'GET'
223+ %'HEAD'
224+ %'OPTIONS'
225+ %'POST'
226+ %'PUT'
227+ %'TRACE'
228+ ==
229+```
230+
231+An HTTP method.
232+
233+## `$request:http`
234+
235+```hoon
236++$ request
237+ $: method=method
238+ url=@t
239+ =header-list
240+ body=(unit octs)
241+ ==
242+```
243+
244+A single HTTP request. The [$method:http](#method-http) is the HTTP method, the `url` is the unescaped URL, the [$header-list:http](#header-list-http) contains the HTTP headers of the request and the `body` is the actual data. An `octs` is just `[p=@ud q=@]` where `p` is the byte-length of `q`, the data.
245+
246+## `$response-header:http`
247+
248+```hoon
249++$ response-header
250+ $: status-code=@ud
251+ headers=header-list
252+ ==
253+```
254+
255+The status code and [$header-list:http](#header-list-http) of an HTTP response. This is typically sent separately to the body.
256+
257+## `$http-event:http`
258+
259+```hoon
260++$ http-event
261+ $% $: %start
262+ =response-header
263+ data=(unit octs)
264+ complete=?
265+ ==
266+ $: %continue
267+ data=(unit octs)
268+ complete=?
269+ ==
270+ [%cancel ~]
271+ ==
272+```
273+
274+Packetised HTTP.
275+
276+Urbit treats Earth's HTTP servers as pipes, where Urbit sends or receives one or more `http-event`s. The first of these will always be a `%start` or an `%error`, and the last will always be `%cancel` or will have `complete` set to `%.y` to finish the connection.
277+
278+Calculation of control headers such as `'Content-Length'` or `'Transfer-Encoding'` should be performed at a higher level; this structure is merely for what gets sent to or received from Earth.
279+
280+## `$simple-payload:http`
281+
282+```hoon
283++$ simple-payload
284+ $: =response-header
285+ data=(unit octs)
286+ ==
287+--
288+```
289+
290+A simple, one-event response used for generators. The [$reponse-header:http](#response-header-http) contains the status code and HTTP headers. The `octs` in the `data` contains the body of the response and is a `[p=@ud q=@]` where `p` is the byte-length of `q`, the data.
arvo/eyre/examples.mdnew file+689
@@ -0,0 +1,689 @@
1++++
2+title = "Examples"
3+weight = 6
4+template = "doc.html"
5++++
6+
7+# Contents
8+
9+- [Introduction](#introduction)
10+- [Using the Channel System](#using-the-channel-system)
11+- [Scrying](#scrying)
12+- [Running Threads With Spider](#running-threads-with-spider)
13+- [Direct HTTP Handling With Gall Agents](#direct-http-handling-with-gall-agents)
14+- [Generators](#generators)
15+- [Managing CORS Origins](#managing-cors-origins)
16+
17+# Introduction
18+
19+This documents contains practical examples of the various ways of interacting with Eyre.
20+
21+General documentation of the `task`s and methods described here are available in the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document and the [Internal API Reference](@/docs/arvo/eyre/tasks.md) document.
22+
23+# Using The Channel System
24+
25+Here we'll look at a practical example of Eyre's channel system. You can refer to the [Channels](@/docs/arvo/eyre/external-api-ref.md#channels) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document for relevant details.
26+
27+The first thing we need to do is obtain a session cookie by [authenticating](@/docs/arvo/eyre/external-api-ref.md#authentication) with our web login code, which you can get by running `+code` in the dojo. In our case we'll just use the default code for a fakezod.
28+
29+Using `curl` in the unix terminal, we'll make an HTTP POST request with `"password=<code>"` in the body:
30+
31+```
32+curl -i localhost:8080/~/login -X POST -d "password=lidlut-tabwed-pillex-ridrup"
33+```
34+
35+Eyre will respond with HTTP status 204, and a `set-cookie` header containing the session cookie.
36+
37+```
38+HTTP/1.1 204 ok
39+Date: Tue, 18 May 2021 01:38:48 GMT
40+Connection: keep-alive
41+Server: urbit/vere-1.5
42+set-cookie: urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm; Path=/; Max-Age=604800
43+```
44+
45+Now that we have our cookie, we can try poking an app & simultaneously opening a new channel. In this case, we'll poke the `hood` app with a `mark` of `helm-hi` to print "Opening airlock" in the dojo.
46+
47+We'll do this with an HTTP PUT request, and we'll include the cookie we obtained when we authenticated in the `Cookie` header. The URL path we'll make the request to will be `http://localhost:8080/~/channel/mychannel`. The last part of the path is the channel `UID` - the name for our new channel. Normally you'd use the current unix time plus a hash to ensure uniqueness, but in this case we'll just use `mychannel` for simplicity.
48+
49+The data will be a JSON array containing a [poke](@/docs/arvo/eyre/external-api-ref.md#poke) `action`:
50+
51+```
52+curl --header "Content-Type: application/json" \
53+ --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" \
54+ --request PUT \
55+ --data '[{"id":1,"action":"poke","ship":"zod","app":"hood","mark":"helm-hi","json":"Opening airlock"}]' \
56+ http://localhost:8080/~/channel/my-channel
57+```
58+
59+If we now have a look in the dojo we'll see it's printed our message, so the poke was successful:
60+
61+```
62+< ~zod: Opening airlock
63+```
64+
65+Now we can connect to the `mychannel` channel we opened. We do this with an HTTP GET request with our session cookie and the same path as the last request:
66+
67+```
68+curl -i --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" http://localhost:8080/~/channel/my-channel
69+```
70+
71+Eyre will respond with an HTTP status code of 200 and a `content-type` of `text/event-stream`, indicating an SSE (Server Sent Event) stream. It will also send us any pending events on the channel - in this case the poke ack as a [poke](@/docs/arvo/eyre/external-api-ref.md#poke-ack) `response` for our original poke:
72+
73+```
74+HTTP/1.1 200 ok
75+Date: Tue, 18 May 2021 01:40:47 GMT
76+Connection: keep-alive
77+Server: urbit/vere-1.5
78+set-cookie: urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm; Path=/; Max-Age=604800
79+connection: keep-alive
80+cache-control: no-cache
81+content-type: text/event-stream
82+transfer-encoding: chunked
83+
84+id: 0
85+data: {"ok":"ok","id":1,"response":"poke"}
86+```
87+
88+Normally this event stream would be handled by an EventSource object in Javascript or the equivalent in whatever other language you're using. Here, though, we'll continue using `curl` for simplicity.
89+
90+Leaving the event stream connection open, in another shell session on unix we'll try subscribing to the watch path of a Gall agent - the `/updates` watch path of `graph-store` in this case.
91+
92+We'll do this in the same way as the initial poke, except this time it will be a [subscribe](@/docs/arvo/eyre/external-api-ref.md#subscribe) `action`:
93+
94+```
95+curl --header "Content-Type: application/json" \
96+ --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" \
97+ --request PUT \
98+ --data '[{"id":2,"action":"subscribe","ship":"zod","app":"graph-store","path":"/updates"}]' \
99+ http://localhost:8080/~/channel/my-channel
100+```
101+
102+Notice we've incremented the `id` to `2`, as request IDs must be sequential.
103+
104+Back in the event stream, we'll see a positive watch ack as a [subscribe](@/docs/arvo/eyre/external-api-ref.md#watch-ack) `response`, meaning the subscription has been successful:
105+
106+```
107+id: 1
108+data: {"ok":"ok","id":2,"response":"subscribe"}
109+```
110+
111+Now we'll try trigger an event on our event stream. In fakezod's landscape, create a new chat channel named "test". You should see the `fact` containing the `add-graph` `graph-update` come through on our channel in a [diff](@/docs/arvo/eyre/external-api-ref.md#fact) `response`:
112+
113+```
114+id: 2
115+data: {"json":{"graph-update":{"add-graph":{"graph":{},"resource":{"name":"test-1183","ship":"zod"},"mark":"graph-validator-chat","overwrite":false}}},"id":2,"response":"diff"}
116+```
117+
118+All `fact`s we receive must be acked so Eyre knows we've successfully received it. To do this we'll send an [ack](@/docs/arvo/eyre/external-api-ref.md#ack) `action` which specifies the `event-id` of the event in question - `2` in this case:
119+
120+```
121+curl --header "Content-Type: application/json" \
122+ --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" \
123+ --request PUT \
124+ --data '[{"id":3,"action":"ack","event-id":2}]' \
125+ http://localhost:8080/~/channel/my-channel
126+```
127+
128+This same pattern would be repeated for all subsequent `fact`s. When we're finished, we can unsubscribe from `graph-store` `/update`. We do this by sending Eyre a [unsubscribe](@/docs/arvo/eyre/external-api-ref.md#unsubscribe) `action`, and specify the request ID of the original `subscribe` `action` in the `subscription` field - `2` in our case:
129+
130+```
131+curl --header "Content-Type: application/json" \
132+ --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" \
133+ --request PUT \
134+ --data '[{"id":4,"action":"unsubscribe","subscription":2}]' \
135+ http://localhost:8080/~/channel/my-channel
136+```
137+
138+Unlike `poke` and `subscribe` actions, Eyre doesn't ack `unsubscribe`s, but we'll now have stopped receiving `fact`s from `graph-store`.
139+
140+Finally, let's close the channel itself. We can do this simply by sending Eyre a [delete](@/docs/arvo/eyre/external-api-ref.md#delete-channel) `action`:
141+
142+```
143+curl --header "Content-Type: application/json" \
144+ --cookie "urbauth-~zod=0v3.j2062.1prp1.qne4e.goq3h.ksudm" \
145+ --request PUT \
146+ --data '[{"id":5,"action":"delete"}]' \
147+ http://localhost:8080/~/channel/my-channel
148+```
149+
150+With our channel deleted, we can now close the connection on the client side.
151+
152+# Scrying
153+
154+Here we'll look at performing scries through Eyre. You can refer to the [Scry](@/docs/arvo/eyre/external-api-ref.md#scry) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document for relevant details.
155+
156+The first thing we must do is obtain a session cookie by authenticating with our web login code. We'll use the unix `curl` utility and provide the default code for a fakezod:
157+
158+```
159+curl -i localhost:8080/~/login -X POST -d "password=lidlut-tabwed-pillex-ridrup"
160+```
161+
162+Eyre will respond with HTTP status 204 and a `set-cookie` header containing the cookie, which we'll use in the `cookie` header of subsequent requests:
163+
164+```
165+HTTP/1.1 204 ok
166+Date: Fri, 04 Jun 2021 10:15:15 GMT
167+Connection: keep-alive
168+Server: urbit/vere-1.5
169+set-cookie: urbauth-~zod=0v1.1pseu.tq7hs.hps2t.ltaf1.tmqjm; Path=/; Max-Age=604800
170+```
171+
172+Having obtained a cookie, we can now try a scry. We'll scry the `graph-store` Gall agent on the `/x/keys` scry path, which will return the list of channels it has. If you don't already have any chat channels on your fakezod, go ahead and create one via landscape so it'll have something to return.
173+
174+The url path will be `/~/scry/graph-store/keys.json`. The `/~/scry` part specifies a scry, the `/graph-store` part is the Gall agent, the `/keys` is the scry path without the `care`, and the `.json` file extension specifies the return `mark`.
175+
176+The request will be an HTTP GET request:
177+
178+```
179+curl -i --cookie "urbauth-~zod=0v1.1pseu.tq7hs.hps2t.ltaf1.tmqjm" \
180+ --request GET \
181+ http://localhost:8080/~/scry/graph-store/keys.json
182+```
183+
184+Eyre will respond with HTTP status 200 if it's successful and the body of the response will contain the data we requested:
185+
186+```
187+HTTP/1.1 200 ok
188+Date: Fri, 04 Jun 2021 10:16:32 GMT
189+Connection: keep-alive
190+Content-Length: 61
191+Server: urbit/vere-1.5
192+set-cookie: urbauth-~zod=0v1.1pseu.tq7hs.hps2t.ltaf1.tmqjm; Path=/; Max-Age=604800
193+content-type: application/json
194+
195+{"graph-update":{"keys":[{"name":"test-1183","ship":"zod"}]}}
196+```
197+
198+Now let's make a request to a non-existent scry endpoint:
199+
200+```
201+curl -i --cookie "urbauth-~zod=0v1.1pseu.tq7hs.hps2t.ltaf1.tmqjm" \
202+ --request GET \
203+ http://localhost:8080/~/scry/foo/bar/baz.json
204+```
205+
206+Eyre will respond with a 404 Missing status and an error message:
207+
208+```
209+HTTP/1.1 404 missing
210+Date: Fri, 04 Jun 2021 10:22:51 GMT
211+Connection: keep-alive
212+Content-Length: 187
213+Server: urbit/vere-1.5
214+set-cookie: urbauth-~zod=0v1.1pseu.tq7hs.hps2t.ltaf1.tmqjm; Path=/; Max-Age=604800
215+content-type: text/html
216+
217+<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>There was an error while handling the request for /foo/bar/baz.json.</p><code>no scry result</code></body></html>
218+```
219+
220+# Running Threads With Spider
221+
222+Here we'll look at running Spider threads through Eyre. You can refer to the [Spider](@/docs/arvo/eyre/external-api-ref.md#spider) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document for relevant details.
223+
224+Here's an extremely simple thread that takes a `vase` of `(unit json)` and just returns the `json` in a new `vase`. You can save it in `/ted` and `|commit %home`:
225+
226+`eyre-thread.hoon`
227+
228+```hoon
229+/- spider
230+=, strand=strand:spider
231+^- thread:spider
232+|= arg=vase
233+=/ m (strand ,vase)
234+^- form:m
235+=/ =json
236+ (need !<((unit json) arg))
237+(pure:m !>(json))
238+```
239+
240+In order to run it through Eyre, we must first obtain a session cookie by [authenticating](@/docs/arvo/eyre/external-api-ref.md#authentication) with our web login code. To do so, we'll make an HTTP POST request using the unix `curl` utility:
241+
242+```
243+curl -i localhost:8080/~/login -X POST -d "password=lidlut-tabwed-pillex-ridrup"
244+```
245+
246+Eyre will respond with a 204 status and a `set-cookie` header containing the cookie:
247+
248+```
249+HTTP/1.1 204 ok
250+Date: Sun, 06 Jun 2021 04:50:09 GMT
251+Connection: keep-alive
252+Server: urbit/vere-1.5
253+set-cookie: urbauth-~zod=0v6.h6t4q.2tkui.oeaqu.nihh9.i0qv6; Path=/; Max-Age=604800
254+```
255+
256+Now we can try and run our thread. Spider (the Gall agent that manages threads) is bound to the `/spider` URL path, and expects the rest of the path to be `/{inputMark}/{thread}/{outputMark}`. Our `{thread}` is called `eyre-thread`, and both its `{inputMark}` and `{outputMark}` are `json`, so our URL path will be `/spider/json/eyre-agent/json`. Our request will be an HTTP POST request and the body will be some `json`, in this case `[{"foo": "bar"}]`:
257+
258+```
259+curl -i --header "Content-Type: application/json" \
260+ --cookie "urbauth-~zod=0v6.h6t4q.2tkui.oeaqu.nihh9.i0qv6" \
261+ --request POST \
262+ --data '[{"foo": "bar"}]' \
263+ http://localhost:8080/spider/json/eyre-thread/json
264+```
265+
266+Spider will run the thread and the result will be returned through Eyre in the body of an HTTP response with a 200 status code:
267+
268+```
269+HTTP/1.1 200 ok
270+Date: Sun, 06 Jun 2021 05:32:45 GMT
271+Connection: keep-alive
272+Server: urbit/vere-1.5
273+set-cookie: urbauth-~zod=0v6.h6t4q.2tkui.oeaqu.nihh9.i0qv6; Path=/; Max-Age=604800
274+content-type: application/json
275+transfer-encoding: chunked
276+
277+[{"foo":"bar"}]
278+```
279+
280+# Direct HTTP Handling With Gall Agents
281+
282+In many cases you'll just want to interact with Gall agents through the JSON API of the channel system, but it's also possible to bypass all that and just deal with HTTP requests directly. Here we'll take a look at how that practically works.
283+
284+You can refer to the [%connect](@/docs/arvo/eyre/tasks.md#connect) section of the [Internal API Reference](@/docs/arvo/eyre/tasks.md) document for relevant details.
285+
286+Here's a Gall agent that demonstrates this method. It binds the URL path `/foo`, serves `<h1>Hello, World!</h1>` for GET requests and a `405` error for all others. It also prints information to the dojo as various things happen.
287+
288+`eyre-agent.hoon`
289+
290+```hoon
291+/+ default-agent, dbug
292+=* card card:agent:gall
293+%- agent:dbug
294+^- agent:gall
295+|_ =bowl:gall
296++* this .
297+ def ~(. (default-agent this %|) bowl)
298+::
299+++ on-init on-init:def
300+++ on-save on-save:def
301+++ on-load on-load:def
302+++ on-poke
303+ |= [=mark =vase]
304+ ^- (quip card _this)
305+ ?+ mark
306+ (on-poke:def [mark vase])
307+ ::
308+ %noun
309+ ?. =(q.vase %bind)
310+ %- (slog leaf+"Bad argument." ~)
311+ `this
312+ %- (slog leaf+"Attempting to bind /foo." ~)
313+ :_ this
314+ [%pass /eyre %arvo %e %connect `/'foo' %eyre-agent]~
315+ ::
316+ %handle-http-request
317+ =/ req !< (pair @ta inbound-request:eyre) vase
318+ ~& [mark req]
319+ ?+ method.request.q.req
320+ =/ data=octs
321+ (as-octs:mimes:html '<h1>405 Method Not Allowed</h1>')
322+ =/ content-length=@t
323+ (crip (skip (scow %ud p.data) |=(a=@tD =(a '.'))))
324+ =/ =response-header:http
325+ :- 405
326+ :~ ['Content-Length' content-length]
327+ ['Content-Type' 'text/html']
328+ ['Allow' 'GET']
329+ ==
330+ :_ this
331+ :~
332+ [%give %fact [/http-response/[p.req]]~ %http-response-header !>(response-header)]
333+ [%give %fact [/http-response/[p.req]]~ %http-response-data !>(`data)]
334+ [%give %kick [/http-response/[p.req]]~ ~]
335+ ==
336+ ::
337+ %'GET'
338+ =/ data=octs
339+ (as-octs:mimes:html '<h1>Hello, World!</h1>')
340+ =/ content-length=@t
341+ (crip (skip (scow %ud p.data) |=(a=@tD =(a '.'))))
342+ =/ =response-header:http
343+ :- 200
344+ :~ ['Content-Length' content-length]
345+ ['Content-Type' 'text/html']
346+ ==
347+ :_ this
348+ :~
349+ [%give %fact [/http-response/[p.req]]~ %http-response-header !>(response-header)]
350+ [%give %fact [/http-response/[p.req]]~ %http-response-data !>(`data)]
351+ [%give %kick [/http-response/[p.req]]~ ~]
352+ ==
353+ ==
354+ ==
355+++ on-watch
356+ |= =path
357+ ^- (quip card _this)
358+ ?+ path
359+ (on-watch:def path)
360+ ::
361+ [%http-response *]
362+ %- (slog leaf+"Eyre subscribed to {(spud path)}." ~)
363+ `this
364+ ==
365+++ on-leave on-leave:def
366+++ on-peek on-peek:def
367+++ on-agent on-agent:def
368+++ on-arvo
369+ |= [=wire =sign-arvo]
370+ ^- (quip card _this)
371+ ?+ sign-arvo
372+ (on-arvo:def [wire sign-arvo])
373+ ::
374+ [%eyre %bound *]
375+ ?: accepted.sign-arvo
376+ %- (slog leaf+"/foo bound successfully!" ~)
377+ `this
378+ %- (slog leaf+"Binding /foo failed!" ~)
379+ `this
380+ ==
381+++ on-fail on-fail:def
382+--
383+```
384+
385+Save the above to `app/eyre-agent.hoon`. Commit it:
386+
387+```
388+> |commit %home
389+>=
390++ /~zod/home/2/app/eyre-agent/hoon
391+```
392+
393+...and start it:
394+
395+```
396+> |start %eyre-agent
397+>=
398+gall: loading %eyre-agent
399+activated app home/eyre-agent
400+[unlinked from [p=~zod q=%eyre-agent]]
401+```
402+
403+Now, first we need to bind a url to our app. In the `++ on-poke` arm, our agent will send a [%connect](@/docs/arvo/eyre/tasks.md#connect) `task` to Eyre when poked with `%bind`:
404+
405+```hoon
406+ %noun
407+?. =(q.vase %bind)
408+ %- (slog leaf+"Bad argument." ~)
409+ `this
410+%- (slog leaf+"Attempting to bind /foo." ~)
411+:_ this
412+[%pass /eyre %arvo %e %connect `/'foo' %eyre-agent]~
413+```
414+
415+...and when `%eyre` responds with a `%bound` gift, the `+on-agent` arm will print whether the bind succeeded:
416+
417+```hoon
418+ [%eyre %bound *]
419+?: accepted.sign-arvo
420+ %- (slog leaf+"/foo bound successfully!" ~)
421+ `this
422+%- (slog leaf+"Binding /foo failed!" ~)
423+`this
424+```
425+...so let's try:
426+
427+```
428+> :eyre-agent %bind
429+>=
430+Attempting to bind /foo.
431+/foo bound successfully!
432+```
433+
434+As you can see, we have successfully bound the `/foo` url path. Now we can try making an HTTP request. Over in the unix terminal, we can make a GET request using curl:
435+
436+```
437+> curl -i localhost:8080/foo
438+HTTP/1.1 200 ok
439+Date: Mon, 17 May 2021 04:39:40 GMT
440+Connection: keep-alive
441+Server: urbit/vere-1.5
442+Content-Type: text/html
443+Content-Length: 22
444+transfer-encoding: chunked
445+
446+<h1>Hello, World!</h1>%
447+```
448+
449+...which has succeed! This is because the `+on-poke` arm tests for http GET requests and responds with `Hello, World!` when it sees one:
450+
451+```hoon
452+ %'GET'
453+=/ data=octs
454+ (as-octs:mimes:html '<h1>Hello, World!</h1>')
455+=/ content-length=@t
456+ (crip (skip (scow %ud p.data) |=(a=@tD =(a '.'))))
457+=/ =response-header:http
458+ :- 200
459+ :~ ['Content-Length' content-length]
460+ ['Content-Type' 'text/html']
461+ ==
462+:_ this
463+:~
464+ [%give %fact [/http-response/[p.req]]~ %http-response-header !>(response-header)]
465+ [%give %fact [/http-response/[p.req]]~ %http-response-data !>(`data)]
466+ [%give %kick [/http-response/[p.req]]~ ~]
467+==
468+```
469+
470+Back in the dojo, our app's `+on-watch` arm has printed the path on which Eyre has subscribed for the response:
471+
472+```
473+Eyre subscribed to /http-response/~.eyre_0v3.1knjk.l544e.5uds6.fn9l2.f8929.
474+```
475+
476+...and it's also printed the request so you can see how it looks when it comes in:
477+
478+```
479+[ %handle-http-request
480+ p=~.~.eyre_0v3.1knjk.l544e.5uds6.fn9l2.f8929
481+ q
482+ [ authenticated=%.n
483+ secure=%.n
484+ address=[%ipv4 .127.0.0.1]
485+ request
486+ [ method=%'GET'
487+ url='/foo'
488+ header-list
489+ ~[
490+ [key='host' value='localhost:8080']
491+ [key='user-agent' value='curl/7.76.1']
492+ [key='accept' value='*/*']
493+ ]
494+ body=~
495+ ]
496+ ]
497+]
498+```
499+
500+This is a very rudimentary app but it demonstrates the basic mechanics of dealing with HTTP requests and serving responses.
501+
502+# Generators
503+
504+Here we'll look at running a generator via Eyre. Eyre doesn't have a mediated JSON API for generators, instead it just passes through the HTTP request and returns the HTTP response composed by the generator.
505+
506+You can refer to the [%serve](@/docs/arvo/eyre/tasks.md#serve) section of the [Internal API Reference](@/docs/arvo/eyre/tasks.md) document for relevant details.
507+
508+Here's a very simple generator that will just echo back the body of the request (if available) along with the current datetime. You can save it in the `/gen` directory and `|commit %home`.
509+
510+`eyre-gen.hoon`
511+
512+```hoon
513+|= [[now=@da eny=@uvJ bec=beak] ~ ~]
514+|= [authenticated=? =request:http]
515+^- simple-payload:http
516+=/ msg=@t
517+ ?~ body.request
518+ (scot %da now)
519+ (cat 3 (cat 3 (scot %da now) 10) q.u.body.request)
520+=/ data=octs
521+ (as-octs:mimes:html msg)
522+=/ content-length=@t
523+ (rsh [3 2] (scot %ui p.data))
524+=/ =response-header:http
525+ :- 200
526+ :~ ['Content-Length' content-length]
527+ ['Content-Type' 'text/plain']
528+ ==
529+[response-header `data]
530+```
531+
532+Eyre requires generators to be a gate within a gate. The sample of the first gate must be:
533+
534+```hoon
535+[[now=@da eny=@uvJ bec=beak] ~ ~]
536+```
537+
538+The sample of the second nested gate must be:
539+
540+```hoon
541+[authenticated=? =request:http]
542+```
543+
544+The return type of the generator must be [simple-payload:http](@/docs/arvo/eyre/data-types.md#simple-payload-http).
545+
546+If you look at our example generator you'll see it meets these requirements.
547+
548+In order to make our generator available, we must bind it to a URL path. To do this, we send Eyre a `%serve` `task`, which looks like:
549+
550+```hoon
551+[%serve =binding =generator]
552+```
553+
554+The [binding](@/docs/arvo/eyre/data-types.md#binding) specifies the site and URL path, and the [generator](@/docs/arvo/eyre/data-types.md#generator) specifies the `desk`, the `path` to the generator, and arguments. Note that the passing of arguments to the generator by Eyre is not currently implemented, so you can just leave that as `~` since it won't do anything.
555+
556+Let's bind our generator to the `/mygen` URL path with the `|pass` command in the dojo:
557+
558+```
559+|pass [%e [%serve `/mygen %home /gen/eyre-gen/hoon ~]]
560+```
561+
562+Note that Eyre responds with a `%bound` `gift` to indicate whether the binding succeeded but `|pass` doesn't take such responses so it's not shown.
563+
564+Now let's try making an HTTP request using `curl` in the unix terminal:
565+
566+```
567+curl -i http://localhost:8080/mygen --data 'blah blah blah'
568+```
569+
570+We can see that the request has succeeded and our generator has responded with the datetime and request body:
571+
572+```
573+HTTP/1.1 200 ok
574+Date: Sat, 29 May 2021 09:19:45 GMT
575+Connection: keep-alive
576+Content-Length: 41
577+Server: urbit/vere-1.5
578+Content-Type: text/plain
579+Content-Length: 41
580+
581+~2021.5.29..09.19.45..e096
582+blah blah blah
583+```
584+
585+# Managing CORS Origins
586+
587+Here we'll look at approving and rejecting a CORS origin by passing Clay a [%approve-origin](@/docs/arvo/eyre/tasks.md#approve-origin) `task` and [%reject-origin](@/docs/arvo/eyre/tasks.md#reject-origin) `task` respectively.
588+
589+First, using `|pass` in the dojo, let's approve the origin `http://foo.example` by sending Eyre a `%approve-origin` `task`:
590+
591+```
592+|pass [%e [%approve-origin 'http://foo.example']]
593+```
594+
595+Now if we scry for the [approved](@/docs/arvo/eyre/scry.md#x-cors-approved) CORS `set`:
596+
597+```
598+> .^(approved=(set @t) %ex /=//=/cors/approved)
599+approved={'http://foo.example'}
600+```
601+
602+...we can see that `http://foo.example` has been added.
603+
604+Next, let's test it by sending Eyre a CORS preflight request via `curl` in unix:
605+
606+```
607+curl -i -X OPTIONS \
608+ -H "Access-Control-Request-Method: POST" \
609+ -H "Access-Control-Request-Headers: X-Requested-With" \
610+ -H "Origin: http://foo.example" \
611+ http://localhost:8080
612+```
613+
614+We can see in the response that it has succeeded:
615+
616+```
617+HTTP/1.1 204 ok
618+Date: Fri, 28 May 2021 12:37:12 GMT
619+Connection: keep-alive
620+Server: urbit/vere-1.5
621+Access-Control-Allow-Origin: http://foo.example
622+Access-Control-Allow-Credentials: true
623+Access-Control-Allow-Headers: X-Requested-With
624+Access-Control-Allow-Methods: POST
625+```
626+
627+Now we'll try rejecting an `origin`. Back in the dojo, let's `|pass` Eyre a `%reject-origin` `task` for `http://bar.example`:
628+
629+```
630+|pass [%e [%reject-origin 'http://bar.example']]
631+```
632+
633+If we scry for the [rejected](@/docs/arvo/eyre/scry.md#x-cors-rejected) CORS `set`:
634+
635+```
636+> .^(rejected=(set @t) %ex /=//=/cors/rejected)
637+rejected={'http://bar.example'}
638+```
639+
640+...we can see that `http://bar.example` has been added.
641+
642+If we again test it with `curl` in unix:
643+
644+```
645+curl -i -X OPTIONS \
646+ -H "Access-Control-Request-Method: POST" \
647+ -H "Access-Control-Request-Headers: X-Requested-With" \
648+ -H "Origin: http://bar.example" \
649+ http://localhost:8080
650+```
651+
652+...we can see that, as expected, it has not returned the access control headers:
653+
654+```
655+HTTP/1.1 404 missing
656+Date: Fri, 28 May 2021 12:38:47 GMT
657+Connection: close
658+Server: urbit/vere-1.5
659+```
660+
661+Finally, let's look at CORS requests that are neither approved nor rejected.
662+
663+If we make another request with `curl` on unix, this time for `http://baz.example` which we haven't added to a list:
664+
665+```
666+curl -i -X OPTIONS \
667+ -H "Access-Control-Request-Method: POST" \
668+ -H "Access-Control-Request-Headers: X-Requested-With" \
669+ -H "Origin: http://baz.example" \
670+ http://localhost:8080
671+```
672+
673+...we can see it also correctly fails to return the access control headers:
674+
675+```
676+HTTP/1.1 404 missing
677+Date: Fri, 28 May 2021 12:39:59 GMT
678+Connection: close
679+Server: urbit/vere-1.5
680+```
681+
682+Now if we scry for the [requests](@/docs/arvo/eyre/scry.md#x-cors-requests) CORS `set`:
683+
684+```
685+> .^(requests=(set @t) %ex /=//=/cors/requests)
686+requests={'http://baz.example' 'http://localhost:8080'}
687+```
688+
689+... we can see it has automatically been added by the mere fact of the request being made.
arvo/eyre/external-api-ref.mdnew file+399
@@ -0,0 +1,399 @@
1++++
2+title = "External API Reference"
3+weight = 2
4+template = "doc.html"
5++++
6+
7+# Contents
8+
9+- [Introduction](#introduction)
10+- [Authentication](#authentication)
11+- [Channels](#channels)
12+ - [HTTP Requests](#http-requests)
13+ - [Actions](#actions)
14+ - [Poke](#poke)
15+ - [Subscribe](#subscribe)
16+ - [Ack](#ack)
17+ - [Unsubscribe](#unsubscribe)
18+ - [Delete Channel](#delete-channel)
19+ - [Responses](#responses)
20+ - [Poke Ack](#poke-ack)
21+ - [Watch Ack](#watch-ack)
22+ - [Fact](#fact)
23+ - [Kick](#kick)
24+- [Scry](#scry)
25+- [Spider](#spider)
26+
27+# Introduction
28+
29+This document contains reference information about Eyre's external APIs including [the channel system](#channels), [scries](#scry) and [threads](#spider). Each section will also have practical examples in the [Examples](@/docs/arvo/eyre/examples.md) document.
30+
31+# Authentication
32+
33+To use Eyre's channel system, run threads or perform scries you must first obtain a session cookie by authenticating with the following HTTP request:
34+
35+| HTTP Method | Data | URL Path | Notes |
36+|-------------|----------------------------------------|------------|-------------------------------------------------------------------------------------|
37+| `POST` | `password=lidlut-tabwed-pillex-ridrup` | `/~/login` | The password is your web login code which can be obtained with `+code` in the dojo. |
38+
39+Eyre's response will include a `set-cookie` header like:
40+
41+```
42+set-cookie: urbauth-~zod=0v4.ilskp.psv00.t09r0.l8rps.3n97v; Path=/; Max-Age=604800
43+```
44+
45+The `urbauth-{...}` cookie provided must be included in a `cookie` header with all subsequent requests like:
46+
47+```
48+cookie: urbauth-~zod=0v4.ilskp.psv00.t09r0.l8rps.3n97v
49+```
50+
51+# Channels
52+
53+Eyre's channel system is the primary way of interacting with Gall agents from outside of Urbit.
54+
55+Data from an external HTTP client is sent to Eyre as an [HTTP PUT request](#http-requests) containing one or more [action](#actions) JSON objects. Clients must obtain a session cookie by [authenticating](#authentication) with Eyre in order to make such requests.
56+
57+Data from Eyre is sent back to the external HTTP client on a channel as SSEs ([Server Sent Events](https://html.spec.whatwg.org/#server-sent-events)) containing a [response](#responses) JSON object.
58+
59+A new channel is automatically created whenever a client sends an [action](#action) in an [HTTP PUT request](#http-requests) to `http{s}://{host}{port}/~/channel/{uid}` with a new `uid`. To connect to the channel and receive any pending events, you just send an HTTP GET request with a valid session cookie to that URL.
60+
61+The response you'll get to the GET request will be an event stream. Events will come in like:
62+
63+```
64+id: 0
65+data: {"ok":"ok","id":1,"response":"poke"}
66+```
67+
68+If you're working with Javascript in the browser context you'll handle these with an EventSource object. If you're using another language, there'll likely be a library available to handle SSEs.
69+
70+When you're finished with a channel, you can send Eyre a [delete action](#delete-channel) to close it.
71+
72+See the [Using the Channel System](@/docs/arvo/eyre/examples.md#using-the-channel-system) section of the [Examples](@/docs/arvo/eyre/examples.md) document for a practical example.
73+
74+## HTTP Requests
75+
76+[Actions](#actions) are sent to Eyre in HTTP PUT requests:
77+
78+| HTTP Method | Required Headers | Data | URL Path |
79+|-------------|---------------------------|----------------------------------------------------------------|--------------------|
80+| `PUT` | `Content-Type` & `Cookie` | One or more [actions](#actions) wrapped in a JSON array (`[]`) | `/~/channel/{uid}` |
81+
82+The `cookie` header contains the session cookie obtained by [authenticating](#authentication). The data is a JSON array containing one or more JSON [action](#actions) objects. The channel `uid` is a unique name of your choosing. Typically you'd use the current unix time and a hash but there's no specific requirements. If you're opening a new channel you'd choose a new `uid` and if you already have a channel open you'd just use that.
83+
84+If successful, Eyre will respond with a status code of 204. Note the HTTP response will have no content, any [responses](#responses) will be sent as SSEs on the channel event stream.
85+
86+## Actions
87+
88+### Poke
89+
90+This is for poking a Gall agent.
91+
92+| Key | JSON Type | Example Value | Description |
93+|----------|-----------|---------------|---------------------------------------------------------------|
94+| `id` | Number | `1` | Sequential ID for keeping track of sent messages. |
95+| `action` | String | `'poke'` | The kind of action. |
96+| `ship` | String | `'zod'` | Ship name, excluding leading `~`. |
97+| `app` | String | `'hood'` | Name of the gall agent you're poking. |
98+| `mark` | String | `'helm-hi'` | Type of data. Must correspond to a mark definition in `/mar`. |
99+| `json` | Any | `'hello'` | Actual payload. Any JSON type, determined by app. |
100+
101+**Example**
102+
103+```json
104+{
105+ 'id': 1,
106+ 'action': 'poke',
107+ 'ship': 'zod',
108+ 'app': 'hood',
109+ 'mark': 'helm-hi',
110+ 'json': 'hello'
111+}
112+```
113+
114+**Response**
115+
116+Eyre will send a [poke ack](#poke-ack) as an SSE event on the channel event stream.
117+
118+### Subscribe
119+
120+This is for subscribing to a watch `path` of a Gall agent.
121+
122+| Key | JSON Type | Example Value | Description |
123+|----------|-----------|-----------------|-----------------------------------------------------|
124+| `id` | Number | `2` | Sequential ID for keeping track of sent messages. |
125+| `action` | String | `'subscribe'` | The kind of action. |
126+| `ship` | String | `'zod'` | Ship name, excluding leading `~`. |
127+| `app` | String | `'graph-store'` | Name of the gall agent to which you're subscribing. |
128+| `path` | String | `'/updates'` | The path to watch. Depends on the app. |
129+
130+**Example**
131+
132+```json
133+{
134+ 'id': 2,
135+ 'action': 'subscribe',
136+ 'ship': 'zod',
137+ 'app': 'graph-store',
138+ 'path': '/updates'
139+}
140+```
141+
142+**Response**
143+
144+Eyre will send back a [watch ack](#watch-ack). If subscribing was successful, you will also begin receiving any [fact](#fact)s sent by the Gall agent on the specified `path`.
145+
146+### Ack
147+
148+This is for acknowledging a [fact](#fact) from a Gall agent to which you've subscribed.
149+
150+| Key | JSON Type | Example Value | Description |
151+|------------|-----------|---------------|--------------------------------------------------------|
152+| `id` | Number | `3` | Sequential ID for keeping track of sent messages. |
153+| `action` | String | `'ack'` | The kind of action. |
154+| `event-id` | Number | `7` | ID of SSE event for which you're acknowledging receipt |
155+
156+**Example**
157+
158+```json
159+{
160+ 'id': 3,
161+ 'action': 'ack',
162+ 'event-id': 7,
163+}
164+```
165+
166+**Response**
167+
168+Eyre will not respond to an `ack` action - acks are never acked.
169+
170+### Unsubscribe
171+
172+This is for unsubscribing from a Gall agent watch `path` to which you've previously subscribed.
173+
174+| Key | JSON Type | Example Value | Description |
175+|----------------|-----------|---------------|------------------------------------------------------------|
176+| `id` | Number | `4` | Sequential ID for keeping track of sent messages. |
177+| `action` | String | `unsubscribe` | The kind of action. |
178+| `subscription` | Number | `2` | Request ID of the initial `subscribe` action from earlier. |
179+
180+**Example**
181+
182+```json
183+{
184+ 'id': 4,
185+ 'action': 'unsubscribe',
186+ 'subscription': 2
187+}
188+```
189+
190+**Response**
191+
192+Eyre will not respond to an `unsubscribe` action.
193+
194+### Delete Channel
195+
196+This is for deleting the channel itself.
197+
198+| Key | JSON Type | Example Value | Description |
199+|----------|-----------|---------------|---------------------------------------------------|
200+| `id` | Number | `5` | Sequential ID for keeping track of sent messages. |
201+| `action` | String | `'delete'` | The kind of action. |
202+
203+**Example**
204+
205+```json
206+{
207+ 'id': 5,
208+ 'action': 'delete'
209+}
210+```
211+
212+**Response**
213+
214+Eyre will not respond to a `delete` action.
215+
216+## Responses
217+
218+### Poke Ack
219+
220+This acknowledgement comes in response to a [poke](#poke) action. A poke ack with an `ok` key means the poke succeeded. A poke ack with an `err` key means the poke failed.
221+
222+**Positive Poke Ack**
223+
224+| Key | JSON Type | Example Value | Description |
225+|------------|-----------|---------------|----------------------------------------------|
226+| `ok` | String | `'ok'` | Positive acknowledgement. |
227+| `id` | Number | `1` | Request ID of the `poke` being acknowledged. |
228+| `response` | String | `'poke'` | The kind of action being acknowledged. |
229+
230+**Example**
231+
232+```json
233+{
234+ 'ok': 'ok',
235+ 'id': 1,
236+ 'response': 'poke'
237+}
238+```
239+
240+**Negative Poke Ack**
241+
242+| Key | JSON Type | Example Value | Description |
243+|------------|-----------|------------------|-----------------------------------------------------------------------|
244+| `err` | String | `'some text...'` | Negative acknowledgement. Contains an error message and/or traceback. |
245+| `id` | Number | `1` | Request ID of the `poke` being acknowledged. |
246+| `response` | String | `'poke'` | The kind of action being acknowledged. |
247+
248+**Example**
249+
250+```json
251+{
252+ 'err': '<error message and traceback>',
253+ 'id': 1,
254+ 'response': 'poke'
255+}
256+```
257+
258+**Action Required**
259+
260+No action is required - acks are never acked.
261+
262+### Watch Ack
263+
264+This acknowledgement comes in response to a [subscribe](#subscribe) action. A watch ack with an `ok` key means the subscription was successful. A watch ack with an `err` key means the subscription failed.
265+
266+**Positive Watch Ack**
267+
268+| Key | JSON Type | Example Value | Description |
269+|------------|-----------|---------------|-----------------------------------------------|
270+| `ok` | String | `'ok'` | Positive acknowledgement. |
271+| `id` | Number | `2` | Request ID of the initial `subscribe` action. |
272+| `response` | String | `'subscribe'` | The kind of action being acknowledged. |
273+
274+**Example**
275+
276+```json
277+{
278+ 'ok': 'ok',
279+ 'id': 2,
280+ 'response': 'subscribe'
281+}
282+```
283+
284+**Negative Watch Ack**
285+
286+| Key | JSON Type | Example Value | Description |
287+|------------|-----------|------------------|-----------------------------------------------------------------------|
288+| `err` | String | `'some text...'` | Negative acknowledgement. Contains an error message and/or traceback. |
289+| `id` | Number | `2` | Request ID of the initial `subscribe` action. |
290+| `response` | String | `'subscribe'` | The kind of action being acknowledged. |
291+
292+**Example**
293+
294+```json
295+{
296+ 'err': '<error message and traceback>',
297+ 'id': 2,
298+ 'response': 'subscribe'
299+}
300+```
301+
302+**Action Required**
303+
304+No action is required - acks are never acked.
305+
306+### Fact
307+
308+All data sent by a Gall agent on the `path` to which you've subscribed comes in as `fact`s.
309+
310+| Key | JSON Type | Example Value | Description |
311+|------------|-----------|------------------|--------------------------------------------------------------|
312+| `json` | Any | `{'foo': 'bar'}` | The actual data from the agent, could be any JSON structure. |
313+| `id` | Number | `3` | Request ID of the initial `subscribe` action from earlier. |
314+| `response` | String | `'diff'` | The kind of response. All `fact`s are marked `'diff'`. |
315+
316+**Example**
317+
318+```json
319+{
320+ 'json': {'foo': 'bar'},
321+ 'id': 3,
322+ 'response': 'diff'
323+}
324+```
325+
326+**Action Required**
327+
328+You must [ack](#ack) each individual `fact` that comes in the event stream.
329+
330+### Kick
331+
332+A `kick` comes in when a subscription has been ended. You may be intentionally `kick`ed by the Gall agent to which you're subscribed, but certain network conditions can also trigger a `kick`. As a result, it's best to try and re[subscribe](#subscribe) when you get a `kick`, and if the resulting [watch ack](#watch-ack) is negative you can then conclude the `kick` was intentional and give up.
333+
334+| Key | JSON Type | Example Value | Description |
335+|------------|-----------|---------------|-----------------------------------------------|
336+| `id` | Number | `4` | Request ID of the initial `subscribe` action. |
337+| `response` | String | `'kick'` | The kind of response. |
338+
339+**Example**
340+
341+```json
342+{
343+ 'id': 4,
344+ 'response': 'kick'
345+}
346+```
347+
348+**Action Required**
349+
350+No action is required in response to a `kick`, but you may wish to try and re[subscribe](#subscribe).
351+
352+# Scry
353+
354+A scry is a read-only request for some data.
355+
356+A scry takes the form of an [authenticated](#authentication) HTTP GET request to a URL path with the following format:
357+
358+```
359+http{s}://{host}/~/scry/{app}{path}.{mark}
360+```
361+
362+The `{app}` is the name of the Gall agent you want to query, for example `graph-store`.
363+
364+The `{path}` is a scry endpoint of the Gall agent in question. Eyre will always scry with a care of `%x`, so the `{path}` needn't specify that. For example, the `/x/keys` scry endpoint of `graph-store` would just be specified as `keys`.
365+
366+The `{mark}` is the type you want returned. It needn't just be `json` as with the channel system, it can be any `mark`, with two conditions:
367+
368+1. It must be possible to convert the `mark` produced by the specified scry endpoint to the `mark` you want returned.
369+2. It must be possible to convert the `mark` you want returned to a `mime` `mark`, otherwise Eyre can't encode it in the HTTP response.
370+
371+If your session cookie is invalid or missing, Eyre will respond with a 403 Forbidden status. If the scry endpoint cannot be found, Eyre will respond with a 404 Missing status. If the `mark` conversions can't be done, Eyre will respond with a 500 Internal Server Error status. Otherwise, Eyre will respond with a 200 OK status with the requested data in the body of the HTTP response.
372+
373+See the [Scrying](@/docs/arvo/eyre/examples.md#scrying) section of the [Examples](@/docs/arvo/eyre/examples.md) document for a practical example.
374+
375+# Spider
376+
377+Spider (the Gall agent that manages threads) has an Eyre binding which allows threads to be run via [authenticated](#authentication) HTTP POST requests.
378+
379+Spider is bound to the `/spider` URL path, and expects the requested URL to look like:
380+
381+```
382+http{s}://{host}/spider/{inputMark}/{threadName}/{outputMark}
383+```
384+
385+The `inputMark` is the `mark` the thread takes. The `threadName` is the name of the thread, e.g. `foo` for `/ted/foo/hoon`. The `outputMark` is the `mark` the thread produces. You may also include a file extension though it doesn't have an effect.
386+
387+When Spider receives an HTTP request, the following steps happen:
388+
389+1. It converts the raw body of the message to `json` using `de-json:html`
390+2. It creates a `tube:clay` (`mark` conversion gate) from `json` to whatever input `mark` you've specified and does the conversion.
391+3. It runs the specified thread and provides a `vase` of `(unit inputMark)` as the argument.
392+4. The thread does its thing and finally produces its result as a `vase` of `outputMark`.
393+5. Spider creates another `tube:clay` from the output `mark` to `json` and converts it.
394+6. It converts the `json` back into raw data suitable for the HTTP response body using `en-json:html`.
395+7. Finally, it composes the HTTP response and passes it back to Eyre which passes it on to the client.
396+
397+Thus, it's important to understand that the original HTTP request and final HTTP response must contain JSON data, and therefore the input & output `mark`s you specify must each have a `mark` file in `/mar` that includes a conversion method for `json -> inputMark` and `outputMark -> json` respectively.
398+
399+See the [Running Threads With Spider](@/docs/arvo/eyre/examples.md#running-threads-with-spider) section of the [Examples](@/docs/arvo/eyre/examples.md) document for a practical example.
arvo/eyre/eyre.md+26−690
@@ -2,720 +2,56 @@
22title = "Overview"
33weight = 1
44template = "doc.html"
5−aliases = ["/docs/learn/arvo/eyre/"]
65+++
76
8−*Current docs on Eyre are out of date. Until they are updated this doc remains for historical purposes*
7+Eyre is the webserver vane.
98
9+HTTP messages come in from outside and Eyre produces HTTP messages in response. In general, apps do not call Eyre; rather, Eyre calls apps. Eyre has a number of ways to handle such HTTP requests which we'll briefly describe.
1010
11−Our HTTP server.
11+# Authentication
1212
13−Unix sends http messages to `%eyre`, and `%eyre` produces http messages
14−in response. In general, apps and vanes do not call `%eyre`; rather,
15−`%eyre` calls apps and vanes. `%eyre` uses `%ford` and `%gall` to
16−functionally publish pages and facilitate communication with apps.
13+Most types of requests require the client provide a valid session cookie which is obtained by authenticating with your ship's web login code. Authentication is documented in the [Authentication](@/docs/arvo/eyre/external-api-ref.md#authentication) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) documentation.
1714
18−`%eyre` primarily parses web requests and handles them in a variety of
19−ways, depending on the control string. Nearly all of these are
20−essentially stateless, like functional publishing with `%ford`.
21−Additionally, there's a fairly significant component that handles
22−`%gall` messaging and subscriptions, which must be stateful.
15+# The Channel System
2316
24−## Reference
17+Eyre's channel system is the primary way of interacting with Gall agents from outside of Urbit. It provides a simple JSON API that allows you to send data to apps and subscribe for updates from apps. Updates come back on a SSE ([Server Sent Event](https://html.spec.whatwg.org/#server-sent-events)) stream which you can easily handle with an EventSource object in Javascript or the equivalent in whichever language you prefer.
2518
26−### State
19+The channel system is designed to be extremely simple with just a handful of `action` and `response` JSON objects to deal with so you can focus on the logic and data structures of your external app and the Gall agent with which you're interacting.
2720
28−Stored
21+Detailed documentation of the channel system's JSON API is provided in the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document with corresponding examples in the [Examples](@/docs/arvo/eyre/examples.md#using-the-channel-system) document.
2922
30−- `++bolo`
31−- `++cyst`
32−- `++stem`
23+# Scrying
3324
34−Runtime
25+Along with the channel system, Eyre also provides a way to make read-only requests for data which are called scries. While not technically part of the channel system, you'll likely use scries in conjunction with channel `action`s.
3526
36−- `perk`
37− + `perk-auth`
38−- `pest`
39−- `even`
27+Details of Eyre's scry API are in the [Scry](@/docs/arvo/eyre/external-api-ref.md#scry) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document.
4028
41−### Cores
29+# Spider Threads
4230
43−- `++handle`
44− + `++parse`
45− - `++as...`
46−- `++ya`
47−- `++ix`
31+Threads are like transient Gall agents which typically handle complex IO operations for Gall agents (you can read more about them [here](@/docs/userspace/threads/overview.md)). Spider (the Gall agent that manages threads) has an Eyre binding that allows you to run threads through Eyre.
4832
49−## Commentary
33+The [Spider](@/docs/arvo/eyre/external-api-ref.md#spider) section of the [External API Reference](@/docs/arvo/eyre/external-api-ref.md) document explains their usage, and the [Running Threads With Spider](@/docs/arvo/eyre/examples.md#running-threads-with-spider) section of the [Examples](@/docs/arvo/eyre/examples.md) document provides a practical example.
5034
35+# Generators
5136
52−Let us follow the loading of a simple cli app, as it bounces from
53−browser to server to browser and back.
37+Generators, which are like hoon scripts, can also be used through Eyre. Rather than having a predefined JSON API, they instead handle HTTP requests and return HTTP responses directly, and are therefore a more complex case that you're less likely to use.
5438
55−### Initial request
39+Their usage is explained in the [%serve](@/docs/arvo/eyre/tasks.md#serve) section of the [Internal API Reference](@/docs/arvo/eyre/tasks.md) documentation and a practical example is provided in the [Generators](@/docs/arvo/eyre/examples.md#generators) section of the [Examples](@/docs/arvo/eyre/examples.md) document.
5640
57−An http request for `http://sampel-sipnym.urbit.org/cli` will be [redirected](dns)
58−to the `%eyre` on ~sampel-sipnym, and come in as a `%this` task.
41+# Direct HTTP Handling With Gall Agents
5942
60−From arvo, requests enter `++call`, which after some type reification are passed
61−along to `++apex:ye`. In the case of a `%this` task, its components are
62−parsed(see `++zest:epur`, `++eat-headers`) and handed off to `++handle`, wrapped
63−in `++emule` to produce a `++fail` page in case of error. `++apex:handle` will
64−`++process` the request to a `pest` or a `++done` [core](/docs/glossary/core/), and in the former case
65−`++resolve` the pest into an outgoing card.
43+As well as the [Channel System](#the-channel-system) and [Scries](#scrying), it's also possible for Gall Agents to deal directly with HTTP requests. This method is much more complicated that the channel system so you're unlikely to use it unless you want to build a custom HTTP-based API or something like that.
6644
67−XX it also seems to affect the current ship, test that serving ship name is consistently correct
45+This method is explained in the [%connect](@/docs/arvo/eyre/tasks.md#connect) section of the [Internal API Reference](@/docs/arvo/eyre/tasks.md) document and a detailed example is provided in the [Direct HTTP Handling With Gall Agents](@/docs/arvo/eyre/examples.md#direct-http-handling-with-gall-agents) section of the [Examples](@/docs/arvo/eyre/examples.md) document.
6846
69−The pest is produced by `++process`, which will first further `++parse` the
70−request, and if this does not make the response immediately obvious,
71−`++process-parsed` the resulting `perk`.
47+# Eyre Documentation Sections
7248
73−`++parse` produces the `perk`, by attempting to interpret the `pork`(url path)
74−[`++as-magic-filename`](#mage), `++as-beam`, and `++as-aux-request`. In this
75−case, `/cli` is parsed by the second case as a `%beam` query to `/=cli=`: a path
76−which starts with a valid ship name is expected to be a full clay(well, ford)
77−path, and one starting with a term implies the current serving ship and a case
78−of `0`, the current revision.
49+- [External API Reference](@/docs/arvo/eyre/external-api-ref.md) - Details of Eyre's external API including the channel system's JSON API.
7950
80−XX spur: when the desks are merged, `/cli` shall point to `/=main=/pub/cli`
51+- [Internal API Reference](@/docs/arvo/eyre/tasks.md) - The `task`s Eyre takes and the `gift`s it returns.
8152
82−The parsed `perk` generates a `%f %boil` note, `mark`ed as its extension(here
83−defaulting to `%urb`) and `wire`d with `~` to return unaltered to the client. It
84−goes on to `++resolve` by being passed to `++ford-get-beam`, which translates
85−the perk it into a `%boil` `++ford-req`, adding an `++fcgi` path-segment
86−containing query string and `++fcgi-cred:for-client` auth information.
53+- [Scry Reference](@/docs/arvo/eyre/scry.md) - The scry endpoints of Eyre.
8754
88−`%ford`s translation of `/=cli=/hymn/hook` to a self-refreshing `%urb` html page
89−[deserves its own commentary](/docs/arvo/ford#commentary), but
90−we resume in `%eyre` when the `%made` sign arrives in `++take`, and soon after
91−`++axon:ye`. There the `wire`, or rather the `whir` it has been verified to be,
92−determines that the response should be served immediately. However, as the mark
93−is not `%mime`, another trip to `%ford` is required to encode it, on the same
94−wire; afterwards, the value of the `%mime` cage is verified to be of the correct type, and finally
95−delivered back up the requesting duct as a successful `%thou` HTTP response.
55+- [Data Types](@/docs/arvo/eyre/data-types.md) - Reference documentation of the various data types used by Eyre.
9656
97−XX `%cast %mime` used to be in ford-get-beam, is there a reason it was removed?
98−
99−## Back into the breach, or: auxilary requests
100−
101−Now, it was mentioned that this result is self-refreshing: the `%urb`
102−translation [door](/docs/glossary/door/) injects a `;script@"/~/on/{deps}.js"` into every page, `deps`
103−is a ford-readable hash of the set of resources that page construction depended
104−on.
105−
106−This triggers another `%this` request. Its handling is identical to that of
107−`/cli` up until `++parse`, where it is seen not `++as-beam` but
108−`++as-aux-request`(auxillary requests starting with `/~/` or `/~~/`).
109−`/on/[hash]` is a long-`%poll`, which `++process-parsed`, for a `.js` mark,
110−answers with a direct `%js`. Its contents are the static `++poll:js`, which
111−initiates the long-polling loop, run against an injected `urb.js` of
112−`{poll:[hash]}`.
113−
114−A `%js` `pest` is `resolve`d as a `text/javascript` success `%this`.
115−
116−When `poll.js` is received by the client, it opens an `XMLHttpRequest` for
117−`/~/on/{window.urb.poll}.json`, bringing us back to `%poll:process`.
118−
119−In the case of a non-`%js` `/~/on/`, `%poll:process-parsed` turns into a
120−`++new-dependency`, which stores the listening duct, and `pass-note`s a `%wasp`
121−with the deps-hash back to `%ford` whence it came. While this occured, the page
122−has loaded.
123−
124−Some indeterminate amount of time afterwards, with dropped `/~/on/{...}.json`s
125−being retried upon expiring and also being stored, a `%news` sign arrives in
126−`++axon`, and the hash in question is retrieved from the wire, and the listening
127−long-polls retrieved by the hash. Each receives a 205 "Reload parent view" HTTP
128−response, which `poll.js` dutifully executes, and a fixed typo of markdown is
129−rendered.
130−
131−## Authentication
132−
133−Now, while this accurately reflects the presentation of e.g. a markdown file,
134−`/cli` is an application front-end, and one that permits only owner access. Its
135−second script is `@"/~~/~/at/main/lib/urb.js"`, semantically equivalent to
136−`/~/as/own/~/at/main/lib/urb.js`, and handled as follows.
137−
138−In `++as-aux-request`, `%as %own` becomes `%auth %get our` perk, which
139−`++process` passes to `++process-parsed` passes to `++process-auth`. There, a
140−`yac` "ya" core is built `++for-client`: a `++cookie-prefix`, which is just the
141−serving ship name, is used to get a `++session-from-cookies`, here nil as the
142−client has no cookie set. In lieu of a cookie, a `++new-ya` is constructed, with
143−a random token `hole` and a `++new-cyst` which fills out `cyst` session state
144−from request data.
145−
146−Returning to `++process-auth`, `%get` checks if the yac is authenticated with
147−the requested credentials(`anon` requests are always granted), which for the
148−fresh new `cyst` is not the case (more on success [later](#auth-ok)). Unless
149−authenticating as a [foreign ship](#xeno), the only thing left is to
150−`++show-login-page`, which detects that the requested resource is not `%html`,
151−and produces a `%red` pest. For `%js`, `%red`irections `++resolve` to
152−`++auth-redir:js`, a line of javascript which prepends `/~~` to the url path.
153−
154−The owner-authenticated main page request similarly ends in `++show-login-page`,
155−which for the empty session is an `[%htme ++login-page:xml]`, `resolve`d to
156−`++give-html` with a 401 "unathorized".
157−
158−The login page shows a simple prompt, and requests `/~/at/auth.js` to handle the
159−submission. And so we are, once again, attempting to divine if what we're doing
160−makes sense `++as-aux-request`.
161−
162−To understand `/~/at`, there will first be a brief diversion to `~/auth.json`.
163−`auth.json`, perk `[%auth %json]`, in `++process-auth` serves `++stat-json:ya`,
164−containing such information as the serving ship, which identities are associated
165−with this session, and `oryx`, a CSRF token. An oryx must be present on all
166−stateful requests, in this case executing a log in. It also saves the new/old
167−session using `abet`.
168−
169−XX explain `ixor` here and not [later](#ixor)?
170−
171−`/~/at` is an alternate interface, which injects `auth.json` data into the
172−requested file. `/~/at/auth.js`, then, is a request for the built-in `auth:js`
173−(parsed to and processed from an `[%auth %js ~]` perk), with session data added
174−as `window.urb`. And indeed, ``[`%js /~/at/auth]`` is parsed to
175−``[%auth at [`%js /auth]``, which in `++process-auth` is re-`process`ed to
176−`[%js ++auth:js]`, which is `++resolve`d after an `++add-json` of
177−the relevant data. The yac cookies are also passed to `resolve`, which
178−`++add-cookies` injects into the `httr`.
179−
180−It is at this point that there is first occasion for user input, namely the password.
181−
182−The `auth:js` script sends a `PUT` request, also to `/~/auth.json`. In `parse`,
183−the first nontrivial `++check-oryx` occurs, `++grab-body` the request oryx and
184−ensuring it is recorded for the session. The request parsed with `++need-body`
185−to a `[%auth %try {password}]` perk. `%get:process-auth` checks it against
186−`++load-secret`, upon success updates the session with `++logon:ya`, and
187−serves a fresh `auth.json` which reflects the changed `user`. Upon receiving
188−this, the page is refreshed to retry the original request.
189−
190−### Post-authentication: app communication.
191−
192−Upon refresh, `/~~/cli` brings us for the third time to `%get:process-auth`, but
193−this time the cookie is set, and the `yac` fetched contains the serving ship as
194−authenticated. The `++handle` sample is updated to reflect the requesting ship,
195−and the `process` continues for the rest of the pork, once again serving the
196−ford page.
197−
198−The `/~/on/[deps].json` poll starts anew, and `/~~/~/at/main/lib/urb.js` we now
199−know to serve the window.urb necessary to make requests, and the `urb.js`
200−standard library which extends it with a number of wrappers to them and other
201−useful functions.
202−
203−One of those functions is `urb.bind`, which is used to subscribe to application
204−data. Userspace javascript sets `urb.appl` to `/tic`, and binds `lines` to a
205−`;pre;` text display, using a callback.
206−
207−This triggers a `PUT` to `/~/is/{ixor}/cli/lines.json`, where `ixor` is a hash
208−of `oryx` that identifies the connection. `++as-aux-request`, an `%is` is a
209−`%subs` subscription update update, which for `%put` forwards to
210−`++add-subs:ix`, the ix core fetched `++for-view` by hashing the request
211−`++oryx-to-ixor`.
212−
213−A view has all the state associated with a client that must be
214−remembered between events. In this case, this is what app/path the request duct
215−is associated with; but mainly, `++add-subs:ix` will `pass-note` to `%gall` so
216−it `%show`s the data on the path, current and future.
217−
218−This will immediately(assuming the ship is local) result in a `%nice` by the
219−`/cli` app, returning `{ok:true}` `++nice-json` to `urb.bind`'s second callback
220−as `{ok:true}`. The initial `%rush` results also arrive, and in `++axon` are
221−converted to json using `++back`(ford `%cast` wrapper), and when `%made` get
222−passed to `++get-rush:ix`. There the source application/path are decoded by
223−duct, and then the full event goes to `++get-even`; `++add-even` inserts it to
224−the queue, and as there is no long poll it simply stays there.
225−
226−Upon receipt, the client realizes the long-poll isn't actually running, so that
227−is started using `urb.poll`. At `/~/of/{ixor}`, perk
228−`[%view ixor ~ {sequence-number}]`, it is `process`ed by `++poll:ix` (the cyst
229−is retrieved by `++ire-ix` form global state, using the perk `ixor`): the
230−sequence number is in the past, so the previously received `%rush` is
231−`++give-even`. After deleting the previous message in the queue and invoking
232−`++pass-took` to signal `%gall` of this occurrence, the data is annotated with
233−the source app+path `++subs-to-json`, and returned to the polling duct.
234−
235−On the client, the user callback receives the `/cli` history, and displays it on
236−the page. The `/~/of` long poll is continued, this time reaching `++poll:ix`
237−with the "pending" sequence number, and being stored in the `cyst` for its troubles.
238−
239−Its next update proceeds idenitcally, but first it must be triggered, which
240−happens when the user enters "(add 2 2)\n", firing an `urb.send` from the event
241−handler. This sends a `POST` request to `/~/to/cli/json.json`, perk `%mess`,
242−`++process`ed to a `%g %mess`. Were the mark not `%json`, a `%ford` conversion
243−would occur first, and `%made:axon` would send the gall message proper. In
244−either case, eventually a `%mean` or `%nice` arrives, is encoded as json, and
245−sent to the client callback.
246−
247−## A path not taken: magic filenames
248−
249−The `/robots.txt` and `/favicon.(ico|png)` files are static, and served
250−immediately when caught by a `++parse`.
251−
252−XX index.html?
253−
254−## A path not taken: foreign auth
255−
256−While this example details a login `/~/as/own`, it is possible to be
257−authenticated as any ship on the network. A request for such seen in
258−`%get:process-auth` is passed to `++foreign-auth:ya`, which sends an
259−`%ames /lon` message to the ship in question. The foreign ship stores the
260−inquiry, calculates(the local) `++our-host` and responds with a `/hat`,
261−containing the redirection host, which is stored by `++foreign-hat`; it is later
262−used to send the client to a `/~/am` url on the foreign client, which acts as a
263−normal login page but later sends the client back. XX expand, basically the
264−status quo is you're logged in and `/~/as/foo` is ignored, just setting your
265−`urb.user` XX
266−
267−
268−### A path not taken: deauthentication
269−
270−`/~/away`, perk `[%away ~]`, produces a static `++logout-page:xml`, which also
271−uses `/~/at/auth.js`, to send a `DELETE /~/auth.json`, perk `[%auth %del]`. This
272−executes `++logoff:ya` for the cookie session, resolving to `++abut` to wipe it
273−from memory.
274−
275−### A path not taken: unsubscription
276−
277−`DELETE /~/is/app/path/within` works much like `PUT /~/is/app/path/within`,
278−`++del-subs:ix` acting as reverse of `++add-subs` by deleting the duct binding
279−and sending `%g %nuke`.
280−
281−
282−XX unmentioned arms: abet, add-poll, adit, ames-gram, anon, ares-to-json, bolo, cyst, doze, even, ford-kill, get-mean, gift, give-json, give-thou, gram, hapt, hasp, host-to-ship, ix, ixor, js, kiss, load, mean-json, move, note, pass-note, perk, perk-auth, pest, poke-test, print-subs, render-tang, resp, root-beak, scry, ses-authed, ses-ya, sign, silk, sine, stay, stem, teba, titl, to-oryx, urb, wait-era, wake, whir, wush, xml, ya, ye
283−
284−### Appendix A: DNS
285−
286−The `*.urbit.org` domain can be used to access destroyers and cruisers. In the
287−common case oh hosted ships, this is done by dynamic DNS directly to the hosting
288−instance. We do not speak of the uncommon case. When ports are blocked and
289−infrastructure crumbles around you, only imported martian networking can be
290−trusted: the `%get` and `%got` grams are used to proxy `%this` requests and
291−`%thou` responses respectively.
292−
293−## Specification
294−
295−The `%eyre` vane serves one purpose: receiving inbound HTTP requests from browsers and clients pretending to be browsers. To facilitate this communication, `%eyre` does two things: 1. provide an API for traditional clients to talk to; and 2. provide a mechanism for saving state that allows the server to keep track of identities/sessions, subscription data, and active connections.
296−
297−This document outlines the following:
298−
299−1. [`perk`](#perk), a `pork` subset that defines what URLs the client can send to `%eyre`.
300−
301−2. [the values stored on the client](#client), both statically in cookies and dynamically as the `window.urb` object, which facilitate this transaction.
302−
303−3. [`task`](#task), the requests `%eyre` will accept.
304−
305−4. [`gift`](#gift), the responses it will give to those requests.
306−
307−5. [`note`](#note), the set of arvo requests that %eyre makes to the other vanes.
308−
309−6. [`whir`](#whir), a `wire` subset, the associated dynamic state
310−
311−7. [`sign`](#sign), the responses `%eyre` accepts
312−
313−8. [`bolo`](#bolo), the state stored between separate events.
314−
315−## 1. URL structure
316−
317−There exist several URL forms accepted by `%eyre`.
318−
319−### 1.1 Functional request
320−
321−The simplest of them is a static `%f` functional publish request:
322−
323−```
324− GET /[ship]/[desk]/[case]/path/to/file.[mark]
325−```
326−e.g.
327−
328−```
329− /~pittyp-pittyp/main/5/lib/urb.js
330−```
331−A `case` of 0 signifies the most recent version.
332−
333−If no file extension is provided, the default `mark` is `%urb`, which consists of `%html` injected with an auto-refresh script.
334−
335−A shorter form:
336−
337−```
338− /path/to.[mark]
339−```
340−is prepended with the [default request path](#prefix). For example, if `%eyre`
341−is configured with a root of `/<our>/main/0/pub`, then `/doc/arvo` is
342−interpreted as a request for `/=main=/pub/doc/arvo.urb`.
343−
344−Auxiliary paths start with `/~/`, and provide other functionality, such as:
345−
346−### 1.2 Auto-reload
347−
348−When a new version of a page becomes available, it is useful to propagate it to the client. The `%f` vane manages the particulars, and provides an update token along with all published pages. The `/~/on` long-polling endpoint makes use of that token, which is a hash of the server-stored dependency set.
349−- `/~/on/[hash].json` retuns `true` when a page may require updating.
350−- `/~/on/[hash].js` is a lightweight script that polls for the above. It is primarily used in error messages.
351−
352−### 1.3 Authentication
353−
354−Authenticated requests are accomplished through sessions, tracked with cookies which are set on the first such request.
355−- `/~/as/[user]/...` is an authenticated request to `...`, where `user` can be a `@p` ship, `'own'`, `'any'`, or `'anon'`.
356− + `'anon'` is a randomly-generated per-session submarine, and requires no further authentication.
357− + `'own'` represents the serving ship. The short form of `/~/as/own/` is `/~~/`
358− + `'any'` requires a network ship, chosen with a prompt if unknown. The short form of `/~/as/any/` is `/_/`
359− + Auth requests are handled in three ways:
360− + I. If the session is associated with the `ship`, serve `...`, storing the ship as the session's default ship. For example, `/~/as/sivtyv-barnel/main/pub/test.html` is an authenticated request of `/main/pub/test.html` with the identity of `~sivtyv-barnel`.
361− + II. If the session is not associated with the `ship` in the path, the client is redirected to a login page, where a password can be entered. Successful authentication results in a page refresh to the requested path.
362− + III. otherwise, [send a message](#foreign) to the claimed ship, and redirect the user to `https://[foreign-host]/~/am/[ses]/...#[current-host]&?code=[code]`
363−- `/~/am/[ses]/...#original-host` similarly serves a login page. Upon success, inform the `ship` of the success and redirect it back to `http://[original-host]/~/as/<this-ship>/...`
364−- `/~/away.html` is a log-out page.
365−- `/~/auth.json` returns `{ship,oryx,user,auth}`: the serving ship, a CSRF token, active user, and all allowed users respectively.
366−- `/~/at/{...}.js` is an alternate form of `/~/auth.json`, which injects a line into the served js file that sets `{ship, oryx, user, auth}` on the `window.urb` object.
367−
368−So far, all the paths specified have been GET requests. Authentication, however, requires sending data. This is also done at the `/~/auth.json` endpoint.
369−- `POST {oryx,ship,code} /~/auth.json?PUT` is used by the login script to authorize a user, and returns the same result as `GET`, additionally containing either`{ok:true}` or `{fail:'type',mess:"Error message"}`
370−- `POST {oryx,ship?} /~/auth.json?DELETE` revokes authorization. Response as above.
371−
372−### 1.4 Messaging
373−
374−- `POST {oryx, wire, xyro} /~/to/[app]/[mark].json`, where `xyro` is data that will be converted to the `mark`. In the simplest case, `/~/to/hello/json.json` will pass `xyro` through verbatim, sending `[%json xyro]` to the `++poke` arm of app `%hello`.
375−- `POST {oryx, wire, xyro} /~/to/<ship>/[app]/[mark].json` is a foreign message send, as above.
376−
377−### 1.5 Subscriptions
378−
379−- `/~/of/[ixor]` is an `EventSource`: a conceptually infinite file containing a stream of events. By default, it sends a newline every 30 seconds serving to signal that the connection is alive to both the server and IP middleware.
380− + `/~/of/[ixor]?poll={n}` is a long-polling fallback interface. Produces event number `{n}`, blocking until it occurs. Its contexts can be affected by `POST` requests with a body of `{oryx, wire}`, and a query string of `PUT` or `DELETE`. They return either `{mark}`(which may be `null`), or [`{fail, mess}`](#mean-json)
381−- `/~/in/[hash].json` is a dual to [`/~/on`](#on-change). It binds `mod` events, which echo the requesting token.
382−- `/~/is/[app]/path/to.[mark]` binds `rush` events, formatted with a first line of `[app] /path/to`, and the rest containing subscription data. Additionally, `mean` events formatted similarly may arrive, also converted to the relevant mark.
383−
384−
385−
386−### 1.6 Ablative
387−
388−These interfaces will temporarily exist to aid development, and are to be considered unstable.
389−- `/~/debug/...` access normally inaccessible pages. For example, `/~/debug/as.html` will present the login page, regardless of current session status.
390−
391−
392−## 2. Client state
393−
394−Some information is stored on, and provided to, browser clients
395−
396−### 2.1 Cookies
397−
398−Authenticated users receive a cookie on the domain of `*.urbit.org`. The cookie contains a client session token, keyed by the serving ship.
399−
400−### 2.2 Authentication
401−
402−It is common(e.g. by the `%urb` mark) to set window.urb to the contents of `/~/auth.json`:
403−- `ship` is the serving ship
404−- `oryx` is a unique CSRF token that identifies this view, bound to the session cookie
405−- `ixor` is a hash of `oryx`, used as an insecure view identifier
406−- `user` is the authenticated/generated ship name
407−- `auth` is a list of identities usable by this session
408−
409−### 2.3 Client library
410−
411−To this object, `/main/lib/urb.js` adds helpers:
412−- `app` is an optional app name to send messages to by default
413−- `send({data,mark?='json',app?=urb.app,ship?}, cb?)` delivers messages
414−- `bind({path,app?=urb.app}, cb)` subscribes by path
415−- `drop({path,app?=urb.app}, cb?)` pulls the subscription
416−- `util` is an object containing methods for converting between JavaScript types and Hoon [atom](/docs/glossary/atom/) auras.
417−
418−## 3. Requests
419−
420−## `[%born port=@ud]`, unix init
421−
422−When the `vere` process is re/started, a TCP port is bound, HTTP requests on which are the scope of this document. The `%born` gift informs eyre of this occurrence, which in turn updates [its state.](#bolo)
423−
424−**Gifts given in response:** none.
425−
426−## `[%hiss p=mark q=cage]`, outbound http
427−
428−Userspace http request, converted by `%ford` into an actual `hiss`.
429−
430−**Gifts given in response:** a `%sigh`
431−
432−### 3.1 `[%this httq]`, inbound http
433−
434−The primary `%eyre` request type comes from the host system, and constitutes an inbound http request. It consists of five parts:
435−
436−I. `p=[? @if]`: a loobean determining whether the request is being made over https, and the client source, an IPv6 address possibly encoding an IPv4 one as `.0.0.0.0.0.ffff.wwxx.yyzz`
437−
438−II. `q=meth`, an http method
439−
440−III. `r=@t`, the unparsed URL
441−
442−IV. `s=mess`, an associative list of header keys/values
443−
444−V. `t=(unit octs)`, the request body, if any.
445−
446−After `r` is parsed to a `purl`, the `pork`(relative path) determines the resource being served. The first step in handling an http request is [classifying its intent](#perk).
447−
448−- A ford request results in a [`%boil` note](#boil).
449−- `/~/[name].js` is generated from [session](#sink) or [view](#stem) state, and [served](#mime) as `%js`.
450−- `/~/am` generates a login page.
451−- `/~/as` is resolved further if authenticated, generates a similar login page if the claimed ship is local, and otherwise is saved to [session state](#sink) and sends a ["login" `%a` message](#lon) to the foreign ship.
452−- `/~/at` and `/~/auth.json` generate a new `oryx` and store it in the [session state](#sink).
453−- `/~/in` and `/~/is` affect [view state](#stem), possibly sending subscriptions or unsubscriptions to `%f` and `%g` respectively, and are generated from view state.
454−- `/~/on` is saved to the `bolo` by `hash`, and translated to a [`%wasp` note](#wasp).
455−- `/~/of` fails if the `ixor` is unknown, and otherwise is stored in the `ixor`, receiving a partial response and all events after its [last-seen header](#). If it has a `poll` parameter, the response is full, and only occurs if the body is non-empty. Otherwise the oryx is saved as a [live](#live) request in case of cancellation.
456−- `/~/to` transforms into a [`%g` message](#mess).
457−
458−**Gifts given in response:** a `%thou`, or a [`%that`](#that) followed by multiple `%thar`s.
459−
460−### 3.2 `[%thud ~]`, inbound close
461−
462−Sent when an unresponded-to request is cancelled. The [live](#live) effect of the request is looked up, and
463−- `%exec` ford boil requests are cancelled with `[%exec ~]`
464−- `%wasp` ford deps requests are cancelled with `[%wasp |]`
465−- `%poll` session polls `%rest` the session heartbeat timeout
466−
467−### 3.3 `[%thin p=@ud]`, delivery failure
468−
469−Sent when a partial [response](#that) or [body](#thar) fails to arrive. Its `duct` is the same as that of the original request. This is handled by [waiting](#wait) for the client to reconnect, and if this not occur, unwinding all subscription state.
470−
471−
472−**Gifts given in response:** None.
473−
474−### 3.4 ``[%wart sock [path *]]``, inbound message
475−
476−Sometimes, messages are received from other ships. They are expected to take the from of a `gram`.
477−
478−**Gifts given in response:** [`%nice` or `%mean`](#ack).
479−
480−#### 3.4.1 `gram`
481−
482−There are three messages of note, all concerning authentication
483−- `[/lon ses]` is a login request, which contains the session wishing to authenticate.
484−- if the session is already authorized, a reply of `[/aut ses]` from (%eyre on) a foreign ship prescribes that the session is henceforth allowed to act on its behalf. All waiting `/~/as` are resolved as successful.
485−- otherwise, `[/hat ses hart]` contains the ship's preferred hostname. This can then be used to redirect the client. All waiting `/~/as` are given `307 Redirect`s to `/~/am` on the provided host.
486−
487−**Gifts given in response:** nice?
488−
489−## 4. Responses
490−
491−### 4.1 `[%nice ~]`, `[%mean ares]`, network acknowledgement
492−
493−A `%nice` is given upon receiving an [ames message](#gram), indicating succesful receipt. `%mean` is currently unused directly, but reserved for error conditions.
494−
495−## `[%sigh p=cage]`, inbound http response
496−
497−An HTTP response gets converted to the requested mark, or `%tang` in case of error.
498−
499−### 4.2 `[%thou httr]`, full HTTP response
500−
501−Most requests are served with one coherent response, consisting of
502−- `p=@ud`, an HTTP status code
503−- `q=mess`, response headers
504−- `r=(unit octs)`, an optional body
505−
506−### 4.3 `[%that httr]`, partial HTTP response
507−
508−[EventStream responses](#of-ixor) consist of multiple sequential chunks. Treated as `%thou`, except the request is kept open.
509−
510−### 4.4 `[%thar (unit octs)]`, partial HTTP body
511−
512−Complementing `%that`, `%thar` is a body chunk, containing an event. An empty `%thar` signals for the connection to be closed.
513−
514−Body chunks, besides `[1 '\0a']`(a heartbeat newline), are encoded from `even` events. The stem becomes the [`event` field](#eventsource), and the content, `data` lines.
515−
516−#### 4.4.1 `even`, event types
517−
518−There are three events that a [client subscription](#subs) will be given.
519−
520−- `[%news hash]` is a `%f` update, and contains the relevant dependency token.
521−- `[%mean [term path] ares]` is a sourced subscription error.
522−
523−## 5. Vane requests
524−
525−### 5.1 ``[%a %wont sock `[path *]`gram]``, outbound message
526−
527−The `%a` interface provides conveyance of [messages](#gram) over UDP.
528−
529−Signs a `%woot` upon message arrival.
530−
531−
532−All open [subscriptions](#of-ixor) require a "heartbeat" newline every `~s30`. When this fails to arrive, a complementary timer is set for `~m1`, after which the client is considered to have departed.
533−The `%b` timer interface is used to schedule the next such event, or cancel past scheduled ones when a connection closes.
534−
535−Signs a `%wake` upon timer activation.
536−
537−### 5.3 `[%f %wasp @uvI]`, dependency listen
538−
539−Knowledge of filesystem changes, requested by `/~/on` and `/~/in`, is requested the `%wasp` note. It contains the hash token which identifies a set of dependencies to query. Saved as a (live[live](#live)] request in case of cancellation when caused by `/~/on`.
540−
541−Signs a `%writ` upon change.
542−
543−### 5.4 `[%f %exec (unit silk)]`, functional transformations
544−
545−The `%f` interface converts [nouns](/docs/glossary/noun/) from one form to another. An empty unit represents cancellation.
546−
547−Signs a `%made` containing the computation result.
548−
549−The `silk`s used are as follows:
550−
551−### `[%cast %mime %boil mark beam [%web span ~]]`, file load
552−
553−The simplest functional request is the construction of a page. Saved as a [live](#live) request in case of cancellation.
554−- The `mark` is the request extension, defaulting to `%html`.
555−- A `beam`(path in `%clay`) is decoded from the request path.
556−- A `/web/<nyp ced quy>` virtual path is appended, span-encoding method, auth, and query string.
557−
558−### `[%cast mark %done ~ cage]`, convert
559−
560−This is used when communicating with apps, in both directions.
561−- Client messages are encoded as JSON objects, but can contain many different marks. Ones sent to non-`json.json` endpoints are `%cast` to he relevant mark, with a `cage` of `[%json p:!>(*json) jon]`, prior to being sent onwards to applications with `[%g %mess]`.
562−- Subscription responses also come in arbitrary marks, but are required to be sent as whichever mark an endpoint is subscribed to. They get `%cast` prior to being sent back as a `%that` EventSource segment.
563−
564−### 5.5 `%g`, app actions
565−
566−The end goal of many a userspace `hymn.hook` is to provide UI for a `%gall` app. To accommodate this, various functionality needs to be interfaced with.
567−
568−### `[%mess hapt ship cage]`, app message
569−
570−After a `/~/to` POST has been received, and possibly converted to the correct mark, it is sent to `%g` for processing. The `hapt` is the destination, the `ship` is the source, the `cage` is the marked message data.
571−
572−Signs a `%nice` or `%mean`, in userspace or upon crashing.
573−
574−### `[%show hapt ship path]`, app subscription
575−
576−An `/~/is` PUT, if not already registered, results in a new subscription. A request for such contains the destination `hapt`, requesting `ship`, and app-internal `path`.
577−
578−Signs a `%nice` on init, `%rush` on data, and a `%mean` in subscription termination.
579−
580−### `[%took hapt ship]`, %rush confirmation
581−
582−A `%took` must be sent to acknowledge the receipt of subscription data, which in this case occurs automatically.
583−
584−Causes no signs.
585−
586−### `[%nuke hapt $|(ship [ship path])]`, subscription cancel
587−
588−An `/~/is` DELETE is used to remove a subscription, and is converted straightforwardly to a `%nuke`. Additionally, when a client disconnects, all of its subscriptions are `%nuke`d to reflect their expiration.
589−
590−Signs an empty `%mean` for each open subscription that is closed.
591−
592−## 6. In-flight metadata
593−
594−Various state can be associated with requests, but not necessarily be returned in responses to them.
595−
596−### 6.1 `~`, dropthrough
597−
598−If the response should be sent statelessly further up the duct, the `wire` is empty. This is used in `%f` pure functional page generation.
599−
600−### 6.2 `[?(%y %n) ...]`, stability
601−
602−The first element of a [`%b` timer](#wait) path distinguishes between live(%y) and dying(%n) channels.
603−
604−### 6.3 `/of/[ixor]`, view
605−
606−Designates which stream to act upon. Present on `%b` timer cards.
607−
608−### 6.4 `/on/<deps>`
609−
610−Present on `%f` dependency news. Looked up in [the state](#bolo) to see if any response is necessary.
611−
612−### 6.5 `/to/<hasp>/<ship>`, app
613−
614−Present on `%f` translations of message marks
615−
616−### 6.6 `/is/[ixor]/{hasp path}`, subscription
617−
618−Subscription requests. Present on `%g` subscription requests, and `%f` translations of [`%rush` subscription data](#show).
619−
620−## 7. Vane responses
621−
622−The goal of requests is to cause some manner of result. Specifically,
623−
624−### 7.1 `[%a %woot ship coop]`, acknowledgement
625−
626−A [message](#mess) which has been acknowledged remotely.
627−
628−### 7.2 `[%b %wake ~]`, timer
629−
630−Timer activate. If this is a `%y` [timer](#wire-live), send a newline to each `/~/of/[oryx]`; if `%n` and the `oryx` still has no listeners, wipe its state/subscriptions.
631−
632−### 7.3 `[%f %news ~]`, dependency update
633−
634−This message signifies a `hash` has changed, and listeners to it should be updated. Results in [`%news` events](#even-news) to concerned streams, and [full responses](#thou) to relevant long-polls.
635−
636−### 7.4 `[%f %made (each bead (list tank))]`, compute result
637−
638−Further action depends on the [`wire`](#whir). It can:
639−- Be empty, designating direct request data, which is [served](#mime) back up the `duct`.
640−- Contain [app and requester identities](#wire-to), which designates an app message has been converted to the correct `mark`, and can now be [sent to the app](#mess) with an empty `wire`.
641−- Contain an `oryx`, app, and `path`, designating subscription data. If the subscription is active in the relevant `stem`, it is acknowledged with a `%took` and given as a [`%rush` event](#even-rush) to all listeners. Otherwise, the subscription is `%nuke`d.
642−
643−### 7.5 `%g`, applications
644−
645−The `%g` interface sends several responses.
646−
647−### `[%nice ~]` and `[%mean ares]`, acknowledgment
648−
649−These are given as a response to `%mess`, with an empty wire, and `%show`s, with a [subscription wire](#wire-is).
650−The former is [served](#mime) back to the requester(i.e. the remaining duct), and the latter returned to the client.
651−
652−#### 7.5 `[%rush cage]`, subscription data
653−
654−A `%rush` arrives on a [subscription wire](#wire-is), and is then sent [for conversion](#done) to the correct mark. An unexpected `%rush` is `%nuke`d.
655−
656−## 8. Server state
657−
658−There is a quantity of data that persists between events.
659−
660−### 8.1 Global
661−
662−- `path` the default path which is prepended to relative plain requests. Initialized to `/<our>`, the serving ship; this interprets the first element of requests as a desk, and injects a `case` of `0`.
663−- `(jar ship hart)` remembered hostnames in order of preference, made accessible through `.^`
664− + The default values(for self) are `http://<ship>.urbit.org:80` if not on a fake network, followed by `https://0.0.0.0:[port]`.
665−- `(jug deps (each duct oryx))`, `/~/on` and `/~/in` endpoints listening to `%c` updates.
666−- `(map duct live)`, inbound request state
667−- `(map ixor oryx)`, open `/~/of` streams.
668−- `(map oryx stem)`, open view state.
669−- `(map hole sink)`, session state.
670−- `(map hole ,[ship ?])`, foreign session names, along with their origin ships and whether they are authorized to act on our behalf.
671−
672−### 8.2 `live`, per-request state
673−
674−To honor request cancellations, each unserved request must track which effect it is causing.
675−+ `[%exec whir]` if it is a ford data request
676−+ `[%wasp (list @uvH)]` if it is a ford dependency poll
677−+ `[%xeno ship]` if this is a proxied request
678−+ `[%poll ixor]` if this is a session long-poll
679−
680−### 8.3 `sink`, per-session state
681−
682−Each `hole` has associated authentication state.
683−- `priv`, a random secret that verifies the session, stored in cookie.
684−- `[ship (set ship)]`, the `ship` a session is acting as and any others it has been authorized with.
685−- `(jug ship ,[path duct])`, authentication `/~/as` requests waiting on foreign ships.
686−- `(set oryx)`, views associated with this session. Dual of `hole` in `stem`.
687−
688−### 8.4 `stem`, per-view state
689−
690−Each `oryx` has active subscription state.
691−- `hole`, session in which this view resides. Dual of `(set oryx)` in `sink`.
692−- `ixor`, a cached hash of the `oryx` that is used as a subscription id, by the `/~/of` EventStream.
693−- `[,@u (map ,@u even)]`, queued [events](#even). Has a maximum size.
694−- `(unit ,[duct @u ?])`, http connection, its last received event, and whether it is a long-poll request.
695−- `(set deps)`, subscribed `/~/in` points. Mirrored in `bolo`.
696−- `(map ,[hasp path] mark)`, subscribed `/~/is` points
697−- `(que duct)`, where any `%nice`/`%mean
698−
699−## Appendix A: Glossary
700−
701−- An `oryx` is a CSRF token used for [authenticated requests](#auth)
702−- `mean.json` is a rendering of hoon `ares`: an error message formatted as `{fail:'type',mess:"Error message"}`
703−- `urb.js` is the standard client-side implementation of the `%eyre` protocols, normally found in `/=main=/lib`
704−- The act of "serving", refers to the wrapping of a `%mime` cage in an HTTP `200 Success` response, and errors or other marks being [sent to ford](#done) for conversion. Inside a `sign`, this conversion occurs along the same [`wire`](#wire); otherwise, the `wire` is [empty](#wire-drop).
705−
706−## Appendix B: EventSource
707−
708−UNIMPLEMENTED
709−
710−For more information, see <http://dev.w3.org/html5/eventsource/>
711−
712−An EventSource is a stream of events, encoded in a conceptually infinite `GET` request. Each event is formatted as
713−```
714− http
715− id: {number}
716− event: {type}
717− data: {contents}
718− data: {more-contents}
719−```
720−
721−Data lines are joined by ASCII `10` newline characters; multiple newlines signify separate events. The `id` is used in a `Last-Event-ID` HTTP request header upon reconnection.
57+- [Examples](@/docs/arvo/eyre/examples.md) - Practical examples of the different ways of using Eyre.
arvo/eyre/scry.mdnew file+233
@@ -0,0 +1,233 @@
1++++
2+title = "Scry Reference"
3+weight = 4
4+template = "doc.html"
5++++
6+
7+## Contents
8+
9+- [Introduction](#introduction)
10+- [/x/cors](#xcors) - CORS settings.
11+ - [/x/cors/requests](#xcorsrequests) - Requested origins.
12+ - [/x/cors/approved](#xcorsapproved) - Approved origins.
13+ - [/x/cors/approved/\<origin\>](#xcorsapprovedorigin) - Check if origin approved.
14+ - [/x/cors/rejected](#xcorsrejected) - Rejected origins.
15+ - [/x/cors/rejected/\<origin\>](#xcorsrejectedorigin) - Check if origin rejected.
16+- [/x/authenticated/cookie/\<cookie\>](#xauthenticatedcookiecookie) - Check if cookie authenticated.
17+- [bindings](#bindings) - URL path bindings.
18+- [connections](#connections) - Open http connections.
19+- [authentication-state](#authentication-state) - Authentication details.
20+- [channel-state](#channel-state) - Details of each channel.
21+- [host](#host) - Host details.
22+
23+# Introduction
24+
25+Here are all of Eyre's scry endpoints. There's not too many and they mostly deal with either CORS settings or aspects of the state of connections.
26+
27+The first few with a `care` of `x` are a scry like `.^(<type> %ex /=//=/<some-path>)` (note the empty `desk`). The rest have no `care` and the tag replaces the `desk` like `.^(<type> %e /=<something>=)`.
28+
29+All examples are from the dojo.
30+
31+# `/x/cors`
32+
33+An `x` scry with a `path` of `/cors` will return Eyre's CORS origin registry. The type returned is a [cors-registry](@/docs/arvo/eyre/data-types.md#cors-registry) which contains the `set`s of approved, rejected and requested origins.
34+
35+Example:
36+
37+```
38+> .^(cors-registry:eyre %ex /=//=/cors)
39+[ requests={~~http~3a.~2f.~2f.baz~.example}
40+ approved={~~http~3a.~2f.~2f.foo~.example}
41+ rejected={~~http~3a.~2f.~2f.bar~.example}
42+]
43+```
44+
45+## `/x/cors/requests`
46+
47+An `x` scry with a `path` of `/cors/requests` will return the `set` of pending origin requests. These are origins that were in an `Origin: ...` http header but weren't in the existing approved or rejected sets. The type returned is a `(set origin:eyre)`.
48+
49+Example:
50+
51+```
52+> .^(requests=(set origin:eyre) %ex /=//=/cors/requests)
53+requests={~~http~3a.~2f.~2f.baz~.example}
54+```
55+
56+## `/x/cors/approved`
57+
58+An `x` scry with a `path` of `/cors/approved` will return the `set` of approved CORS origins. The type returned is a `(set origin:eyre)`.
59+
60+Example:
61+
62+```
63+> .^(approved=(set origin:eyre) %ex /=//=/cors/approved)
64+approved={~~http~3a.~2f.~2f.foo~.example}
65+```
66+
67+## `/x/cors/approved/<origin>`
68+
69+An `x` scry whose `path` is `/cors/approved/<origin>` tests whether the given origin URL is in the `approved` set of the CORS registry. The type returned is a simple `?`.
70+
71+The origin URL must be a cord-encoded `@t` rather than just the plain `@t`, so you'll have to do something like `(scot %t 'foo')` rather than just `'foo'`.
72+
73+Examples:
74+
75+```
76+> .^(? %ex /=//=/cors/approved/(scot %t 'http://foo.example'))
77+%.y
78+```
79+
80+```
81+> .^(? %ex /=//=/cors/approved/(scot %t 'http://bar.example'))
82+%.n
83+```
84+
85+## `/x/cors/rejected`
86+
87+An `x` scry with a `path` of `/cors/rejected` will return the `set` of rejected CORS origins. The type returned is a `(set origin:eyre)`.
88+
89+Example:
90+
91+```
92+> .^(rejected=(set origin:eyre) %ex /=//=/cors/rejected)
93+rejected={~~http~3a.~2f.~2f.bar~.example}
94+```
95+
96+## `/x/cors/rejected/<origin>`
97+
98+An `x` scry whose `path` is `/cors/rejected/<origin>` tests whether the given origin URL is in the `rejected` set of the CORS registry. The type returned is a simple `?`.
99+
100+The origin URL must be a cord-encoded `@t` rather than just the plain `@t`, so you'll have to do something like `(scot %t 'foo')` rather than just `'foo'`.
101+
102+Examples:
103+
104+```
105+> .^(? %ex /=//=/cors/rejected/(scot %t 'http://bar.example'))
106+%.y
107+```
108+
109+```
110+> .^(? %ex /=//=/cors/rejected/(scot %t 'http://foo.example'))
111+%.n
112+```
113+
114+# `/x/authenticated/cookie/<cookie>`
115+
116+An `x` scry whose `path` is `/authenticated/cookies/<cookie>` tests whether the given cookie is currently valid. The type returned is a `?`.
117+
118+The cookie must be the full cookie including the `urbauth-<ship>=` part. The cookie must be a cord-encoded `@t` rather than just a plain `@t`, so you'll have to do something like `(scot %t 'foo')` rather than just `'foo'`.
119+
120+Examples:
121+
122+```
123+> .^(? %ex /=//=/authenticated/cookie/(scot %t 'urbauth-~zod=0vvndn8.bfsjj.j3614.k40ha.8fomi'))
124+%.y
125+```
126+
127+```
128+> .^(? %ex /=//=/authenticated/cookie/(scot %t 'foo'))
129+%.n
130+```
131+
132+# `bindings`
133+
134+A scry with `bindings` in place of the `desk` in the `beak` will return Eyre's URL path bindings. The type returned is a `(list [binding:eyre duct action:eyre])` (see the [binding](@/docs/arvo/eyre/data-types.md#binding) & [action](@/docs/arvo/eyre/data-types.md#action) sections of the Data Types document for details).
135+
136+Example:
137+
138+```
139+> .^((list [binding:eyre duct action:eyre]) %e /=bindings=)
140+~[
141+ [ [site=~ path=<|~landscape js bundle|>]
142+ ~[/gall/use/file-server/0w2.EijQB/~zod/~landscape/js/bundle /dill //term/1]
143+ [%app app=%file-server]
144+ ]
145+ [ [site=~ path=<|~landscape|>]
146+ ~[/gall/use/file-server/0w2.EijQB/~zod/~landscape /dill //term/1]
147+ [%app app=%file-server]
148+ ]
149+ [ [site=~ path=<|~chat|>]
150+ ~[/gall/use/file-server/0w2.EijQB/~zod/~chat /dill //term/1]
151+ [%app app=%file-server]
152+ ]
153+ [[site=~ path=<|~ scry|>] ~[/dill //term/1] [%scry ~]]
154+ [[site=~ path=<|~ logout|>] ~[/dill //term/1] [%logout ~]]
155+ [[site=~ path=<|~ login|>] ~[/dill //term/1] [%authentication ~]]
156+ [[site=~ path=<|~ channel|>] ~[/dill //term/1] [%channel ~]]
157+ [ [site=~ path=<|spider|>]
158+ ~[/gall/use/spider/0w2.EijQB/~zod/bind /dill //term/1]
159+ [%app app=%spider]
160+ ]
161+ [ [site=~ path=<|.well-known acme-challenge|>]
162+ ~[/gall/use/acme/0w2.EijQB/~zod/acme /dill //term/1]
163+ [%gen generator=[desk=%home path=<|gen acme domain-validation hoon|> args=0]]
164+ ]
165+ [ [site=~ path=<||>]
166+ ~[/gall/use/file-server/0w2.EijQB/~zod /dill //term/1]
167+ [%app app=%file-server]
168+ ]
169+]
170+```
171+
172+# `connections`
173+
174+
175+A scry with `bindings` in place of the `desk` in the `beak` will return all open http connections that aren't fully complete. The type returned is a `(map duct outstanding-connection:eyre)` (see the [outstanding-connection](@/docs/arvo/eyre/data-types.md#outstanding-connection) section of the Data Types document for details).
176+
177+Example:
178+
179+```
180+> .^((map duct outstanding-connection:eyre) %e /=connections=)
181+{}
182+```
183+
184+# `authentication-state`
185+
186+A scry with `authentication-state` in place of the `desk` in the `beak` will return authentication details of all current sessions. The type returned is a [authentication-state](@/docs/arvo/eyre/data-types.md#authentication-state). The `p` field is the cookie sans the `urbauth-<ship>=` part.
187+
188+Example:
189+
190+```
191+> .^(authentication-state:eyre %e /=authentication-state=)
192+ sessions
193+{ [ p=0v3.kags1.hj7hm.6llrl.cga2j.eh1r7
194+ q=[expiry-time=~2021.5.20..08.44.27..39e0 channels={}]
195+ ]
196+}
197+```
198+
199+# `channel-state`
200+
201+A scry with `channel-state` in place of the `desk` in the `beak` will return details of the state of each channel. The type returned is a [channel-state](@/docs/arvo/eyre/data-types.md#channel-state).
202+
203+Example:
204+
205+```
206+> .^(channel-state:eyre %e /=channel-state=)
207+[ session
208+ { [ p='1601844290-ae45b'
209+ q
210+ [ state=[%.y p=[date=~2021.5.13..20.44.27..39e0 duct=~[//http-server/0v2.kmj6q/26/1]]]
211+ next-id=1
212+ last-ack=~2021.5.13..08.44.27..39e0
213+ events={[id=0 request-id=2 channel-event=[%poke-ack p=~]]}
214+ unacked={}
215+ subscriptions={}
216+ heartbeat=~
217+ ]
218+ ]
219+ }
220+ duct-to-key={}
221+]
222+```
223+
224+# `host`
225+
226+A scry with `host` in place of the `desk` in the `beak` will return host details of the ship. The type returned is a `hart:eyre`.
227+
228+Example:
229+
230+```
231+> .^(hart:eyre %e /=host=)
232+[p=%.n q=[~ 8.080] r=[%.y p=<|localhost|>]]
233+```
arvo/eyre/tasks.mdnew file+243
@@ -0,0 +1,243 @@
1++++
2+title = "Internal API Reference"
3+weight = 3
4+template = "doc.html"
5++++
6+
7+# Contents
8+- [Introduction](#introduction)
9+- [%live](#live) - *(Internal only)* - Notifies Eyre of HTTP(S) ports.
10+- [%rule](#rule) - *(Usually Internal)* - Sets TLS Cert or DNS binding.
11+- [%request](#request) - *(Internal only)* - Incoming HTTP request.
12+- [%request-local](#request-local) - *(Internal only)* - Incoming HTTP request from the local loopback port.
13+- [%cancel-request](#cancel-request) - *(Internal only)* - Notifies Eyre of a connection being closed externally.
14+- [%connect](#connect) - Bind a Gall agent to a URL.
15+- [%serve](#serve) - Bind a generator to a URL.
16+- [%disconnect](#disconnect) - Disconnect agent or generator from URL binding.
17+- [%code-changed](#code-changed) - *(Usually internal)* - Notifies Eyre of the web login code changing.
18+- [%approve-origin](#approve-origin) - Approve a CORS origin.
19+- [%reject-origin](#reject-origin) - Reject a CORS origin.
20+
21+# Introduction
22+
23+This document details all the `task`s you're likely to use to interact with Eyre, as well as the `gift`s you'll receive in response.
24+
25+The primary way of interacting with Eyre is from the outside with HTTP requests. As a result, most of its `task`s are only used internally and you're unlikely to need to deal with them directly. The ones you may want to use in certain cases are [%connect](#connect), [%serve](#serve), [%disconnect](#disconnect), [%approve-origin](#approve-origin) and [%reject-origin](#reject-origin), and they are also demonstrated in the [Examples](@/docs/arvo/eyre/examples.md) document. The rest are just documented for completeness.
26+
27+Many of the types referenced are detailed in the [Data Types](@/docs/arvo/eyre/data-types.md) document. It may also be useful to look at the `+clay` section of `/sys/lull.hoon` in Arvo where these `task`s, `gift`s and data structures are defined.
28+
29+The focus of this document is on interacting with Clay from userspace applications and threads, so it doesn't delve into the internal mechanics of Clay from a kernel development perspective.
30+
31+# `%live`
32+
33+This `task` notifies Eyre of the listening HTTPS and HTTP ports. It is automatically sent to Eyre by Vere and should not be used manually.
34+
35+## Accepts
36+
37+```hoon
38+[insecure=@ud secure=(unit @ud)]
39+```
40+
41+The `insecure` field is the HTTP port and `secure` is the optional HTTPS port.
42+
43+## Returns
44+
45+Eyre returns no `gift` in response to a `%live` `task`.
46+
47+# `%rule`
48+
49+This `task` either configures HTTPS with a certificate and keypair, or configures a DNS binding. You would typically do this via the `%acme` app rather than directly.
50+
51+## Accepts
52+
53+```hoon
54+=http-rule
55+```
56+
57+The [http-rule](@/docs/arvo/eyre/data-types.md#http-rule) is either tagged with `%cert` or `%turf`. A `%cert` `http-rule` sets an HTTPS certificate and keypair or removes it if null. A `%turf` `http-rule` either adds or removes a DNS binding depending on whether the `action` is `%put` or `%del`. Note that using `%turf` will automatically cause the system to try and obtain a certificate and keypair via Letsencrypt.
58+
59+## Returns
60+
61+Eyre returns no `gift` in response to a `%rule` `task`.
62+
63+# `%request`
64+
65+This `task` is how Eyre receives an inbound HTTP request. It will ordinarily be sent to Eyre by Vere so you wouldn't use it except perhaps in tests.
66+
67+## Accepts
68+
69+```hoon
70+[secure=? =address =request:http]
71+```
72+
73+The `secure` field says whether it's over HTTPS. The `address` is the ip address from which the request originated. The [request:http](@/docs/arvo/eyre/data-types.md#request-http) is the HTTP request itself containing the method, url, headers and body.
74+
75+## Returns
76+
77+Eyre may `pass` a `%response` `gift` on the appropriate `duct` depending on the contents of the `%request`, state of the connection and other factors.
78+
79+# `%request-local`
80+
81+This `task` is how Eyre receives an inbound HTTP request over the local loopback port. It behaves the same and takes the same arguments as in the [%request](#request) example except it skips any normally required authentication. Just like for a [%request](#request) `task`, you'd not normally use this manually.
82+
83+# `%cancel-request`
84+
85+This `task` is sent to Eyre by Vere when an HTTP client closes its previously established connection. You would not normally use this manually.
86+
87+## Accepts
88+
89+```hoon
90+~
91+```
92+
93+Takes no arguments.
94+
95+## Returns
96+
97+Eyre may `pass` a `%response` `gift` on the appropriate `duct` depending on the state of the connection and other factors.
98+
99+# `%connect`
100+
101+This `task` binds a Gall agent to a URL path so it can receive HTTP requests and return HTTP responses.
102+
103+If an agent is bound in Eyre using this method, the channel system is bypassed and instead Eyre pokes HTTP requests directly into the agent as a `cage` with a `%handle-http-request` `mark` and a `vase` of `[@ta inbound-request:eyre]` where the `@ta` is a unique `eyre-id` and the [inbound-request](@/docs/arvo/eyre/data-types.md#inbound-request) contains the HTTP request itself.
104+
105+Along with the poke, Eyre will also subscribe to the `/http-response/[eyre-id]` `path` of the agent and await a response, which it will pass on to the HTTP client who made the request. Eyre expects at least two `fact`s and a `kick` to complete the response and close the connection (though it can take more than two `fact`s).
106+
107+The first `fact`'s `cage` must have a `mark` of `%http-response-header` and a `vase` containing a [response-header:http](@/docs/arvo/eyre/data-types.md#response-header-http) with the HTTP status code and headers of the response.
108+
109+The `cage` of the second and subsequent `fact`s must have a `mark` of `%http-response-data` and a `vase` containing a `(unit octs)` with the actual data of the response. An `octs` is just `[p=@ud q=@]` where `p` is the byte-length of `q`, the data. You can send an arbitrary number of these.
110+
111+Finally, once you've sent all the `fact`s you want, you can `give` Eyre a `kick` and it will complete the response and close the connection to the HTTP client.
112+
113+## Accepts
114+
115+```hoon
116+[=binding app=term]
117+```
118+
119+The [binding](@/docs/arvo/eyre/data-types.md#binding) contains a URL path and optional domain through which the agent will be able to take HTTP requests. The `app` is just the name of the Gall agent to bind. Note that if you bind a URL path of `/foo`, Eyre will also match `/foo/bar`, `/foo/bar/baz`, etc.
120+
121+## Returns
122+
123+Eyre will respond with a `%bound` `gift` which says whether the binding was successful and looks like:
124+
125+```hoon
126+[%bound accepted=? =binding]
127+```
128+
129+The `accepted` field says whether the binding succeeded and the `binding` is the requested binding described above.
130+
131+## Example
132+
133+See the [Direct HTTP Handling With Gall Agents](@/docs/arvo/eyre/examples.md#direct-http-handling-with-gall-agents) section of the [Examples](@/docs/arvo/eyre/examples.md) document for an example.
134+
135+# `%serve`
136+
137+This `task` binds a generator to a URL path so it can receive HTTP requests and return HTTP responses.
138+
139+The bound generator must be a gate within a gate and the type returned must be a [simple-payload:http](@/docs/arvo/eyre/data-types.md#simple-payload-http).
140+
141+The sample of the first gate must be:
142+
143+```hoon
144+[[now=@da eny=@uvJ bec=beak] ~ ~]
145+```
146+
147+...and the sample of the second, nested gate must be:
148+
149+```hoon
150+[authenticated=? =request:http]
151+```
152+
153+The `?` says whether the HTTP request contained a valid session cookie and the [request:http](@/docs/arvo/eyre/data-types.md#request-http) contains the request itself.
154+
155+The `simple-payload:http` returned by the generator is similar to the response described in the [%connect](#connect) section except the HTTP headers and body are all contained in the one response rather than staggered across several.
156+
157+## Accepts
158+
159+```hoon
160+[=binding =generator]
161+```
162+
163+The `binding` contains the URL path and optional domain through which the generator will take HTTP requests. The [generator](@/docs/arvo/eyre/data-types.md#generator) specifies the `desk`, the `path` to the generator in Clay, and also has a field for arguments. Note that the passing of specified arguments to the generator by Eyre is not currently implemented, so you can just leave it as `~`.
164+
165+## Returns
166+
167+Eyre will return a `%bound` `gift` as described at the end of the [%connect](#connect) section.
168+
169+## Example
170+
171+See the [Generators](@/docs/arvo/eyre/examples.md#generators) section of the [Examples](@/docs/arvo/eyre/examples.md) document for an example.
172+
173+# `%disconnect`
174+
175+This `task` deletes a URL binding previously set by a `%connect` or `%serve` `task`.
176+
177+## Accepts
178+
179+```hoon
180+=binding
181+```
182+
183+The [binding](@/docs/arvo/eyre/data-types.md#binding) is the URL path and domain of the binding you want to delete.
184+
185+## Returns
186+
187+Eyre returns no `gift` in response to a `%disconnect` `task`.
188+
189+# `%code-changed`
190+
191+This `task` tells Eyre that the web login code has changed, causing Eyre to throw away all sessions and cookies. Typically it's automatically sent to Eyre by `hood` when you run `|code %reset`.
192+
193+## Accepts
194+
195+```hoon
196+~
197+```
198+
199+This `task` takes no arguments.
200+
201+## Returns
202+
203+Eyre returns no `gift` in response to a `%code-changed` `task`.
204+
205+# `%approve-origin`
206+
207+This `task` tells Eyre to start responding positively to CORS requests for the specified `origin`.
208+
209+## Accepts
210+
211+```hoon
212+=origin
213+```
214+
215+The [origin](@/docs/arvo/eyre/data-types.md#origin) is a CORS origin like `http://foo.example` you want to approve.
216+
217+## Returns
218+
219+Eyre returns no `gift` in response to a `%approve-origin` `task`.
220+
221+## Example
222+
223+See the [Managing CORS Origins](@/docs/arvo/eyre/examples.md#managing-cors-origins) section of the [Examples](@/docs/arvo/eyre/examples.md) document for an example.
224+
225+# `%reject-origin`
226+
227+This `task` tells Eyre to start responding negatively to CORS requests for the specified `origin`.
228+
229+## Accepts
230+
231+```hoon
232+=origin
233+```
234+
235+The [origin](@/docs/arvo/eyre/data-types.md#origin) is a CORS origin like `http://foo.example` you want want to reject.
236+
237+## Returns
238+
239+Eyre returns no `gift` in response to a `%reject-origin` `task`.
240+
241+## Example
242+
243+See the [Managing CORS Origins](@/docs/arvo/eyre/examples.md#managing-cors-origins) section of the [Examples](@/docs/arvo/eyre/examples.md) document for an example.
arvo/eyre/using-eyre.mddeleted−230
@@ -1,230 +0,0 @@
1−+++
2−title = "Using Eyre"
3−description = "How to work with eyre from outside Urbit."
4−weight = 20
5−template = "doc.html"
6−+++
7−
8−This guide is aimed at developers who have a working knowledge of HTTP grammar (`PUT`, `GET`), and should not require any special knowledge of Urbit's internals. To learn more about a specific application within Urbit, please search for that with the docs once you have finished this guide.
9−
10−## Prerequisites
11−
12−You'll need a working development ship to follow along with this guide. It's
13−recommended that you set up a new "fakezod" on port 8080: Run this code,
14−substituting the appropriate path to your Urbit binary:
15−
16−```bash
17−/path/to/urbit -p 8080 -F zod
18−```
19−
20−For the unfamiliar, this will create a folder named "zod" in your working directory, from which the ship will run. Use `/path/to/urbit -p 8080 zod` in the future. For more information on this process, see our guide on [Environment Setup](@/docs/development/environment.md).
21−
22−## Authentication
23−
24−We'll authenticate with a code that can be retrieved from the dojo. You can run
25−`+code` in the dojo to obtain it, but a fakezod's code is always
26−`lidlut-tabwed-pillex-ridrup`.
27−
28−Run this code in your bash terminal (requires cURL):
29−
30−```bash
31−curl -i localhost:8080/~/login -X POST -d "password=lidlut-tabwed-pillex-ridrup"
32−```
33−Let's explain what this does:
34−
35− - `-i` displays the headers, so that you can see the cookie that gets sent
36− - `localhost:8080/~/login` is the URL to which you are POSTing. You will note this is also the URL you visit when you log into Landscape.
37− - `-X POST` specifies that you are POSTing data, not GETting.
38− - `-d "password=lidlut-tabwed-pillex-ridrup"` specifies the code for your Urbit that we retrieved above. It is sent as form data, as if it were sent from an HTML form input field (which it is in Landscape)
39−
40−You should see the following:
41−
42−```bash
43−HTTP/1.1 200 ok
44−Date: Sun, 01 Jan 2020 00:00:00 GMT
45−Connection: keep-alive
46−Server: urbit/vere-0.10.8
47−set-cookie: urbauth-~zod=0v3.fvaqc.nnjda.vude1.vb5l6.kmjmg; Path=/; Max-Age=604800
48−transfer-encoding: chunked
49−```
50−
51−The `Date` and `set-cookie` will be slightly different of course.
52−
53−Take a look at the `set-cookie` line. This is now your session authentication, and will need to be sent with any future requests. It consists of three parts:
54−
55− - `urbauth` is a prefix that Eyre uses to check for presence of authentication
56− - `~zod` is the name of the ship you are logging in as
57− - `0v3.fvaqc.nnjda.vude1.vb5l6.kmjmg` is the actual authentication token.
58−
59−At present there is no way to separate these parts — you must pass a cookie *as* a cookie. This string must be in the `Cookie` header. The `set-cookie` header is only used for this request upon response. It is what browsers expect when receiving a cookie.
60−
61−## Interacting with Eyre
62−
63−Once authenticated, you will perform all your operations on a channel. You may open as many channels as needed using the same authentication token, but this will increase complexity and memory usage on your Urbit ship.
64−
65−Interacting with Urbit comprises two parts:
66−
67−1. Sending information via PUT requests, which receive HTTP status code `204` (no content) upon success. We will not receive updated information (as in a POST request).
68−2. Receiving data on channels, which must first be subscribed to via an initial request. These come in the form of SSEs ([Server-Sent Events](https://www.w3.org/TR/eventsource/))
69−
70−These can be used independently, i.e. you may choose to only send information or only receive information from your Urbit, based on your application. Both can take place on the same channel.
71−
72−### Creating a Channel
73−
74−For this example, we will use the following channel:
75−
76−```
77−http://localhost:8080/~/channel/1601844290-ae45b
78−```
79−
80−Let's examine the parts. A channel is simply a URL in this pattern: `{url}/~/channel/{uid}` where `{uid}` is a string of your choosing. Most libraries default to the current unix time plus six hexadecimal characters. Your program should determine a channel for its current session and store that in its state.
81−
82−The channel does not yet exist in Urbit, however. To subscribe to events on this URL, you must first make a request (PUT) to Urbit on this URL. The simplest way to do this is to `hi` ourselves, as if we had entered `|hi our` in the dojo. A `hi` is analogous to a ping, and does not manipulate state. Let's learn how to make requests using this as an example.
83−
84−### Making Requests
85−
86−All requests will take the form of sending a message. Messages can take different forms, such as `subscribe`s, `ack`s, and `poke`s. These are called actions and there are more than these, but these will cover most basic use cases. You can think of them as a somewhat more sophisticated HTTP grammar. A message always requires an `id` and an `action`. Other fields depend on the specific action.
87−
88−Let's look at the structure of a message by examining the most basic `hi` we will send.
89−
90−```js
91−{
92− 'id': 1, // Required. A sequential ID. Keep track of which messages you have sent.
93− 'action': 'poke', // Required. The action to take. poke is the most basic way of sending data, like HTTP POST
94− 'ship': 'zod', // Required by poke. The ship on which to perform the poke. You can only poke foreign ships with JSON, but this is the authenticated ship.
95− 'app': 'hood', // Required by poke. The Urbit app to which to send the data.
96− 'mark': 'helm-hi', // Required by poke. The "mark," or type, of data being sent.
97− 'json': 'Opening airlock' // Required by poke. The actual data being sent.
98−}
99−```
100−
101−Let's open our channel by sending the following request using cURL (**remember to change the cookie**):
102−
103−```bash
104−curl --header "Content-Type: application/json" \
105− --cookie "urbauth-~zod=0v3.fvaqc.nnjda.vude1.vb5l6.kmjmg" \
106− --request PUT \
107− --data '[{"id":1,"action":"poke","ship":"zod","app":"hood","mark":"helm-hi","json":"Opening airlock"}]' \
108− http://localhost:8080/~/channel/1601844290-ae45b
109−```
110−
111−If you switch to your fakezod's dojo, you should see `< ~zod: Opening airlock`.
112−
113−Note that in the JSON that we sent via `--data`, the payload is wrapped in `[]`. This is because we can send multiple messages in a single payload, and Eyre expects a list of items, even if we are only sending one.
114−
115−You will always receive a `204` status code if the `PUT` request successfully reached Urbit, authentication succeeded, and the payload was valid. This is merely an HTTP status code, however. If the request failed within Urbit itself, however, you will receive a "nack" event that you will have to process separately.
116−
117−Let's look at how to receive events from Urbit.
118−
119−### Subscribing to Events
120−
121−Now that Urbit has opened an Eyre channel at our URL, we can watch for events on that URL by sending a `subscribe` message. Let's look at the anatomy of a `susbcribe`:
122−
123−```js
124−{
125− 'id': 2, // Required. This is the next message we are sending, so we give it the next ID.
126− 'action': 'subscribe', // Required.
127− 'ship': 'zod', // Required by subscribe.
128− 'app': 'chat-view', // Required by subscribe. In this case, we want to watch events that occur in the chat-view app, which is responsible for handling incoming chats.
129− 'path': '/primary' // Required by subscribe. All apps have different path structures. In the case of chat-view, this is where we see all incoming chats.
130−}
131−```
132−
133−This is all we need to send Urbit to say "On this URL through which I am sending information, send me SSEs whenever something occurs on this app at this path."
134−
135−You should be able to send this information if you were able to send the above cURL example. However, we now need to be able to listen to the SSEs. The `EventSource` object is available for JavaScript in the browser context, as this is why SSEs were invented, but there should be a library for it in your chosen language. Take a look at a Browser JavaScript example:
136−
137−```js
138−const eventSource = new EventSource('http://localhost:8080/~/channel/1601844290-ae45b', {
139− withCredentials: true // Required, sends your cookie
140−});
141−
142−eventSource.addEventListener('message', function (event) {
143− ack(Number(event.lastEventId)); // See section below
144− const payload = JSON.parse(event.data); // Data is sent in JSON format
145− payload.id === event.lastEventId; // The SSE spec includes event IDs. This information is duplicated in the payload.
146− const data = payload.json; // Beyond this, the actual data will vary between apps
147−});
148−
149−eventSource.addEventListener('error', function (event) {
150− handleError(event);
151−});
152−
153−```
154−
155−### Handling Received Events
156−
157−Once you have received an event, it is expected that you will "ack" or "acknowledge" that you have received them. To do so, simply send a message in the following format:
158−
159−```js
160−{
161− 'id': 3, // Required. Picking up where we left off
162− 'action': 'ack', // Required.
163− 'event-id': 15, // Required by ack. Whichever SSE of which you are acknowledging receipt
164−}
165−```
166−
167−### Unsubscribing from Events
168−
169−You may want to stop receiving events from a particular app path, but you don't want to close the channel altogether yet. Let's look at how to do that. Take a look at the example for subscribing. We sent that message with `id: 2`. We will use that ID to cancel the relevant subscription:
170−
171−```javascript
172−{
173− 'id': 4, // Required. We always increment the ID as we send messages.
174− 'action': 'unsubscribe', // Required.
175− 'subscription': 2 // Required by unsubscribe. This corresponds to the id of a subscribe message sent earlier.
176−}
177−```
178−
179−### Deleting a Channel
180−
181−You should clean up your channel when able. To do so, simply send a `delete` message and Eyre will handle the rest so your program can safely exit.
182−
183−```javascript
184−{
185− 'id': 5, // Required.
186− 'action': 'delete' // Required.
187−}
188−```
189−
190−## Other Operations
191−
192−There are other operations which require authentication but do not require the use of a channel. Some operations are app-specific and will not be enumerated here, but there are two operations that exist across Urbit: `scry` and `spider`.
193−
194−### Scrying
195−
196−Scrying lets you see what an app has exposed at a particular path. It does not manipulate state.
197−
198−It takes the form `{url}/~/scry/{app}{path}.{mark}`
199−
200− Let's get the base hash of our fakezod in the same way that Landscape does it.
201−
202−```bash
203−curl --header "Content-Type: application/json" \
204− --cookie "urbauth-~zod=0v3.fvaqc.nnjda.vude1.vb5l6.kmjmg" \
205− --request GET \
206− http://localhost:8080/~/scry/file-server/clay/base/hash.json
207−```
208−
209−Note the use of a `GET` request.
210−
211−In this example we're scrying the `file-server` app at the path `/clay/base/hash` and using the `json` mark, which is most common. We receive `"0"` which is correct because we are at the top level of the hierarchy using a fake ship.
212−
213−Scry will fail with a 500 or return a 404 if no data is found.
214−
215−### Running Threads with Spider
216−
217−Running threads is an exception to the rule that we outlined in the section on channels. It uses a `POST` request and both manipulates state and receives information back. It also exposes the ability to send a sequence of commands, i.e. a "thread," hence the name.
218−
219−It takes the form `{url}/spider/{inputMark}/{threadname}/{outputmark}.json`
220−
221−This should be considered an advanced technique, but the basic structure of a request can be seen here:
222−
223−```bash
224−curl --header "Content-Type: application/json" \
225− --cookie "urbauth-~zod=0v3.fvaqc.nnjda.vude1.vb5l6.kmjmg" \
226− --request POST \
227− --data '[{"foo": "bar"}]' \
228− http://localhost:8080/spider/graph-view-action/graph-create/json.json
229−
230−```
development/develop.md+1−2
@@ -48,8 +48,7 @@ communicate over HTTP.
4848To get started quickly with the language of your choice, see the list
4949libraries that provide HTTP interfaces to Urbit [here](https://github.com/urbit/awesome-urbit#http-apis-airlock).
5050
51−To learn more about how to work with Urbit's HTTP interface, follow [this
52−guide](@/docs/arvo/eyre/using-eyre.md).
51+To learn more about how to work with Urbit's HTTP interface, have a look at [this document](@/docs/arvo/eyre/external-api-ref.md).
5352
5453Alternatively, command-line interface (CLI) applications can be built using a
5554library called `shoe`, which you can learn more about