ravnpad 1.3.14

A simple UTF-8 notepad
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
#[cfg(unix)]
use std::io::Write as _;
use std::io::{self, Read as _};
use std::path::{Path, PathBuf};

const MAX_MESSAGE: usize = 1024 * 1024;
const PROTOCOL_VERSION: u32 = 2;

#[derive(Debug, Deserialize)]
struct Endpoint {
    protocol_version: u32,
    instance_id: String,
    address: String,
    token: String,
}

#[derive(Serialize)]
struct FileRead<'a> {
    protocol_version: u32,
    path: &'a Path,
    content_complete: bool,
    range_unit: &'static str,
    text: &'a str,
}

fn main() {
    let code = match run() {
        Ok(()) => 0,
        Err(error) => {
            eprintln!("{error}");
            error.exit_code()
        }
    };
    std::process::exit(code);
}

#[derive(Debug)]
struct CliError {
    code: i32,
    message: String,
}

impl CliError {
    fn usage(message: impl Into<String>) -> Self {
        Self {
            code: 2,
            message: message.into(),
        }
    }
    fn unavailable(message: impl Into<String>) -> Self {
        Self {
            code: 3,
            message: message.into(),
        }
    }
    fn protocol(message: impl Into<String>) -> Self {
        Self {
            code: 4,
            message: message.into(),
        }
    }
    fn exit_code(&self) -> i32 {
        self.code
    }
}

impl std::fmt::Display for CliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

fn run() -> Result<(), CliError> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    match args.as_slice() {
        [family, command, path, rest @ ..] if family == "file" && command == "read" => {
            if rest.iter().any(|arg| arg != "--json") {
                return Err(CliError::usage(usage()));
            }
            let text = std::fs::read_to_string(path)
                .map_err(|error| CliError::unavailable(format!("cannot read {path}: {error}")))?;
            print_json(&FileRead {
                protocol_version: PROTOCOL_VERSION,
                path: Path::new(path),
                content_complete: true,
                range_unit: "utf8-byte",
                text: &text,
            })
        }
        [family, command, rest @ ..] if family == "document" && command == "status" => {
            let instance = option(rest, "--instance")?;
            ensure_known(rest, &["--instance", "--json"])?;
            let endpoint = endpoint(instance)?;
            ensure_instance(&endpoint, instance)?;
            send(
                &endpoint.address,
                &json!({
                    "command": "document_status",
                    "token": endpoint.token,
                }),
            )
        }
        [family, command, rest @ ..] if family == "document" && command == "read" => {
            let instance = option(rest, "--instance")?;
            let document = option(rest, "--document")?;
            let offset = optional_usize(rest, "--offset")?;
            let limit = optional_usize(rest, "--limit")?;
            ensure_known(
                rest,
                &["--instance", "--document", "--offset", "--limit", "--json"],
            )?;
            let endpoint = endpoint(instance)?;
            ensure_instance(&endpoint, instance)?;
            send(
                &endpoint.address,
                &json!({
                    "command": "document_read",
                    "token": endpoint.token,
                    "document_id": document,
                    "offset": offset,
                    "limit": limit,
                }),
            )
        }
        [family, command, rest @ ..] if family == "document" && command == "propose" => {
            let instance = option(rest, "--instance")?;
            let document = option(rest, "--document")?;
            ensure_known(rest, &["--instance", "--document", "--stdin", "--json"])?;
            if !rest.iter().any(|arg| arg == "--stdin") {
                return Err(CliError::usage("document propose requires --stdin"));
            }
            let mut input = String::new();
            io::stdin()
                .take((MAX_MESSAGE + 1) as u64)
                .read_to_string(&mut input)
                .map_err(|error| CliError::protocol(format!("cannot read stdin: {error}")))?;
            if input.len() > MAX_MESSAGE {
                return Err(CliError::protocol("patch exceeds one MiB"));
            }
            let mut patch: Value = serde_json::from_str(&input)
                .map_err(|error| CliError::protocol(format!("invalid patch JSON: {error}")))?;
            if patch.get("document_id").is_none() {
                patch["document_id"] = Value::String(document.to_owned());
            }
            if patch.get("document_id").and_then(Value::as_str) != Some(document) {
                return Err(CliError::usage("patch document_id differs from --document"));
            }
            let endpoint = endpoint(instance)?;
            ensure_instance(&endpoint, instance)?;
            send(
                &endpoint.address,
                &json!({ "command": "document_propose", "token": endpoint.token, "patch": patch }),
            )
        }
        _ => Err(CliError::usage(usage())),
    }
}

