hydro_lang/deploy/maelstrom/
deploy_runtime_maelstrom.rs1#![allow(
7 unused,
8 reason = "unused in trybuild but the __staged version is needed"
9)]
10#![allow(missing_docs, reason = "used internally")]
11
12use std::io::{BufRead, Write};
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, Ordering};
15
16use futures::{Stream, StreamExt};
17use serde::{Deserialize, Serialize};
18use stageleft::{QuotedWithContext, RuntimeData, q};
19
20use crate::forward_handle::ForwardHandle;
21use crate::live_collections::boundedness::Unbounded;
22use crate::live_collections::keyed_stream::KeyedStream;
23use crate::live_collections::stream::{ExactlyOnce, NoOrder, TotalOrder};
24use crate::location::dynamic::LocationId;
25use crate::location::{Cluster, LocationKey, MembershipEvent};
26use crate::nondet::nondet;
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct MaelstromMessage<T> {
31 pub src: String,
32 pub dest: String,
33 pub body: T,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct InitBody {
39 #[serde(rename = "type")]
40 pub msg_type: String,
41 pub msg_id: u64,
42 pub node_id: String,
43 pub node_ids: Vec<String>,
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct InitOkBody {
49 #[serde(rename = "type")]
50 pub msg_type: String,
51 pub in_reply_to: u64,
52}
53
54pub struct MaelstromMeta {
57 pub node_id: String,
58 pub node_ids: Vec<String>,
59 stdin_tx: tokio::sync::broadcast::Sender<String>,
60 peers_ready: Arc<AtomicBool>,
64}
65
66impl MaelstromMeta {
67 pub fn subscribe_stdin(&self) -> tokio_stream::wrappers::BroadcastStream<String> {
70 tokio_stream::wrappers::BroadcastStream::new(self.stdin_tx.subscribe())
71 }
72
73 pub fn peers_ready(&self) -> Arc<AtomicBool> {
91 self.peers_ready.clone()
92 }
93
94 pub fn start_receiving(&self) {
96 let tx_clone = self.stdin_tx.clone();
97 let peers_ready = self.peers_ready.clone();
98 let node_ids: std::collections::HashSet<String> = self.node_ids.iter().cloned().collect();
99
100 std::thread::spawn(move || {
102 let stdin = std::io::stdin();
103 for line in stdin.lock().lines() {
104 match line {
105 Ok(l) => {
106 if !peers_ready.load(Ordering::Relaxed)
107 && message_activates_node(&l, &node_ids)
108 {
109 peers_ready.store(true, Ordering::Release);
110 }
111 let _ = tx_clone.send(l);
113 }
114 Err(_) => break,
115 }
116 }
117 });
118 }
119}
120
121fn message_activates_node(line: &str, node_ids: &std::collections::HashSet<String>) -> bool {
127 let Ok(msg) = serde_json::from_str::<MaelstromMessage<serde_json::Value>>(line) else {
128 return false;
129 };
130 node_ids.contains(&msg.src) || msg.src.starts_with('c')
131}
132
133pub fn maelstrom_init() -> MaelstromMeta {
137 let stdin = std::io::stdin();
138 let mut stdout = std::io::stdout();
139
140 let msg: MaelstromMessage<InitBody> = loop {
149 let mut line = String::new();
150 let bytes_read = stdin
151 .lock()
152 .read_line(&mut line)
153 .expect("Failed to read init message");
154
155 if bytes_read == 0 {
156 eprintln!("stdin closed before an init message was received; exiting");
162 std::process::exit(0);
163 }
164
165 let parsed: MaelstromMessage<serde_json::Value> =
166 serde_json::from_str(&line).expect("Failed to parse message while waiting for init");
167
168 if parsed.body.get("type").and_then(|t| t.as_str()) == Some("init") {
169 let body: InitBody =
170 serde_json::from_value(parsed.body).expect("Failed to parse init message");
171 break MaelstromMessage {
172 src: parsed.src,
173 dest: parsed.dest,
174 body,
175 };
176 }
177 eprintln!(
178 "dropping message received before init (lossy channel): {}",
179 line.trim_end()
180 );
181 };
182
183 let (stdin_tx, _) = tokio::sync::broadcast::channel::<String>(1024);
185
186 let meta = MaelstromMeta {
187 node_id: msg.body.node_id.clone(),
188 node_ids: msg.body.node_ids.clone(),
189 stdin_tx,
190 peers_ready: Arc::new(AtomicBool::new(false)),
191 };
192
193 let response = MaelstromMessage {
195 src: msg.body.node_id,
196 dest: msg.src,
197 body: InitOkBody {
198 msg_type: "init_ok".to_owned(),
199 in_reply_to: msg.body.msg_id,
200 },
201 };
202
203 let response_json = serde_json::to_string(&response).expect("Failed to serialize init_ok");
204 writeln!(stdout, "{}", response_json).expect("Failed to write init_ok");
205 stdout.flush().expect("Failed to flush stdout");
206
207 meta
208}
209
210pub(super) fn cluster_members<'a>(
214 meta: RuntimeData<&'a MaelstromMeta>,
215 _of_cluster: LocationKey,
216) -> impl QuotedWithContext<'a, &'a [String], ()> + Clone + 'a {
217 q!({
218 let members: &'static [String] = Box::leak(
219 meta.node_ids
220 .iter()
221 .cloned()
222 .collect::<Vec<String>>()
223 .into_boxed_slice(),
224 );
225 members
226 })
227}
228
229pub(super) fn cluster_self_id<'a>(
231 meta: RuntimeData<&'a MaelstromMeta>,
232) -> impl QuotedWithContext<'a, String, ()> + Clone + 'a {
233 q!(meta.node_id.clone())
234}
235
236pub(super) fn cluster_membership_stream<'a>(
239 _location_id: &LocationId,
240) -> impl QuotedWithContext<'a, Box<dyn Stream<Item = (String, MembershipEvent)> + Unpin>, ()> {
241 let meta: RuntimeData<&MaelstromMeta> = RuntimeData::new("__hydro_lang_maelstrom_meta");
242 q!(Box::new(futures::stream::iter(
243 meta.node_ids
244 .iter()
245 .map(|id| (id.clone(), MembershipEvent::Joined))
246 .collect::<Vec<_>>()
247 ))
248 as Box<
249 dyn futures::Stream<Item = (String, MembershipEvent)> + Unpin,
250 >)
251}
252
253pub(super) fn deploy_maelstrom_m2m(meta: RuntimeData<&MaelstromMeta>) -> (syn::Expr, syn::Expr) {
256 let sink_expr = q!({
260 let node_id = meta.node_id.clone();
261 let peers_ready = meta.peers_ready();
262 sinktools::map(
263 move |(dest_id, payload): (String, bytes::Bytes)| {
264 let msg = serde_json::json!({
265 "src": node_id,
266 "dest": dest_id.as_str(),
267 "body": {
268 "type": "hydro_data",
269 "data": payload.to_vec()
270 }
271 });
272 let mut line = serde_json::to_string(&msg).unwrap();
273 line.push('\n');
274 line
275 },
276 futures::sink::unfold(
277 peers_ready,
278 |peers_ready: std::sync::Arc<std::sync::atomic::AtomicBool>, line: String| {
279 Box::pin(async move {
280 if peers_ready.load(std::sync::atomic::Ordering::Acquire) {
281 print!("{}", line);
282 std::io::stdout().flush().ok();
283 } else {
284 eprintln!(
285 "dropping message sent before peers are known to be up (lossy channel): {}",
286 line.trim_end()
287 );
288 }
289 Ok::<_, std::io::Error>(peers_ready)
290 })
291 },
292 ),
293 )
294 })
295 .splice_untyped_ctx(&());
296
297 let source_expr = q!({
299 let node_ids: std::collections::HashSet<String> = meta.node_ids.iter().cloned().collect();
300 let lines = meta.subscribe_stdin();
301 futures::StreamExt::filter_map(lines, move |line_result| {
302 let node_ids = node_ids.clone();
303 Box::pin(async move {
304 let line = line_result.ok()?;
305 let mut msg =
306 serde_json::from_str::<MaelstromMessage<serde_json::Value>>(&line).ok()?;
307 if msg
309 .body
310 .get("type")
311 .is_some_and(|t| t.as_str() == Some("hydro_data"))
312 {
313 let deser: Vec<u8> =
314 serde_json::from_value(msg.body.get_mut("data").unwrap().take()).unwrap();
315 Some(Ok::<_, std::io::Error>((
316 msg.src,
317 bytes::BytesMut::from(&deser[..]),
318 )))
319 } else {
320 None
321 }
322 })
323 })
324 })
325 .splice_untyped_ctx(&());
326
327 (sink_expr, source_expr)
328}
329
330pub fn maelstrom_client_source(
336 meta: &MaelstromMeta,
337) -> impl Stream<Item = (String, serde_json::Value)> + Unpin {
338 use std::collections::HashSet;
339
340 let node_ids: HashSet<String> = meta.node_ids.iter().cloned().collect();
341 let lines = meta.subscribe_stdin();
342
343 Box::pin(lines.filter_map(move |line_result| {
344 let node_ids = node_ids.clone();
345 async move {
346 let line = line_result.ok()?;
347 let msg: MaelstromMessage<serde_json::Value> = serde_json::from_str(&line).ok()?;
348 if !node_ids.contains(&msg.src) {
350 Some((msg.src, msg.body))
351 } else {
352 None
353 }
354 }
355 }))
356}
357
358pub fn maelstrom_send_response(node_id: &str, client_id: &str, body: serde_json::Value) {
362 use std::io::Write;
363
364 let msg = MaelstromMessage {
365 src: node_id.to_owned(),
366 dest: client_id.to_owned(),
367 body,
368 };
369
370 let json = serde_json::to_string(&msg).expect("Failed to serialize response");
371 println!("{}", json);
372 std::io::stdout().flush().ok();
373}