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
#![forbid(unsafe_code)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, future_incompatible, unreachable_pub, rust_2018_idioms)]
use deno_core::Op;
use deno_core::{json_op_sync, JsRuntime};
use serde::{Deserialize, Serialize};
use std::sync::mpsc::channel;
use std::{fmt::Display, io::Write};
use thiserror::Error;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServiceDefinition {
pub name: String,
pub url: String,
pub type_defs: String,
}
impl ServiceDefinition {
pub fn new<N: Into<String>, U: Into<String>, D: Into<String>>(
name: N,
url: U,
type_defs: D,
) -> ServiceDefinition {
ServiceDefinition {
name: name.into(),
url: url.into(),
type_defs: type_defs.into(),
}
}
}
pub type ServiceList = Vec<ServiceDefinition>;
#[derive(Debug, Error, Serialize, Deserialize, PartialEq)]
pub struct CompositionError {
pub message: Option<String>,
pub extensions: Option<CompositionErrorExtensions>,
}
impl Display for CompositionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(msg) = &self.message {
f.write_fmt(format_args!("{code}: {msg}", code = self.code(), msg = msg))
} else {
f.write_str(self.code())
}
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct CompositionErrorExtensions {
pub code: String,
}
impl CompositionError {
pub fn code(&self) -> &str {
match self.extensions {
Some(ref ext) => &*ext.code,
None => "UNKNOWN",
}
}
}
pub fn harmonize(service_list: ServiceList) -> Result<String, Vec<CompositionError>> {
let mut runtime = JsRuntime::new(Default::default());
let (tx, rx) = channel();
runtime.register_op(
"op_print",
|_state, zero_copy| {
let mut out = std::io::stdout();
for buf in zero_copy {
out.write_all(&buf)
.expect("failure writing buffered output");
}
Op::Sync(Box::new([]))
},
);
runtime.register_op(
"op_composition_result",
json_op_sync(move |_state, value, _zero_copy| {
tx.send(serde_json::from_value(value).expect("deserializing composition result"))
.expect("channel must be open");
Ok(serde_json::json!(null))
}),
);
runtime
.execute(
"<init>",
r#"
// First we initialize the ops cache.
// This maps op names to their id's.
Deno.core.ops();
// Then we define a print function that uses
// our op_print op to display the stringified argument.
const _newline = new Uint8Array([10]);
function print(value) {
Deno.core.dispatchByName('op_print', Deno.core.encode(value.toString()), _newline);
}
function done(result) {
Deno.core.jsonOpSync('op_composition_result', result);
}
// Finally we register the error class used during do_compose.js.
// so that it throws the correct class.
Deno.core.registerErrorClass('Error', Error);
// We build some of the preliminary objects that our Rollup-built package is
// expecting to be present in the environment.
// node_fetch_1 is an unused external dependency we don't bundle. See the
// configuration in this package's 'rollup.config.js' for where this is marked
// as an external dependency and thus not packaged into the bundle.
node_fetch_1 = {};
// 'process' is a Node.js ism. We rely on process.env.NODE_ENV, in
// particular, to determine whether or not we are running in a debug
// mode. For the purposes of harmonizer, we don't gain anything from
// running in such a mode.
process = { env: { "NODE_ENV": "production" }};
// Some JS runtime implementation specific bits that we rely on that
// need to be initialized as empty objects.
global = {};
exports = {};
"#,
)
.expect("unable to initialize composition runtime environment");
runtime
.execute("composition.js", include_str!("../dist/composition.js"))
.expect("unable to evaluate composition module");
let service_list_javascript = format!(
"serviceList = {}",
serde_json::to_string(&service_list)
.expect("unable to serialize service list into JavaScript runtime")
);
runtime
.execute("<set_service_list>", &service_list_javascript)
.expect("unable to evaluate service list in JavaScript runtime");
runtime
.execute("do_compose.js", include_str!("../js/do_compose.js"))
.expect("unable to invoke composition in JavaScript runtime");
rx.recv().expect("channel remains open")
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
use crate::{harmonize, ServiceDefinition};
insta::assert_snapshot!(harmonize(vec![
ServiceDefinition::new(
"users",
"undefined",
"
type User {
id: ID
name: String
}
type Query {
users: [User!]
}
"
),
ServiceDefinition::new(
"movies",
"undefined",
"
type Movie {
title: String
name: String
}
extend type User {
favorites: [Movie!]
}
type Query {
movies: [Movie!]
}
"
)
])
.unwrap());
}
}