graphshell 0.0.2

Graphshell presentation host and loopback acceptance view.
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
//! Deterministic disconnect and resume acceptance fixture for G2.

use chirograph::{
    BoundsRelationship, CachePolicy, EndpointDescriptor, IntentInvocation, IntentResult,
    PresentationBinding, PresentationCapability, PresentationChange, PresentationCodec,
    PresentationKey, PresentationManifest, PresentationOffer, PresentationSemantics, ProjectionAck,
    ProjectionDiff, ProjectionOffer, ProjectionRequest, ProjectionSession, ProjectionSnapshot,
    ProtocolVersion, ResourceRequest, ResourceResponse, ResumeReply, ResumeRequest, SemanticRole,
    SessionStatus,
};
use graphshell_client::{ClientState, DiffApplication, ResumeApplication, ResumeApplyError};
use graphshell_endpoint::{
    IntentSink, PresentationSource, ProjectionCatalog, ProjectionSource, ResumableProjectionSource,
};
use sceno::{
    Arrangement, Footprint, InstanceId, ProjectedItem, Representation, Scene, Score, Size2,
    SourceIx, SourceRef, Transform2,
};
use scenotime::{Revision, SceneDiff, SceneEpoch, SceneOp, SceneSnapshot};

const SESSION: &str = "loopback:g2-resume";

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResumeFixtureError {
    WrongSession,
    NoSuchResource,
}

/// A source with a two-diff history and an epoch-preserving current snapshot.
pub struct ResumeFixtureEndpoint {
    session: ProjectionSession,
    initial: ProjectionSnapshot,
    current: ProjectionSnapshot,
    history: Vec<ProjectionDiff>,
}

impl ResumeFixtureEndpoint {
    pub fn new() -> Self {
        let session = ProjectionSession(SESSION.into());
        let mut scene = Scene::new();
        let source = scene.intern_source(SourceRef::new("fixture.graphshell", "card:0"));
        scene.items.push(item(source, 0.0));
        let scene = SceneSnapshot::from_dense(SceneEpoch(3), Revision(1), scene)
            .expect("initial fixture scene is valid");
        let key_0 = PresentationKey("fixture:0".into());
        let key_1 = PresentationKey("fixture:1".into());
        let key_2 = PresentationKey("fixture:2".into());
        let mut initial_presentation = PresentationManifest {
            bindings: vec![PresentationBinding {
                instance: InstanceId(0),
                key: key_0.clone(),
            }],
            ..PresentationManifest::default()
        };
        initial_presentation
            .offers
            .insert(key_0.clone(), vec![offer("First", b"first")]);
        let initial = ProjectionSnapshot {
            version: ProtocolVersion::V1,
            session: session.clone(),
            scene,
            presentation: initial_presentation,
            cache_policy: CachePolicy::default(),
        };

        let diff_2 = ProjectionDiff {
            version: ProtocolVersion::V1,
            session: session.clone(),
            scene: SceneDiff {
                epoch: SceneEpoch(3),
                base: Revision(1),
                revision: Revision(2),
                operations: vec![SceneOp::AddItem {
                    index: InstanceId(1),
                    value: item(source, 80.0),
                    order: -1,
                }],
            },
            presentation: vec![
                PresentationChange::Bind(PresentationBinding {
                    instance: InstanceId(1),
                    key: key_1.clone(),
                }),
                PresentationChange::ReplaceOffers {
                    key: key_1.clone(),
                    offers: vec![offer("Second", b"second")],
                },
            ],
            status: Some(SessionStatus::Live),
        };
        let diff_3 = ProjectionDiff {
            version: ProtocolVersion::V1,
            session: session.clone(),
            scene: SceneDiff {
                epoch: SceneEpoch(3),
                base: Revision(2),
                revision: Revision(3),
                operations: vec![
                    SceneOp::TombstoneItem {
                        index: InstanceId(0),
                    },
                    SceneOp::AddItem {
                        index: InstanceId(2),
                        value: item(source, 160.0),
                        order: 0,
                    },
                    SceneOp::SetItemLayer {
                        index: InstanceId(1),
                        layer: 4,
                    },
                ],
            },
            presentation: vec![
                PresentationChange::Unbind {
                    instance: InstanceId(0),
                },
                PresentationChange::RemoveOffers { key: key_0 },
                PresentationChange::Bind(PresentationBinding {
                    instance: InstanceId(2),
                    key: key_2.clone(),
                }),
                PresentationChange::ReplaceOffers {
                    key: key_2.clone(),
                    offers: vec![offer("Third", b"third")],
                },
            ],
            status: Some(SessionStatus::Live),
        };

        let mut current_scene = initial.scene.clone();
        current_scene
            .apply_diff(&diff_2.scene)
            .expect("revision 2 is valid");
        current_scene
            .apply_diff(&diff_3.scene)
            .expect("revision 3 is valid");
        let mut current_presentation = PresentationManifest {
            bindings: vec![
                PresentationBinding {
                    instance: InstanceId(1),
                    key: key_1.clone(),
                },
                PresentationBinding {
                    instance: InstanceId(2),
                    key: key_2.clone(),
                },
            ],
            ..PresentationManifest::default()
        };
        current_presentation
            .offers
            .insert(key_1, vec![offer("Second", b"second")]);
        current_presentation
            .offers
            .insert(key_2, vec![offer("Third", b"third")]);
        let current = ProjectionSnapshot {
            version: ProtocolVersion::V1,
            session: session.clone(),
            scene: current_scene,
            presentation: current_presentation,
            cache_policy: CachePolicy::default(),
        };
        Self {
            session,
            initial,
            current,
            history: vec![diff_2, diff_3],
        }
    }