fn usage() -> String {
    "usage:\n  ravnpad-cli file read PATH --json\n  ravnpad-cli document status --instance ID --json\n  ravnpad-cli document read --instance ID --document ID [--offset N --limit N] --json\n  ravnpad-cli document propose --instance ID --document ID --stdin --json".into()
}

fn option<'a>(args: &'a [String], name: &str) -> Result<&'a str, CliError> {
    args.windows(2)
        .find(|pair| pair[0] == name)
        .map(|pair| pair[1].as_str())
        .ok_or_else(|| CliError::usage(format!("missing {name}")))
}

fn optional_usize(args: &[String], name: &str) -> Result<Option<usize>, CliError> {
    match args.windows(2).find(|pair| pair[0] == name) {
        Some(pair) => pair[1]
            .parse()
            .map(Some)
            .map_err(|_| CliError::usage(format!("{name} must be a non-negative integer"))),
        None => Ok(None),
    }
}

fn ensure_known(args: &[String], value_options: &[&str]) -> Result<(), CliError> {
    let mut index = 0;
    while index < args.len() {
        let argument = args[index].as_str();
        if argument == "--json" || argument == "--stdin" {
            index += 1;
            continue;
        }
        if value_options.contains(&argument) && index + 1 < args.len() {
            index += 2;
            continue;
        }
        return Err(CliError::usage(format!(
            "unknown or incomplete option: {argument}"
        )));
    }
    Ok(())
}

fn endpoint(instance: &str) -> Result<Endpoint, CliError> {
    let path = config_dir()
        .ok_or_else(|| CliError::unavailable("configuration directory unavailable"))?
        .join("agent")
        .join(format!("{instance}.json"));
    let bytes = std::fs::read(&path).map_err(|error| {
        CliError::unavailable(format!("RavnPad instance is unavailable: {error}"))
    })?;
    serde_json::from_slice(&bytes)
        .map_err(|error| CliError::protocol(format!("invalid endpoint metadata: {error}")))
}

fn ensure_instance(endpoint: &Endpoint, expected: &str) -> Result<(), CliError> {
    if endpoint.protocol_version != PROTOCOL_VERSION {
        return Err(CliError::protocol("unsupported protocol version"));
    }
    if endpoint.instance_id != expected {
        return Err(CliError::protocol("endpoint instance mismatch"));
    }
    Ok(())
}

fn config_dir() -> Option<PathBuf> {
    #[cfg(windows)]
    {
        Some(PathBuf::from(std::env::var_os("APPDATA")?).join("RavnPad"))
    }
    #[cfg(target_os = "macos")]
    {
        Some(PathBuf::from(std::env::var_os("HOME")?).join("Library/Application Support/RavnPad"))
    }
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        let base = std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .or_else(|| Some(PathBuf::from(std::env::var_os("HOME")?).join(".config")))?;
        Some(base.join("ravnpad"))
    }
}

fn send(address: &str, request: &Value) -> Result<(), CliError> {
    let encoded =
        serde_json::to_vec(request).map_err(|error| CliError::protocol(error.to_string()))?;
    if encoded.len() > MAX_MESSAGE {
        return Err(CliError::protocol("request exceeds one MiB"));
    }
    let response = exchange(address, &encoded)?;
    let value: Value = serde_json::from_slice(&response)
        .map_err(|error| CliError::protocol(format!("invalid host response: {error}")))?;
    print_json(&value)?;
    if value.get("status").and_then(Value::as_str) == Some("error") {
        Err(CliError::protocol(
            value
                .pointer("/error/message")
                .and_then(Value::as_str)
                .unwrap_or("document operation failed"),
        ))
    } else {
        Ok(())
    }
}

