aboutsummaryrefslogtreecommitdiff
path: root/src/commands/discocaml.rs
blob: 8565c6fdb05dabc7661f2cbb951ff9fe17dafd65 (plain)
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use anyhow::{anyhow, bail, Context as _, Error, Result};
use futures::Future;
use serde::{Deserialize, Serialize};
use serde_json::de::Deserializer;
use serenity::{
    all::{
        CommandDataOptionValue, CommandInteraction, CommandOptionType, CommandType,
        ComponentInteraction, ComponentInteractionDataKind, InteractionId,
        InteractionResponseFlags, Member, RoleId,
    },
    builder::{
        CreateButton, CreateCommand, CreateCommandOption, CreateInteractionResponse,
        CreateInteractionResponseMessage,
    },
    client::Context,
    model::Permissions,
};
use sqlx::SqlitePool;
use std::process::Stdio;
use tokio::{io::AsyncWriteExt, process::Command};

use crate::utils::EnumAsArray;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DiscocamlConfig {
    pub command: Vec<String>,
    pub role: RoleId,
}

#[derive(Debug, PartialEq, Serialize)]
pub struct DiscocamlRequest {
    pub expr: String,
    pub command: DiscocamlCommand,
}

#[derive(Debug, PartialEq, Serialize)]
pub enum DiscocamlCommand {
    Parse,
    DrawTree,
    RunCBN,
    RunCBV,
    StepCBN,
    StepCBV,
}

/// A response outputted by the discocaml subprocess as a JSON string.
///
/// ```
/// # use lambo::{commands::discocaml::*, utils::EnumAsArray};
/// # use serde::Deserialize;
/// # use serde_json::Deserializer;
///
/// let example = r#"
/// [ "Expr"
/// , { "expr": "1 + 2"
///   , "has_redex": true
///   }
/// ]
/// "#;
/// let expected = DiscocamlResponse::Expr(DiscocamlResponseExpr {
///     expr: "1 + 2".to_string(),
///     has_redex: true,
/// });
///
/// let mut de = Deserializer::from_str(&example);
/// let out = DiscocamlResponse::deserialize(EnumAsArray(&mut de)).unwrap();
/// de.end().unwrap();
///
/// assert_eq!(out, expected);
/// ```
#[derive(Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub enum DiscocamlResponse {
    Expr(DiscocamlResponseExpr),
    Error(String),
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct DiscocamlResponseExpr {
    pub expr: String,
    pub has_redex: bool,
}

impl DiscocamlResponseExpr {
    async fn save(&self, db: &SqlitePool, id: InteractionId) -> Result<()> {
        let interaction_id = i64::from(id);
        sqlx::query!(
            "INSERT INTO discocaml_exprs (interaction_id, expr) VALUES (?, ?)",
            interaction_id,
            self.expr
        )
        .execute(db)
        .await?;
        Ok(())
    }
}

pub fn command() -> CreateCommand {
    CreateCommand::new("discocaml")
        .kind(CommandType::ChatInput)
        .default_member_permissions(Permissions::empty())
        .dm_permission(true)
        .description("Sends this expression to the disco!")
        .add_option(
            CreateCommandOption::new(
                CommandOptionType::String,
                "expr",
                "The expression to operate on.",
            )
            .required(true),
        )
}

async fn check_permissions(config: &DiscocamlConfig, member: Option<&Member>) -> Result<()> {
    if let Some(member) = member {
        if !member.roles.contains(&config.role) {
            bail!("This command can only be used by <@&{}>.", config.role)
        }
        Ok(())
    } else {
        bail!("This command cannot be used in DMs.")
    }
}

async fn respond_with_error<E: std::error::Error, F: Future<Output = Result<(), E>>>(
    err: &Error,
    send: impl FnOnce(CreateInteractionResponse) -> F,
) {
    let msg = CreateInteractionResponseMessage::new()
        .content(format!(":no_entry_sign: {}", err))
        .flags(InteractionResponseFlags::EPHEMERAL);
    if let Err(err) = send(CreateInteractionResponse::Message(msg)).await {
        log::error!(
            "failed to respond to command that failed permissions check: {:?}",
            err
        )
    }
}

pub async fn run_discocaml(
    config: &DiscocamlConfig,
    req: &DiscocamlRequest,
) -> Result<DiscocamlResponseExpr> {
    let mut child = Command::new(&config.command[0])
        .args(&config.command)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .context("failed to start discocaml")?;

    let mut stdin = child.stdin.take().unwrap();
    let req = serde_json::to_string(req).context("failed to serialize request to discocaml")?;
    stdin
        .write_all(req.as_bytes())
        .await
        .context("failed to write request to discocaml")?;
    stdin
        .shutdown()
        .await
        .context("failed to close pipe to discocaml")?;
    drop(stdin);
    drop(req);

    let output = child
        .wait_with_output()
        .await
        .context("failed to wait for discocaml to complete")?;
    if !output.status.success() {
        bail!("discocaml exited with non-zero status {:?}", output.status)
    }

    let mut de = Deserializer::from_slice(&output.stdout);
    let out = DiscocamlResponse::deserialize(EnumAsArray(&mut de))
        .context("failed to parse response from discocaml")?;
    de.end()
        .context("failed to parse response from discocaml")?;

    match out {
        DiscocamlResponse::Expr(expr) => Ok(expr),
        DiscocamlResponse::Error(err) => bail!("got an error from discocaml: {:?}", err),
    }
}

