tc-server 0.1.0

TinyChain's cluster server logic, including peer discovery and replication
Documentation
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use std::fmt;
use std::sync::Arc;

use futures::future::{Future, TryFutureExt};
use futures::stream::{FuturesUnordered, TryStreamExt};
use log::debug;
use rjwt::VerifyingKey;
use safecast::{TryCastFrom, TryCastInto};

use tc_error::*;
use tc_transact::hash::AsyncHash;
use tc_transact::public::*;
use tc_transact::{Gateway, Transact, Transaction};
use tc_value::{Host, Link, Value};
use tcgeneric::{label, Id, Label, Map, PathSegment, TCPath, Tuple};

use crate::txn::Txn;
use crate::State;

use super::{Cluster, IsDir, REPLICAS};

const ACTION: Label = label("action");
const JOIN: Label = label("join");

mod class;
mod dir;
mod library;
#[cfg(feature = "service")]
mod service;

struct ClusterHandler<T> {
    cluster: Cluster<T>,
}

impl<'a, T> Handler<'a, State> for ClusterHandler<T>
where
    T: AsyncHash + Public<State> + IsDir + Transact + Send + Sync + fmt::Debug + 'a,
{
    fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key: Value| {
            Box::pin(async move {
                if txn.has_claims() {
                    self.cluster.state().get(txn, &[], key).await
                } else {
                    let keyring = self.cluster.keyring(*txn.id()).await?;

                    if key.is_none() {
                        let keyring = keyring
                            .values()
                            .map(|public_key| Value::Bytes((*public_key.as_bytes()).into()))
                            .map(State::from)
                            .collect();

                        Ok(State::Tuple(keyring))
                    } else {
                        let key = Arc::<[u8]>::try_from(key)?;

                        if keyring
                            .values()
                            .any(|public_key| public_key.as_bytes() == &key[..])
                        {
                            Ok(State::from(Value::from(key)))
                        } else {
                            Err(not_found!(
                                "{:?} (of {} keys)",
                                Value::Bytes(key),
                                keyring.len()
                            ))
                        }
                    }
                }
            })
        }))
    }

    fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key, value| {
            Box::pin(async move {
                if txn.locked_by()?.is_some() {
                    debug!("received commit message for {:?}", self.cluster);

                    return if key.is_some() || value.is_some() {
                        Err(TCError::unexpected((key, value), "empty commit message"))
                    } else if txn.leader(self.cluster.path())?.is_none() {
                        let txn = self.cluster.claim(txn.clone())?;
                        self.cluster.replicate_commit(&txn).await
                    } else {
                        self.cluster.replicate_commit(txn).await
                    };
                }

                let should_commit = txn.leader(self.cluster.path())?.is_none();
                let txn = self.cluster.claim(txn.clone())?;

                self.cluster
                    .state
                    .put(&txn, &[], key.clone(), value.clone())
                    .await?;

                debug!("write to {:?} succeeded", self.cluster);

                let (_leader, leader_pk) = txn
                    .leader(self.cluster.path())?
                    .ok_or_else(|| internal!("leaderless transaction"))?;

                if leader_pk == self.cluster.public_key() {
                    self.cluster
                        .replicate_write(&txn, &[], |txn, link| {
                            debug!("replicating write to {:?} to {}...", self.cluster, link);

                            let key = key.clone();
                            let value = value.clone();
                            async move { txn.put(link, key, value).await }
                        })
                        .await?;
                }

                if self.cluster.is_dir() {
                    let this_host = if let Some(host) = self.cluster.link().host() {
                        host
                    } else {
                        return Ok(());
                    };

                    let entry_name: PathSegment =
                        key.try_cast_into(|v| TCError::unexpected(v, "a directory entry name"))?;

                    let (this_replica_hash, this_replica_pk) = self
                        .cluster
                        .get_dir_item_key(*txn.id(), &entry_name)
                        .await?
                        .ok_or_else(|| {
                            internal!("there is no directory entry {entry_name} to replicate")
                        })?;

                    let (leader, leader_pk) = txn.leader(self.cluster.path())?.expect("leader");

                    if leader_pk == self.cluster.public_key() {
                        let replica_set: Vec<Host> = if let Some(keyring) = self
                            .cluster
                            .get_dir_item_keyring(*txn.id(), &entry_name)
                            .await?
                        {
                            keyring.keys().cloned().collect()
                        } else {
                            vec![]
                        };

                        let this_replica_path = self.cluster.path().clone().append(entry_name);

                        replica_set
                            .iter()
                            .map(|host| {
                                let replicas = replica_set
                                    .iter()
                                    .filter(|that_host| host != *that_host)
                                    .cloned()
                                    .map(Value::from)
                                    .collect();

                                let params: Map<State> = [
                                    (Id::from(ACTION), Value::String(JOIN.into())),
                                    (Id::from(REPLICAS), Value::Tuple(replicas)),
                                ]
                                .into_iter()
                                .collect();

                                txn.post(
                                    Link::from((
                                        host.clone(),
                                        this_replica_path.clone().append(REPLICAS),
                                    )),
                                    params,
                                )
                            })
                            .collect::<FuturesUnordered<_>>()
                            .try_fold(State::default(), |_, _| {
                                futures::future::ready(Ok(State::default()))
                            })
                            .await?;
                    } else {
                        let this_replica_hash = Value::Bytes(this_replica_hash.as_slice().into());
                        let this_replica_pk = Value::Bytes(Arc::new(*this_replica_pk.as_bytes()));

                        txn.put(
                            leader.append(entry_name).append(REPLICAS),
                            (this_host.clone(), this_replica_pk),
                            this_replica_hash,
                        )
                        .await?;
                    }
                }

                let owner = txn
                    .owner()?
                    .ok_or_else(|| internal!("ownerless transaction"))?;

                if should_commit {
                    if owner == self.cluster.public_key() {
                        let txn = self.cluster.lock(txn)?;
                        self.cluster.replicate_commit(&txn).await?;
                    }
                }

                Ok(())
            })
        }))
    }

    fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, params| {
            Box::pin(async move {
                // This handler can only execute a hypothetical transaction

                let should_rollback = txn.leader(self.cluster.path())?.is_none();
                let txn = self.cluster.claim(txn.clone())?;
                let response = self.cluster.state.post(&txn, &[], params).await?;

                if should_rollback {
                    if let Some(owner) = txn.owner()? {
                        if owner == self.cluster.public_key() {
                            let txn = self.cluster.lock(txn.clone())?;
                            self.cluster.replicate_rollback(&txn).await?;
                        }
                    }
                }

                Ok(response)
            })
        }))
    }

    fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b, Txn>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key| {
            Box::pin(async move {
                if txn.locked_by()?.is_some() {
                    return if key.is_some() {
                        Err(TCError::unexpected(key, "empty rollback message"))
                    } else {
                        self.cluster.replicate_rollback(txn).await
                    };
                }

                let should_commit = txn.leader(self.cluster.path())?.is_none();
                let txn = self.cluster.claim(txn.clone())?;
                self.cluster.state.delete(&txn, &[], key.clone()).await?;

                maybe_replicate(
                    &self.cluster,
                    &txn,
                    &[],
                    |txn, link| {
                        let key = key.clone();
                        async move { txn.delete(link, key).await }
                    },
                    should_commit,
                )
                .await
            })
        }))
    }
}

