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
#![feature(core_intrinsics)]
#![feature(never_type)]
use std::{env, process};
use std::net::SocketAddr;
use serde::{Deserialize, Serialize};
use spinach::tokio;
use spinach::tokio::net::TcpStream;
use spinach::collections::Single;
use spinach::comp::{CompExt};
use spinach::func::binary::{HashPartitioned, TableProduct};
use spinach::func::unary::{Morphism};
use spinach::hide::{Hide, Qualifier};
use spinach::lattice::LatticeRepr;
use spinach::lattice::map_union::MapUnionRepr;
use spinach::lattice::set_union::SetUnionRepr;
use spinach::lattice::dom_pair::DomPairRepr;
use spinach::lattice::ord::MaxRepr;
use spinach::lattice::pair::PairRepr;
use spinach::op::{BinaryOp, OpExt, ReadOp, TcpOp, TcpServerOp};
use spinach::tag;
use spinach::tcp_server::TcpServer;
type ValueLatRepr = DomPairRepr<MaxRepr<usize>, MaxRepr<String>>;
#[derive(Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum KvsOperation {
Read(String),
Write(String, <ValueLatRepr as LatticeRepr>::Repr),
}
type RequestLatRepr = SetUnionRepr<tag::SINGLE, KvsOperation>;
type ResponseLatRepr = MapUnionRepr<tag::VEC, String, ValueLatRepr>;
pub struct Switch;
impl Morphism for Switch {
type InLatRepr = SetUnionRepr<tag::VEC, (SocketAddr, KvsOperation)>;
type OutLatRepr = PairRepr<
MapUnionRepr<tag::VEC, String, SetUnionRepr<tag::VEC, SocketAddr>>,
MapUnionRepr<tag::VEC, String, ValueLatRepr>,
>;
fn call<Y: Qualifier>(&self, item: Hide<Y, Self::InLatRepr>) -> Hide<Y, Self::OutLatRepr> {
let (reads, writes) = item.switch::<tag::VEC, _>(|(_addr, operation)| {
match operation {
KvsOperation::Read(_) => true,
KvsOperation::Write(_, _) => false,
}
});
let reads = reads
.map::<_, tag::VEC, _>(|(addr, operation)| {
match operation {
KvsOperation::Read(key) => Single((key, Single(addr))),
KvsOperation::Write(_, _) => panic!(),
}
})
.fold::<MapUnionRepr<tag::VEC, String, SetUnionRepr<tag::VEC, SocketAddr>>, MapUnionRepr<tag::SINGLE, String, SetUnionRepr<tag::SINGLE, SocketAddr>>>();
let writes = writes
.map::<_, tag::VEC, _>(|(_addr, operation)| {
match operation {
KvsOperation::Read(_) => panic!(),
KvsOperation::Write(key, val) => Single((key, val)),
}
})
.fold::<MapUnionRepr<tag::VEC, String, ValueLatRepr>, MapUnionRepr<tag::SINGLE, String, ValueLatRepr>>();
Hide::zip(reads, writes)
}
}
async fn server(url: &str) -> Result<!, String> {
let server = TcpServer::bind(url).await.map_err(|e| e.to_string())?;
let (op_reads, op_writes) = TcpServerOp::<RequestLatRepr>::new(server.clone())
.morphism_closure(|item| item.flatten_keyed::<tag::VEC>())
.morphism(Switch)
.switch();
type ReadsLatRepr = MapUnionRepr<tag::HASH_MAP, String, SetUnionRepr<tag::HASH_SET, SocketAddr>>;
let op_reads = op_reads
.lattice_default::<ReadsLatRepr>();
type WritesLatRepr = MapUnionRepr<tag::HASH_MAP, String, ValueLatRepr>;
let op_writes = op_writes
.lattice_default::<WritesLatRepr>();
let binary_func = HashPartitioned::<String, _>::new(
TableProduct::<_, _, _, MapUnionRepr<tag::VEC, _, _>>::new());
let comp = BinaryOp::new(op_reads, op_writes, binary_func)
.morphism_closure(|item| item.transpose::<tag::VEC, tag::VEC>())
.comp_tcp_server::<ResponseLatRepr, _>(server);
comp
.run()
.await
.map_err(|e| format!("TcpComp error: {:?}", e))?;
}
pub struct ParseKvsOperation;
impl Morphism for ParseKvsOperation {
type InLatRepr = SetUnionRepr<tag::SINGLE, String>;
type OutLatRepr = SetUnionRepr<tag::OPTION, KvsOperation>;
fn call<Y: Qualifier>(&self, item: Hide<Y, Self::InLatRepr>) -> Hide<Y, Self::OutLatRepr> {
item.filter_map_one(|input| {
match ron::de::from_str::<KvsOperation>(&*input) {
Ok(operation) => {
Some(operation)
},
Err(err) => {
eprintln!("Failed to parse operation, error: {}", err);
None
}
}
})
}
}
async fn client<R: tokio::io::AsyncRead + std::marker::Unpin>(url: &str, input_read: R) -> Result<!, String> {
let (read, write) = TcpStream::connect(url).await.map_err(|e| e.to_string())?
.into_split();
let read_comp = TcpOp::<ResponseLatRepr>::new(read)
.comp_null();
let write_comp = ReadOp::new(input_read)
.morphism(ParseKvsOperation)
.debottom()
.comp_tcp::<RequestLatRepr>(write);
#[allow(unreachable_code)]
let result = tokio::try_join!(
async {
read_comp.run().await.map_err(|_| format!("Read failed."))
},
async {
let err = write_comp.run().await.map_err(|e| e.to_string());
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
err
},
);
result?;
unreachable!();
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<!, String> {
let args: Vec<_> = env::args().collect();
match &*args {
[_, mode, url] if mode == "server" => server(url).await?,
[_, mode, url] if mode == "client" => client(url, tokio::io::stdin()).await?,
[_, mode, url, input_file] if mode == "client" => {
match tokio::fs::File::open(input_file).await {
Ok(file) => client(url, file).await?,
Err(err) => {
eprintln!("Failed to open input_file: \"{}\", error: {}", input_file, err);
process::exit(2);
}
}
}
_ => {
eprintln!("Usage:\n{0} server <url>\n or\n{0} client <url> [input_file]", args[0]);
process::exit(1);
}
}
}