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
use std::{collections::HashMap, time::Duration};

use anyhow::Context;
use cf_pty_process_alpha::{unix::UnixPtySystem, Child, PtySystem};
use serde::{Deserialize, Serialize};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    sync::mpsc::{self, Sender},
    time,
};

static CHUNK_LEN: usize = 4096;

pub struct Capabilities {
    pub shell: bool,
    pub actions: Option<Vec<Action>>,
}

/// Outgoing messages sent to the Relay service.
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "t", content = "c")]
pub enum TxMessage {
    #[serde(rename = "tty_output")]
    Output { session_id: String, data: String },
    #[serde(rename = "session_created")]
    SessionCreated { session_id: String },
    #[serde(rename = "capabilities")]
    Capabilities {
        shell: bool,
        actions: Option<Vec<Action>>,
    },
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Action {
    pub name: String,
}

#[derive(Debug, Clone)]
pub enum RecvMessage {
    Command { data: String },
    End,
}

#[derive(Debug, Clone)]
pub struct CommandName {
    pub name: String,
    pub args: Vec<String>,
}

pub struct Manager {
    tx: Sender<TxMessage>,
    command: CommandName,
    sessions: HashMap<String, Sender<RecvMessage>>,
}

impl Manager {
    pub fn new(tx: Sender<TxMessage>, command: CommandName) -> Self {
        Self {
            tx,
            command,
            sessions: HashMap::new(),
        }
    }

    pub async fn send_command(
        &mut self,
        session_id: String,
        command: String,
    ) -> anyhow::Result<()> {
        let proc_tx = self
            .sessions
            .get(&session_id)
            .context("session not found")?;

        proc_tx.send(RecvMessage::Command { data: command }).await?;
        Ok(())
    }

    pub async fn create_session(&mut self, id: String) -> anyhow::Result<()> {
        let proc_tx = spawn_process(id.clone(), self.command.clone(), self.tx.clone()).await?;
        self.sessions.insert(id.clone(), proc_tx);

        Ok(())
    }

    pub async fn end_session(&mut self, id: String) -> anyhow::Result<()> {
        let session = self.sessions.get(&id).context("session not found")?;
        session.send(RecvMessage::End).await?;
        Ok(())
    }
}

async fn spawn_process(
    session_id: String,
    command: CommandName,
    tx: Sender<TxMessage>,
) -> anyhow::Result<Sender<RecvMessage>> {
    let mut cmd = tokio::process::Command::new(command.name.clone());
    cmd.args(command.args);
    let (proc_tx, mut proc_rx) = mpsc::channel(100);

    let mut instance = UnixPtySystem::spawn(
        cmd,
        cf_pty_process_alpha::PtySystemOptions { raw_mode: false },
    )?;

    tx.send(TxMessage::SessionCreated {
        session_id: session_id.clone(),
    })
    .await?;

    let mut write = instance.write;
    let mut read = instance.read;

    tokio::spawn(async move {
        loop {
            match proc_rx.recv().await {
                Some(RecvMessage::Command { data }) => {
                    let with_newline = format!("{data}\n");
                    write.write(with_newline.as_bytes()).await.unwrap();
                }
                Some(RecvMessage::End) => {
                    // try and kill the child process with best effort
                    if let Err(e) = instance.child.kill().await {
                        println!("error ending session: {}", e)
                    };
                }
                None => break,
            };
        }
    });

    tokio::spawn(async move {
        let mut buffer = vec![0u8; CHUNK_LEN];
        while let Ok(read) = read.read(buffer.as_mut_slice()).await {
            if read == 0 {
                println!("Received {} bytes", read);
                break;
            }

            println!("Received {} bytes", read);

            let mut buf = vec![0; read];
            buf.copy_from_slice(&buffer[0..read]);

            let data_str = std::str::from_utf8(&buf).unwrap();

            println!("data: {data_str}");
            let msg = TxMessage::Output {
                data: data_str.to_owned(),
                session_id: session_id.clone(),
            };
            if let Err(e) = tx.send(msg).await {
                println!("mpsc send error: {e}")
            }

            time::sleep(Duration::from_micros(150)).await;
        }
    });

    return Ok(proc_tx);
}