impl<T> From<Cluster<T>> for ClusterHandler<T> {
    fn from(cluster: Cluster<T>) -> Self {
        Self { cluster }
    }
}

struct ReplicaSetHandler<T> {
    cluster: Cluster<T>,
}

impl<'a, T> Handler<'a, State> for ReplicaSetHandler<T>
where
    T: AsyncHash + Send + Sync + fmt::Debug + 'a,
{
    fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key| {
            Box::pin(async move {
                debug!("GET {:?} replicas", self.cluster);

                let keyring = self.cluster.keyring(*txn.id()).await?;

                if key.is_some() {
                    let key = Arc::<[u8]>::try_from(key)?;

                    for (host, public_key) in keyring.iter() {
                        if public_key.as_bytes() == &key[..] {
                            return Ok(Value::Link(host.clone().into()).into());
                        }
                    }

                    Ok(Value::None.into())
                } else {
                    let keyring = keyring
                        .iter()
                        .map(|(host, public_key)| {
                            (
                                Value::from(host.clone()),
                                Value::Bytes(Arc::new(*public_key.as_bytes())),
                            )
                        })
                        .map(|(host, public_key)| {
                            State::Tuple(vec![host.into(), public_key.into()].into())
                        })
                        .collect();

                    Ok(State::Tuple(keyring))
                }
            })
        }))
    }

    fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key, value| {
            Box::pin(async move {
                debug!("PUT {:?} replica {key}: {value:?}", self.cluster);

                let new_replica_hash = Value::try_from(value)?;
                let this_replica_hash = AsyncHash::hash(self.cluster.state(), *txn.id())
                    .map_ok(|hash| Arc::<[u8]>::from(hash.as_slice()))
                    .map_ok(Value::Bytes)
                    .await?;

                if new_replica_hash != this_replica_hash {
                    return Err(bad_request!("the provided cluster state hash {new_replica_hash} differs from the hash of this cluster {this_replica_hash}"));
                }

                let mut keyring = self.cluster.keyring_mut(*txn.id()).await?;

                let (host, public_key): (Host, Arc<[u8]>) =
                    key.try_cast_into(|v| TCError::unexpected(v, "a host address and key"))?;

                if self.cluster.link().host() == Some(&host) {
                    return Err(bad_request!(
                        "cannot overwrite the public key of {:?}",
                        self.cluster
                    ));
                }

                let public_key = VerifyingKey::try_from(&*public_key)
                    .map_err(|cause| bad_request!("invalid public key: {cause}"))?;

                keyring.insert(host, public_key);

                Ok(())
            })
        }))
    }

    fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, mut params| {
            Box::pin(async move {
                let action: Id = params.require(&*ACTION)?;
                if action != JOIN {
                    return Err(bad_request!("unrecognized action: {action}"));
                }

                let replicas: Tuple<Link> = params.require(&*REPLICAS)?;

                let this_host = self
                    .cluster
                    .link()
                    .host()
                    .cloned()
                    .ok_or_else(|| bad_request!("{:?} cannot join a cluster", self.cluster))?;

                let this_path = self.cluster.link().path();

                let public_key = Value::Bytes((*self.cluster.public_key().as_bytes()).into());
                let hash = AsyncHash::hash(self.cluster.state(), *txn.id()).await?;

                replicas
                    .into_iter()
                    .map(|mut that_host| {
                        that_host.extend(this_path.iter().cloned());

                        let this_host = this_host.clone();
                        let public_key = public_key.clone();

                        async move {
                            if that_host.host().is_none() {
                                Err(bad_request!(
                                    "{} received a join request with no host",
                                    this_host
                                ))
                            } else if that_host.host() == Some(&this_host) {
                                Err(bad_request!(
                                    "{} received a join request for itself",
                                    this_host
                                ))
                            } else if that_host.path() == this_path {
                                txn.put(
                                    that_host.append(REPLICAS),
                                    (this_host, public_key),
                                    Value::Bytes(hash.as_slice().into()),
                                )
                                .await
                            } else {
                                Err(bad_request!(
                                    "{} received a request to join {}",
                                    this_host,
                                    that_host
                                ))
                            }
                        }
                    })
                    .collect::<FuturesUnordered<_>>()
                    .try_fold(State::default(), |_, _| {
                        futures::future::ready(Ok(State::default()))
                    })
                    .await
            })
        }))
    }

    fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b, Txn>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key| {
            Box::pin(async move {
                debug!("DELETE {:?} replicas {key}", self.cluster);

                let mut keyring = self.cluster.keyring_mut(*txn.id()).await?;

                let hosts = Tuple::<Value>::try_from(key)?;

                for host in hosts {
                    let host =
                        Host::try_cast_from(host, |v| TCError::unexpected(v, "a host address"))?;

                    keyring.remove(&host);
                }

                Ok(())
            })
        }))
    }
}