fn make_response_message(expr: &DiscocamlResponseExpr) -> CreateInteractionResponseMessage {
    // TODO: Real escaping
    CreateInteractionResponseMessage::new()
        .content(format!("```ocaml\n{}\n```", expr.expr))
        .button(CreateButton::new("draw-tree").label("Draw Tree"))
        .button(
            CreateButton::new("step-cbv")
                .label("Step (CBV)")
                .disabled(!expr.has_redex),
        )
        .button(
            CreateButton::new("step-cbn")
                .label("Step (CBN)")
                .disabled(!expr.has_redex),
        )
        .button(
            CreateButton::new("run-cbv")
                .label("Run (CBV)")
                .disabled(!expr.has_redex),
        )
        .button(
            CreateButton::new("run-cbn")
                .label("Run (CBN)")
                .disabled(!expr.has_redex),
        )
}

pub async fn handle_command(
    ctx: &Context,
    config: &DiscocamlConfig,
    db: &SqlitePool,
    command: &CommandInteraction,
) -> Result<()> {
    // Check that the required role was present.
    if let Err(err) = check_permissions(config, command.member.as_deref()).await {
        respond_with_error(&err, |res| command.create_response(&ctx, res)).await;
        return Err(err.context("permissions check failed"));
    }

    // Parse the expression out.
    let mut expr = None;
    for option in &command.data.options {
        match (&option.name as &str, &option.value) {
            ("expr", CommandDataOptionValue::String(value)) => expr = Some(value),
            _ => {
                let err = anyhow!("unknown option {:?}", option);
                respond_with_error(&err, |res| command.create_response(&ctx, res)).await;
                return Err(err);
            }
        }
    }
    let expr = if let Some(expr) = expr {
        expr
    } else {
        let err = anyhow!("missing option {:?}", "expr");
        respond_with_error(&err, |res| command.create_response(&ctx, res)).await;
        return Err(err);
    };

    // Round-trip the expression through discocaml.
    let req = DiscocamlRequest {
        expr: expr.to_string(),
        command: DiscocamlCommand::Parse,
    };
    let res = match run_discocaml(config, &req).await {
        Ok(res) => res,
        Err(err) => {
            respond_with_error(&err, |res| command.create_response(&ctx, res)).await;
            return Err(err.context("failed to run discocaml"));
        }
    };

    // Insert the output expression in the database.
    if let Err(err) = res
        .save(db, command.id)
        .await
        .context("failed to save expression to database")
    {
        respond_with_error(&err, |res| command.create_response(&ctx, res)).await;
        return Err(err);
    }

    // Respond with the expression and the buttons.
    command
        .create_response(
            &ctx,
            CreateInteractionResponse::Message(make_response_message(&res)),
        )
        .await
        .context("failed to respond")
}

pub async fn handle_button(
    ctx: &Context,
    config: &DiscocamlConfig,
    db: &SqlitePool,
    component: &ComponentInteraction,
) -> Result<()> {
    // Check that the required role was present.
    if let Err(err) = check_permissions(config, component.member.as_ref()).await {
        respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
        return Err(err.context("permissions check failed"));
    }

    // Find the interaction ID from the message it was in response to.
    let interaction_id = if let Some(interaction) = &component.message.interaction {
        i64::from(interaction.id)
    } else {
        let err = anyhow!(
            "button was pressed in response to an unknown message {:?}",
            component.message.id
        );
        respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
        return Err(err);
    };

    // Fetch the expression it was in response to.
    let result = sqlx::query!(
        "SELECT expr FROM discocaml_exprs WHERE interaction_id = ?",
        interaction_id,
    )
    .fetch_one(db)
    .await
    .context("failed to load expression from database");
    let expr = match result {
        Ok(expr) => expr.expr,
        Err(err) => {
            respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
            return Err(err);
        }
    };

    // Come up with a command for discocaml based on which button it was.
    let command = match (&component.data.kind, &component.data.custom_id as &str) {
        (ComponentInteractionDataKind::Button, "draw-tree") => DiscocamlCommand::DrawTree,
        (ComponentInteractionDataKind::Button, "step-cbv") => DiscocamlCommand::StepCBV,
        (ComponentInteractionDataKind::Button, "step-cbn") => DiscocamlCommand::StepCBN,
        (ComponentInteractionDataKind::Button, "run-cbv") => DiscocamlCommand::RunCBV,
        (ComponentInteractionDataKind::Button, "run-cbn") => DiscocamlCommand::RunCBN,
        _ => {
            let err = anyhow!("unknown component {:?}", component.data);
            respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
            return Err(err);
        }
    };

    // Send discocaml the request.
    let req = DiscocamlRequest { expr, command };
    let res = match run_discocaml(config, &req).await {
        Ok(res) => res,
        Err(err) => {
            respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
            return Err(err.context("failed to run discocaml"));
        }
    };

    // Insert the output expression in the database.
    if let Err(err) = res
        .save(db, component.id)
        .await
        .context("failed to save expression to database")
    {
        respond_with_error(&err, |res| component.create_response(&ctx, res)).await;
        return Err(err);
    }

    // Respond with the expression and the buttons.
    component
        .create_response(
            &ctx,
            CreateInteractionResponse::Message(make_response_message(&res)),
        )
        .await
        .context("failed to respond")
}