fn print_json(value: &impl Serialize) -> Result<(), CliError> {
    serde_json::to_writer(io::stdout().lock(), value)
        .map_err(|error| CliError::protocol(error.to_string()))?;
    println!();
    Ok(())
}

#[cfg(unix)]
fn exchange(address: &str, request: &[u8]) -> Result<Vec<u8>, CliError> {
    use std::net::Shutdown;
    use std::os::unix::net::UnixStream;
    let mut stream = UnixStream::connect(address)
        .map_err(|error| CliError::unavailable(format!("cannot connect to RavnPad: {error}")))?;
    stream
        .write_all(request)
        .map_err(|error| CliError::unavailable(error.to_string()))?;
    stream
        .shutdown(Shutdown::Write)
        .map_err(|error| CliError::unavailable(error.to_string()))?;
    let mut response = Vec::new();
    stream
        .take((MAX_MESSAGE + 1) as u64)
        .read_to_end(&mut response)
        .map_err(|error| CliError::unavailable(error.to_string()))?;
    if response.len() > MAX_MESSAGE {
        return Err(CliError::protocol("response exceeds one MiB"));
    }
    Ok(response)
}

#[cfg(windows)]
fn exchange(address: &str, request: &[u8]) -> Result<Vec<u8>, CliError> {
    use std::os::windows::ffi::OsStrExt as _;
    type Handle = *mut std::ffi::c_void;
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn WaitNamedPipeW(name: *const u16, timeout: u32) -> i32;
        fn CreateFileW(
            name: *const u16,
            access: u32,
            share: u32,
            security: *mut std::ffi::c_void,
            creation: u32,
            flags: u32,
            template: Handle,
        ) -> Handle;
        fn SetNamedPipeHandleState(
            pipe: Handle,
            mode: *const u32,
            max_collection: *const u32,
            timeout: *const u32,
        ) -> i32;
        fn WriteFile(
            file: Handle,
            buffer: *const u8,
            size: u32,
            written: *mut u32,
            overlapped: *mut std::ffi::c_void,
        ) -> i32;
        fn ReadFile(
            file: Handle,
            buffer: *mut u8,
            size: u32,
            read: *mut u32,
            overlapped: *mut std::ffi::c_void,
        ) -> i32;
        fn CloseHandle(handle: Handle) -> i32;
    }
    const INVALID_HANDLE: Handle = -1_isize as Handle;
    let name: Vec<u16> = std::ffi::OsStr::new(address)
        .encode_wide()
        .chain(Some(0))
        .collect();
    if unsafe { WaitNamedPipeW(name.as_ptr(), 5_000) } == 0 {
        return Err(CliError::unavailable(format!(
            "RavnPad pipe unavailable: {}",
            io::Error::last_os_error()
        )));
    }
    let pipe = unsafe {
        CreateFileW(
            name.as_ptr(),
            0xC0000000,
            0,
            std::ptr::null_mut(),
            3,
            0,
            std::ptr::null_mut(),
        )
    };
    if pipe == INVALID_HANDLE {
        return Err(CliError::unavailable(format!(
            "cannot connect to RavnPad: {}",
            io::Error::last_os_error()
        )));
    }
    let result = (|| {
        let mode = 2_u32;
        if unsafe { SetNamedPipeHandleState(pipe, &mode, std::ptr::null(), std::ptr::null()) } == 0
        {
            return Err(CliError::unavailable(
                io::Error::last_os_error().to_string(),
            ));
        }
        let mut written = 0;
        if unsafe {
            WriteFile(
                pipe,
                request.as_ptr(),
                request.len() as u32,
                &mut written,
                std::ptr::null_mut(),
            )
        } == 0
        {
            return Err(CliError::unavailable(
                io::Error::last_os_error().to_string(),
            ));
        }
        let mut response = vec![0_u8; MAX_MESSAGE];
        let mut read = 0;
        if unsafe {
            ReadFile(
                pipe,
                response.as_mut_ptr(),
                response.len() as u32,
                &mut read,
                std::ptr::null_mut(),
            )
        } == 0
        {
            return Err(CliError::unavailable(
                io::Error::last_os_error().to_string(),
            ));
        }
        response.truncate(read as usize);
        Ok(response)
    })();
    unsafe {
        CloseHandle(pipe);
    }
    result
}