impl<T> From<Cluster<T>> for ReplicaSetHandler<T> {
    fn from(cluster: Cluster<T>) -> Self {
        Self { cluster }
    }
}

struct ReplicationHandler<'a, T> {
    cluster: Cluster<T>,
    path: &'a [PathSegment],
}

impl<'a, T> ReplicationHandler<'a, T> {
    fn new(cluster: Cluster<T>, path: &'a [PathSegment]) -> Self {
        Self { cluster, path }
    }
}

impl<'a, T> Handler<'a, State> for ReplicationHandler<'a, T>
where
    T: Public<State> + Transact + Send + Sync + fmt::Debug + 'a,
{
    fn get<'b>(self: Box<Self>) -> Option<GetHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, key| {
            Box::pin(async move {
                let txn = self.cluster.claim(txn.clone())?;
                self.cluster.state().get(&txn, self.path, key).await
            })
        }))
    }

    fn put<'b>(self: Box<Self>) -> Option<PutHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        let path = self.path;
        let cluster = self.cluster;

        Some(Box::new(move |txn, key, value| {
            Box::pin(async move {
                let should_commit = txn.leader(cluster.path())?.is_none();
                let txn = cluster.claim(txn.clone())?;

                cluster
                    .state()
                    .put(&txn, path, key.clone(), value.clone())
                    .await?;

                maybe_replicate(
                    &cluster,
                    &txn,
                    path,
                    |txn, link| {
                        let key = key.clone();
                        let value = value.clone();
                        async move { txn.put(link, key, value).await }
                    },
                    should_commit,
                )
                .await
            })
        }))
    }

    fn post<'b>(self: Box<Self>) -> Option<PostHandler<'a, 'b, Txn, State>>
    where
        'b: 'a,
    {
        Some(Box::new(|txn, params| {
            Box::pin(async move {
                let should_commit = txn.leader(self.cluster.path())?.is_none();
                let txn = self.cluster.claim(txn.clone())?;
                let response = self.cluster.state().post(&txn, self.path, params).await?;

                if should_commit {
                    if let Some(owner) = txn.owner()? {
                        if owner == self.cluster.public_key() {
                            let txn = self.cluster.lock(txn)?;
                            self.cluster.replicate_commit(&txn).await?;
                        }
                    }
                }

                Ok(response)
            })
        }))
    }

    fn delete<'b>(self: Box<Self>) -> Option<DeleteHandler<'a, 'b, Txn>>
    where
        'b: 'a,
    {
        let path = self.path;
        let cluster = self.cluster;

        Some(Box::new(move |txn, key| {
            Box::pin(async move {
                let should_commit = txn.leader(cluster.path())?.is_none();
                let txn = cluster.claim(txn.clone())?;

                cluster.state().delete(&txn, path, key.clone()).await?;

                maybe_replicate(
                    &cluster,
                    &txn,
                    path,
                    |txn, link| {
                        let key = key.clone();

                        async move { txn.delete(link, key).await }
                    },
                    should_commit,
                )
                .await
            })
        }))
    }
}