    pub fn initial_snapshot(&self) -> ProjectionSnapshot {
        self.initial.clone()
    }

    pub fn diff(&self, revision: Revision) -> ProjectionDiff {
        self.history
            .iter()
            .find(|diff| diff.scene.revision == revision)
            .expect("fixture revision exists")
            .clone()
    }
}

impl Default for ResumeFixtureEndpoint {
    fn default() -> Self {
        Self::new()
    }
}

/// Required by `graphshell_endpoint::dispatch_common`: a carrier reports an
/// endpoint's failure to a peer as text and never leaks the endpoint's own
/// error type onto the wire.
impl std::fmt::Display for ResumeFixtureError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResumeFixtureError::WrongSession => write!(f, "request names another session"),
            ResumeFixtureError::NoSuchResource => write!(f, "no such resource"),
        }
    }
}

impl ResumeFixtureEndpoint {
    /// The request that selects this fixture's projection.
    pub fn request(&self) -> ProjectionRequest {
        ProjectionRequest {
            version: ProtocolVersion::V1,
            session: self.session.clone(),
            score: Score::new(Arrangement::Spiral(Default::default())),
        }
    }

    /// The revision a resuming client should currently be able to reach.
    pub fn current_revision(&self) -> Revision {
        self.current.scene.revision
    }
}

impl ProjectionCatalog for ResumeFixtureEndpoint {
    fn describe(&self) -> EndpointDescriptor {
        EndpointDescriptor {
            label: "graphshell resume fixture".to_string(),
            projections: vec![ProjectionOffer {
                label: "G2 resume".to_string(),
                request: self.request(),
            }],
        }
    }
}

impl PresentationSource for ResumeFixtureEndpoint {
    type Error = ResumeFixtureError;

    /// This fixture's scenes carry presentation *bindings* but no resource
    /// bytes; its point is scene diff and resume, not disclosure. Saying so is
    /// better than returning empty bytes that would read as a real resource.
    fn resource(&mut self, _request: ResourceRequest) -> Result<ResourceResponse, Self::Error> {
        Err(ResumeFixtureError::NoSuchResource)
    }
}

impl IntentSink for ResumeFixtureEndpoint {
    type Error = ResumeFixtureError;

    /// Real adjudication against the scene, not a stub.
    ///
    /// An intent naming another session is refused; one raised against a
    /// revision the endpoint has moved past is `Stale` with the current
    /// position, which is what lets a client resynchronize rather than guess.
    /// Only an intent on the current revision is accepted.
    fn invoke(&mut self, intent: IntentInvocation) -> Result<IntentResult, Self::Error> {
        if intent.session != self.session {
            return Err(ResumeFixtureError::WrongSession);
        }
        if intent.observed_epoch != self.current.scene.epoch
            || intent.observed_revision != self.current.scene.revision
        {
            return Ok(IntentResult::Stale {
                current_epoch: self.current.scene.epoch,
                current_revision: self.current.scene.revision,
            });
        }
        Ok(IntentResult::Accepted)
    }
}

impl ProjectionSource for ResumeFixtureEndpoint {
    type Error = ResumeFixtureError;

    fn snapshot(&mut self, request: ProjectionRequest) -> Result<ProjectionSnapshot, Self::Error> {
        if request.session != self.session {
            return Err(ResumeFixtureError::WrongSession);
        }
        Ok(self.current.clone())
    }
}

impl ResumableProjectionSource for ResumeFixtureEndpoint {
    type Error = ResumeFixtureError;

    fn resume(&mut self, request: ResumeRequest) -> Result<ResumeReply, Self::Error> {
        if request.session != self.session {
            return Err(ResumeFixtureError::WrongSession);
        }
        if request.epoch != self.current.scene.epoch {
            return Ok(ResumeReply::Snapshot(Box::new(self.current.clone())));
        }
        if request.revision == self.current.scene.revision {
            return Ok(ResumeReply::Current(ProjectionAck {
                session: self.session.clone(),
                epoch: self.current.scene.epoch,
                revision: self.current.scene.revision,
            }));
        }
        if let Some(start) = self
            .history
            .iter()
            .position(|diff| diff.scene.base == request.revision)
        {
            return Ok(ResumeReply::Diffs(self.history[start..].to_vec()));
        }
        Ok(ResumeReply::Snapshot(Box::new(self.current.clone())))
    }
}

