1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! The specification's Basic HTTP Event I/O Processor, and the seam a host
//! fills to carry its sends.
//!
//! The processor is host-side code over the driver's ordinary surface, as
//! the reference's `Statifier.Send.BasicHTTP` is (statifier-ex):
//!
//! - [`register`] registers it in a host's [`Options`] under its URI
//! ([`URI`]) and its short form ([`SHORT_FORM`]), with the base address
//! the host's own front answers at. The chart's `_ioprocessors` then
//! carries an entry under each spelling whose `location` is that address,
//! `/` and the session's id.
//! - [`deliver`] takes one send of either spelling the driver handed the
//! host, encodes it as the reference encodes it and hands the request to
//! the host's [`Transport`], passed per call and never kept. A transport
//! error or a status outside 2xx is reported to the chart as
//! [`State::report_send_failed`] reports it; a send with no target the
//! driver has already answered with `error.communication` in the sending
//! session, as the reference does.
//! - [`decode`] reads a request the host's front received into the name and
//! data of an external event, which the host passes to [`State::step`].
//!
//! The crate opens no socket and ships no transport, the standard library
//! having no HTTP client: a host implements [`Transport`] over a client it
//! already has. The module exists only behind the `basichttp` feature, off
//! by default, and the feature adds no dependency.
//!
//! ```
//! use statifier::basichttp::{self, Delivery, Request, Response, Transport, TransportError};
//! use statifier::{Effect, Options};
//! use std::cell::RefCell;
//!
//! // A transport that keeps each request in memory and answers 204.
//! struct Kept(RefCell<Vec<Request>>);
//!
//! impl Transport for Kept {
//! fn send(&self, request: Request) -> Result<Response, TransportError> {
//! self.0.borrow_mut().push(request);
//! Ok(Response::new(204, Vec::new(), Vec::new()))
//! }
//! }
//!
//! let machine = statifier::compile(
//! r#"<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
//! <state id="a">
//! <onentry>
//! <send event="e.go" type="basichttp"
//! targetexpr="_ioprocessors['basichttp']['location']"/>
//! </onentry>
//! <transition event="e.go" target="b"/>
//! </state>
//! <final id="b"/>
//! </scxml>"#,
//! )
//! .map_err(|refusals| format!("{refusals:?}"))?;
//! let options = basichttp::register(Options::new("s-1"), "http://localhost:8080/scxml");
//! let started = machine.start(options)?;
//! let send = started
//! .effects
//! .iter()
//! .find(|effect| matches!(effect, Effect::Send { .. }))
//! .ok_or("the send is handed to the host")?;
//!
//! let transport = Kept(RefCell::new(Vec::new()));
//! let delivery = basichttp::deliver(&started.state, send, &transport)?;
//! assert!(matches!(delivery, Delivery::Delivered { .. }));
//!
//! // The host's front receives the request and steps the chart with it.
//! let request = transport.0.borrow()[0].clone();
//! assert_eq!(request.address, "http://localhost:8080/scxml/s-1");
//! assert_eq!(request.body, b"_scxmleventname=e.go".to_vec());
//! let received = basichttp::decode(&request)?;
//! let moved = started.state.step(&received.name, received.data)?;
//! assert!(moved.state.done().is_some());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
use crate::;
use Error;
use fmt;
use Arc;
/// The processor's URI, the send type the specification names it by.
pub const URI: &str = "http://www.w3.org/TR/scxml/#BasicHTTPEventProcessor";
/// The processor's short form, the send type and `_ioprocessors` key a
/// chart may name it by.
pub const SHORT_FORM: &str = "basichttp";
/// `options` with the processor registered under [`URI`] and
/// [`SHORT_FORM`], each with the `_ioprocessors` entry
/// [`IoProcessorEntry::SessionLocation`] writes from `base_address`: a
/// `location` that is the address, `/` and the session's id. Both
/// spellings are listed in [`Options::target_required`], so a send of
/// either with no target raises `error.communication` in the sending
/// session as the reference's processor raises it. Any entry `options`
/// already gives either spelling is replaced; nothing else changes.
///
/// ```
/// use statifier::basichttp;
/// use statifier::{IoProcessorEntry, Options};
///
/// let options = basichttp::register(Options::new("s-1"), "http://localhost:8080/scxml");
/// assert!(options.send_types.contains(basichttp::URI));
/// assert_eq!(
/// options.ioprocessors.get(basichttp::SHORT_FORM),
/// Some(&IoProcessorEntry::SessionLocation("http://localhost:8080/scxml".to_owned()))
/// );
/// ```
/// What [`deliver`] answers for a send it took.
/// Why a send missed.
/// Delivers `send`, a send of [`URI`] or [`SHORT_FORM`] the driver handed
/// the host from `state`: encodes it as the reference encodes it, hands the
/// request to `transport` once, and reports a miss to the chart.
///
/// `send` is the [`Effect::Send`] or [`Effect::SendDelayed`] as the host
/// was handed it, or, for an invoked child's send, the [`Effect::Child`]
/// carrying it. A delayed send is delivered at once: the host calls this
/// when its delay has passed, unless a `<cancel>` named it first.
///
/// The request is a `POST` to the send's target. A `data` that is a map,
/// the `namelist` and `<param>` values or a `<content>` whose value is a
/// map, is a form body (`application/x-www-form-urlencoded`): the event's
/// name as `_scxmleventname` first, then each member in the order the
/// reference walks a map of up to 32 members (integer keys, then `false`,
/// `true` and undefined, then string keys, each in its own order). No data
/// sends `_scxmleventname` alone as a form body. Any other `<content>` is a
/// `text/plain` body, and the event's name travels as a `_scxmleventname`
/// query parameter of the target. Names and values are percent-encoded,
/// every byte outside letters, digits, `-`, `.`, `_` and `~`, a space as
/// `+`. A value is written as text: a string as it is, a number or a
/// boolean as its literal, null as `null`, undefined as the empty string,
/// a list or a map as JSON text. The request carries the `content-type`
/// header and the `scxml-send-key` header, the reference's dedup key: the
/// session's id, the send id, the macrostep, microstep and round, the
/// content index, the owner and the ordinal, joined by `/`.
///
/// A 2xx response answers [`Delivery::Delivered`]. A send with no target,
/// a transport error, and a response whose status is outside 2xx answer
/// [`Delivery::Missed`]: the miss is reported with
/// [`State::report_send_failed`], whose new state the delivery carries.
/// A send with no target whose type the sending session lists in
/// [`Options::target_required`], as [`register`] lists both spellings, is
/// the exception: the driver raised its `error.communication` itself, when
/// the send was made, so it is answered missed with no report and nothing
/// moved.
///
/// Refused, with nothing requested, as [`State::report_send_failed`]
/// refuses an effect that is not a send handed to the host, and with
/// [`crate::Error::NotAHandedSend`] for a send of another type.
/// An external event read from a request: the host passes its name and
/// data to [`State::step`].
/// Which part of a request [`DecodeError::NotUtf8`] names.
/// Why [`decode`] read no event from a request.
/// Reads a request a host's front received into an external event, as the
/// reference reads one. Pure: it knows no session, so the front resolves
/// the address to the session and steps it.
///
/// - The method must be `POST` in any case.
/// - The event's name is the first `_scxmleventname`, the query's before
/// the body's, else `HTTP.` and the method in upper case (`HTTP.POST`).
/// - A form body (a `content-type` header starting
/// `application/x-www-form-urlencoded`, in any case) and the query give
/// their other parameters as the data, a map, the last of a repeated name
/// kept, each value read as a `<content>` text is (a predicator literal,
/// else the text with its whitespace runs one space), a parameter with
/// no `=` undefined; with none the data is undefined.
/// - Any other body is the data, read the same way, and the query then
/// gives the name alone.
/// - An `scxml-send-key` header, the dedup key, sets nothing: a front
/// deduplicates on it itself. Only its shape is checked.
///
/// The query is what follows the address's first `?`, up to a `#`. The
/// first header of a name counts, the name read in any case.
///
/// ```
/// use statifier::basichttp::{self, Request};
/// use statifier::Value;
///
/// let request = Request::new(
/// "POST",
/// "http://localhost:8080/scxml/s-1",
/// vec![("content-type".to_owned(), "application/x-www-form-urlencoded".to_owned())],
/// "_scxmleventname=e.go&n=2",
/// );
/// let received = basichttp::decode(&request)?;
/// assert_eq!(received.name, "e.go");
/// let Value::Map(data) = &received.data else { panic!("a map") };
/// assert_eq!(data.get(&"n".into()), Some(&Value::from(2)));
/// # Ok::<(), basichttp::DecodeError>(())
/// ```
/// One HTTP request: one a transport sends, or one a front received.
/// The response a server answered.
///
/// Every status the server answered is a response, 2xx or not (100 to 599
/// are HTTP's). A status outside 2xx is answered as a `Response`, never as a
/// [`TransportError`].
/// The one error a transport answers when no response came back: an address
/// it cannot request, a connection refused or failed, a time bound passed,
/// or an exchange broken off.
///
/// The cause, when there was one, is its [`source`](Error::source). It
/// implements no `PartialEq`, because a cause is not comparable.
/// What a host implements to carry a request to a server.
///
/// `send` is synchronous. It makes one attempt and does not retry. It
/// answers the response that came back, whatever its status, or a
/// [`TransportError`] when none came back.
///
/// The trait is object safe and used as `&dyn Transport`. It takes `&self`
/// so one transport serves many sends; a host whose client needs mutation
/// uses interior mutability. It has no `Send` or `Sync` supertrait: a host
/// that shares one transport across threads names the bound where it holds
/// it, as `&(dyn Transport + Sync)`, and a single-threaded host's transport
/// needs neither.
///
/// ```
/// use statifier::basichttp::{Request, Response, Transport, TransportError};
///
/// struct InMemory;
///
/// impl Transport for InMemory {
/// fn send(&self, request: Request) -> Result<Response, TransportError> {
/// if request.address.starts_with("http://") {
/// Ok(Response::new(200, Vec::new(), request.body))
/// } else {
/// Err(TransportError::new("not an http address"))
/// }
/// }
/// }
///
/// let transport: &dyn Transport = &InMemory;
/// let request = Request::new("POST", "http://localhost:8080/s1", Vec::new(), "e.go");
/// assert_eq!(transport.send(request).unwrap().status, 200);
/// ```