async fn maybe_replicate<T, Op, Fut>(
    cluster: &Cluster<T>,
    txn: &Txn,
    path: &[PathSegment],
    op: Op,
    should_commit: bool,
) -> TCResult<()>
where
    T: Transact + Send + Sync + fmt::Debug,
    Op: Fn(Txn, Link) -> Fut,
    Fut: Future<Output = TCResult<()>>,
{
    let (_leader, leader_pk) = txn
        .leader(cluster.path())?
        .ok_or_else(|| internal!("leaderless transaction"))?;

    if leader_pk == cluster.public_key() {
        cluster.replicate_write(txn, path, op).await?;
    }

    if should_commit {
        if let Some(owner) = txn.owner()? {
            if owner == cluster.public_key() {
                let txn = cluster.lock(txn.clone())?;
                cluster.replicate_commit(&txn).await?;
            }
        }
    }

    Ok(())
}

impl<T> Cluster<T>
where
    T: AsyncHash + Route<State> + IsDir + Transact + Send + Sync + fmt::Debug,
{
    pub fn route_owned<'a>(
        self,
        path: &'a [PathSegment],
    ) -> Option<Box<dyn Handler<'a, State> + 'a>>
    where
        T: 'a,
    {
        debug!("{:?} routing request to {}...", self, TCPath::from(path));

        if path.is_empty() {
            Some(Box::new(ClusterHandler::from(self)))
        } else if path == [REPLICAS] {
            Some(Box::new(ReplicaSetHandler::from(self)))
        } else {
            Some(Box::new(ReplicationHandler::new(self, path)))
        }
    }
}

impl<T> Route<State> for Cluster<T>
where
    T: AsyncHash + Route<State> + IsDir + Transact + Clone + Send + Sync + fmt::Debug,
{
    fn route<'a>(&'a self, path: &'a [PathSegment]) -> Option<Box<dyn Handler<'a, State> + 'a>> {
        self.clone().route_owned(path)
    }
}