fn item(source: SourceIx, x: f32) -> ProjectedItem {
    ProjectedItem {
        source,
        space: Scene::WORLD,
        transform: Transform2::translation(x, 0.0),
        footprint: Footprint::Rect {
            size: Size2::new(64.0, 40.0),
        },
        representation: Representation::Card,
        layer: 0,
        visible: true,
        hit: None,
        channels: Vec::new(),
    }
}

fn offer(label: &str, bytes: &[u8]) -> PresentationOffer {
    PresentationOffer {
        codec: PresentationCodec::NativeGlyphV1,
        resource: chirograph::ContentHash::of(bytes),
        byte_size: bytes.len() as u64,
        requires: PresentationCapability::NativeGlyph,
        semantics: PresentationSemantics {
            label: label.into(),
            role: SemanticRole::Graphic,
            bounds: BoundsRelationship::FitWithinFootprint,
            actions: Vec::new(),
        },
    }
}

/// Disconnect after revision 2, replay revision 3, then compare against the
/// endpoint's complete current snapshot.
pub fn run_resume_canary() -> Result<ClientState, ResumeApplyError> {
    let mut endpoint = ResumeFixtureEndpoint::new();
    let session = ProjectionSession(SESSION.into());
    let mut client = ClientState::default();
    client
        .apply_snapshot(endpoint.initial_snapshot())
        .map_err(ResumeApplyError::InvalidSnapshot)?;
    let diff_2 = endpoint.diff(Revision(2));
    assert!(matches!(
        client.apply_diff(&diff_2),
        Ok(DiffApplication::Applied(_))
    ));
    assert!(matches!(
        client.apply_diff(&diff_2),
        Ok(DiffApplication::AlreadyApplied(_))
    ));
    client.mark_disconnected(&session);
    let request = client
        .resume_request(&session)
        .expect("mounted fixture has an acknowledgement");
    let reply = endpoint
        .resume(request)
        .expect("fixture session is correct");
    assert!(matches!(
        client.apply_resume(&session, reply)?,
        ResumeApplication::Applied(ProjectionAck {
            revision: Revision(3),
            ..
        })
    ));
    Ok(client)
}

#[cfg(test)]
mod tests {
    use super::*;
    use sceno::Arrangement;

    #[test]
    fn disconnected_client_resumes_to_the_full_snapshot_without_slot_reuse() {
        let client = run_resume_canary().unwrap();
        let session = ProjectionSession(SESSION.into());
        let mounted = client.mounted(&session).unwrap();
        let endpoint = ResumeFixtureEndpoint::new();
        assert_eq!(mounted.scene, endpoint.current.scene);
        assert_eq!(mounted.presentation, endpoint.current.presentation);
        assert_eq!(mounted.status, SessionStatus::Live);
        assert_eq!(mounted.scene.tables.items.len(), 3);
        assert!(mounted.scene.tables.items[0].is_none());
        assert!(mounted.scene.tables.items[1].is_some());
        assert!(mounted.scene.tables.items[2].is_some());
        assert_eq!(mounted.scene.active_item_count(), 2);
    }

    #[test]
    fn resumed_diff_and_current_ack_are_idempotent() {
        let mut endpoint = ResumeFixtureEndpoint::new();
        let session = ProjectionSession(SESSION.into());
        let mut client = run_resume_canary().unwrap();
        let once = client.clone();
        let duplicate = ResumeReply::Diffs(vec![endpoint.diff(Revision(3))]);
        client.apply_resume(&session, duplicate).unwrap();
        assert_eq!(client, once);

        client.mark_disconnected(&session);
        let reply = endpoint
            .resume(client.resume_request(&session).unwrap())
            .unwrap();
        assert!(matches!(
            client.apply_resume(&session, reply).unwrap(),
            ResumeApplication::Current(_)
        ));
        assert_eq!(
            client.mounted(&session).unwrap().status,
            SessionStatus::Live
        );
    }

    #[test]
    fn unavailable_base_falls_back_to_an_epoch_preserving_snapshot() {
        let mut endpoint = ResumeFixtureEndpoint::new();
        let session = ProjectionSession(SESSION.into());
        let reply = endpoint
            .resume(ResumeRequest {
                session: session.clone(),
                epoch: SceneEpoch(3),
                revision: Revision(99),
            })
            .unwrap();
        assert!(
            matches!(reply, ResumeReply::Snapshot(snapshot) if snapshot.scene.tables.items[0].is_none())
        );

        let full = endpoint
            .snapshot(ProjectionRequest {
                version: ProtocolVersion::V1,
                session,
                score: sceno::Score::new(Arrangement::Spiral(Default::default())),
            })
            .unwrap();
        assert_eq!(full.scene.revision, Revision(3));
        assert!(full.scene.tables.items[0].is_none());
    }
}