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
use juniper::{Context as JuniperContext, GraphQLType, RootNode};
use kubos_system::Config;
use log::info;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use warp::{filters::BoxedFilter, Filter};
#[derive(Clone)]
pub struct Context<T> {
pub subsystem: T,
pub storage: Arc<RwLock<HashMap<String, String>>>,
}
impl<T> JuniperContext for Context<T> {}
impl<T> Context<T> {
pub fn subsystem(&self) -> &T {
&self.subsystem
}
pub fn get(&self, name: &str) -> String {
let stor = self.storage.read().unwrap();
match stor.get(&name.to_string()) {
Some(s) => s.clone(),
None => "".to_string(),
}
}
pub fn set(&self, key: &str, value: &str) {
let mut stor = self.storage.write().unwrap();
stor.insert(key.to_string(), value.to_string());
}
pub fn clear(&self, name: &str) {
let mut storage = self.storage.write().unwrap();
storage.remove(name);
}
pub fn clear_all(&self) {
self.storage.write().unwrap().clear();
}
}
pub struct Service {
config: Config,
pub filter: BoxedFilter<(warp::http::response::Response<std::vec::Vec<u8>>,)>,
}
impl Service {
pub fn new<Query, Mutation, S>(
config: Config,
subsystem: S,
query: Query,
mutation: Mutation,
) -> Self
where
Query: GraphQLType<Context = Context<S>, TypeInfo = ()> + Send + Sync + 'static,
Mutation: GraphQLType<Context = Context<S>, TypeInfo = ()> + Send + Sync + 'static,
S: Send + Sync + Clone + 'static,
{
let root_node = RootNode::new(query, mutation);
let context = Context {
subsystem,
storage: Arc::new(RwLock::new(HashMap::new())),
};
let context = warp::any().map(move || context.clone()).boxed();
let graphql_filter = juniper_warp::make_graphql_filter(root_node, context);
let filter = warp::path("graphiql")
.and(juniper_warp::graphiql_filter("/graphql"))
.or(graphql_filter)
.unify()
.boxed();
Service { config, filter }
}
pub fn start(self) {
let hosturl = self
.config
.hosturl()
.ok_or_else(|| {
log::error!("Failed to load service URL");
"Failed to load service URL"
})
.unwrap();
let addr = hosturl
.parse::<SocketAddr>()
.map_err(|err| {
log::error!("Failed to parse SocketAddr: {:?}", err);
err
})
.unwrap();
info!("Listening on: {}", addr);
warp::serve(self.filter).run(addr);
}
}