maincopy-cli 0.1.0

Operator command-line client for the Maincopy administration API
Documentation
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{future::Future, io};

use maincopy_shared::profile_api::{
    ActiveTipRecipientResponse, PutActiveTipRecipientRequest, UpdateUserProfileRequest,
    UserProfileResponse,
};
use serde_json::json;
use uuid::Uuid;

use super::CliError;
use crate::{
    client::AdminClientError,
    models::{ProfileInvocation, TipRecipientInvocation},
};

pub(super) enum ProfileOutput {
    Profile(Option<UserProfileResponse>),
    ProfileChanged {
        idempotency_key: Uuid,
        profile: UserProfileResponse,
    },
    Recipient(ActiveTipRecipientResponse),
    RecipientChanged {
        idempotency_key: Uuid,
        recipient: ActiveTipRecipientResponse,
    },
}

pub(super) async fn execute<Show, ShowFuture, Save, SaveFuture>(
    command: ProfileInvocation,
    show: Show,
    save: Save,
) -> Result<ProfileOutput, CliError>
where
    Show: FnOnce() -> ShowFuture,
    ShowFuture: Future<Output = Result<Option<UserProfileResponse>, AdminClientError>>,
    Save: FnOnce(Uuid, UpdateUserProfileRequest) -> SaveFuture,
    SaveFuture: Future<Output = Result<UserProfileResponse, AdminClientError>>,
{
    let (idempotency_key, request) = match command {
        ProfileInvocation::Show => return Ok(ProfileOutput::Profile(show().await?)),
        ProfileInvocation::Change {
            idempotency_key,
            request,
        } => (idempotency_key, request),
    };
    let profile =
        save(idempotency_key, request)
            .await
            .map_err(|source| CliError::ProfileChange {
                idempotency_key,
                source,
            })?;
    Ok(ProfileOutput::ProfileChanged {
        idempotency_key,
        profile,
    })
}

pub(super) async fn execute_recipient<Show, ShowFuture, Save, SaveFuture>(
    command: TipRecipientInvocation,
    show: Show,
    save: Save,
) -> Result<ProfileOutput, CliError>
where
    Show: FnOnce() -> ShowFuture,
    ShowFuture: Future<Output = Result<ActiveTipRecipientResponse, AdminClientError>>,
    Save: FnOnce(Uuid, PutActiveTipRecipientRequest) -> SaveFuture,
    SaveFuture: Future<Output = Result<ActiveTipRecipientResponse, AdminClientError>>,
{
    let (idempotency_key, request) = match command {
        TipRecipientInvocation::Show => {
            return Ok(ProfileOutput::Recipient(show().await?));
        }
        TipRecipientInvocation::Change {
            idempotency_key,
            request,
        } => (idempotency_key, request),
    };
    let recipient =
        save(idempotency_key, request)
            .await
            .map_err(|source| CliError::ProfileChange {
                idempotency_key,
                source,
            })?;
    Ok(ProfileOutput::RecipientChanged {
        idempotency_key,
        recipient,
    })
}

pub(super) fn write_output(
    mut output: impl io::Write,
    result: ProfileOutput,
    json_output: bool,
) -> Result<(), CliError> {
    if json_output {
        let value = match result {
            ProfileOutput::Profile(profile) => json!({"profile": profile}),
            ProfileOutput::ProfileChanged {
                idempotency_key,
                profile,
            } => json!({"idempotency_key": idempotency_key, "profile": profile}),
            ProfileOutput::Recipient(recipient) => json!({"tip_recipient": recipient}),
            ProfileOutput::RecipientChanged {
                idempotency_key,
                recipient,
            } => json!({"idempotency_key": idempotency_key, "tip_recipient": recipient}),
        };
        writeln!(output, "{value}")?;
        return Ok(());
    }
    match result {
        ProfileOutput::Profile(profile) => write_profile(&mut output, profile.as_ref())?,
        ProfileOutput::ProfileChanged {
            idempotency_key,
            profile,
        } => {
            writeln!(output, "Accepted profile change: {idempotency_key}")?;
            write_profile(&mut output, Some(&profile))?;
            writeln!(output, "Inspect current state: maincopy profile show")?;
        }
        ProfileOutput::Recipient(recipient) => write_recipient(&mut output, &recipient)?,
        ProfileOutput::RecipientChanged {
            idempotency_key,
            recipient,
        } => {
            writeln!(output, "Accepted recipient change: {idempotency_key}")?;
            write_recipient(&mut output, &recipient)?;
            writeln!(output, "Inspect current state: maincopy tip-recipient show")?;
        }
    }
    Ok(())
}

fn write_profile(
    mut output: impl io::Write,
    profile: Option<&UserProfileResponse>,
) -> io::Result<()> {
    let Some(profile) = profile else {
        return writeln!(
            output,
            "Profile is not configured. Use maincopy profile create."
        );
    };
    writeln!(output, "User: {}", profile.user_id)?;
    writeln!(output, "Profile version: {}", profile.version.into_u64())?;
    writeln!(
        output,
        "Display name: {}",
        profile
            .display_name
            .as_ref()
            .map_or("(unset)", |name| name.as_str())
    )?;
    writeln!(
        output,
        "Lightning Address: {}",
        profile
            .lightning_address
            .as_ref()
            .map_or("(unset)", |address| address.as_str())
    )?;
    writeln!(output, "Tips enabled: {}", profile.tips_enabled)
}

fn write_recipient(
    mut output: impl io::Write,
    recipient: &ActiveTipRecipientResponse,
) -> io::Result<()> {
    writeln!(
        output,
        "Recipient setting version: {}",
        recipient.version.into_u64()
    )?;
    match recipient.user_id {
        Some(user_id) => {
            writeln!(output, "Selected user: {user_id}")?;
            writeln!(
                output,
                "Tip links require an enabled account, tips enabled, and a valid Lightning Address."
            )
        }
        None => writeln!(
            output,
            "No active recipient. Articles remain readable without tip links."
        ),
    }
}

#[cfg(test)]
mod tests {
    use maincopy_shared::profile::ProfileVersion;
    use std::{cell::Cell, future::ready};

    use super::*;
    use crate::{
        client::{AdminClientError, AdminProblem},
        startup::{error_exit, write_error},
    };
    use reqwest::StatusCode;

    fn profile() -> UserProfileResponse {
        serde_json::from_value(json!({"user_id":Uuid::from_u128(1), "display_name":"Alice", "lightning_address":"alice@example.test", "tips_enabled":true, "version":2, "updated_at":"2026-09-05T12:00:00Z"})).unwrap()
    }

    fn recipient(selected: bool) -> ActiveTipRecipientResponse {
        serde_json::from_value(json!({"user_id":selected.then_some(Uuid::from_u128(1)), "version":3, "updated_at":"2026-09-05T12:00:00Z"})).unwrap()
    }

    #[tokio::test]
    async fn profile_reads_never_submit_a_mutation() {
        let saved = Cell::new(false);
        let result = execute(
            ProfileInvocation::Show,
            || ready(Ok(None)),
            |_, _| {
                saved.set(true);
                ready(Ok(profile()))
            },
        )
        .await
        .unwrap();
        assert!(matches!(result, ProfileOutput::Profile(None)));
        assert!(!saved.get());
        let result = execute_recipient(
            TipRecipientInvocation::Show,
            || ready(Ok(recipient(false))),
            |_, _| {
                saved.set(true);
                ready(Ok(recipient(true)))
            },
        )
        .await
        .unwrap();
        assert!(matches!(result, ProfileOutput::Recipient(value) if value.user_id.is_none()));
        assert!(!saved.get());
    }

    #[tokio::test]
    async fn profile_mutations_submit_the_prepared_command_and_preserve_uncertain_outcomes() {
        for succeeded in [true, false] {
            let key = Uuid::new_v4();
            let loaded = Cell::new(false);
            let submitted = Cell::new(false);
            let command = ProfileInvocation::Change {
                idempotency_key: key,
                request: UpdateUserProfileRequest {
                    expected_version: Some(ProfileVersion::new(1).unwrap()),
                    display_name: Some("Alice".parse().unwrap()),
                    lightning_address: Some("alice@example.test".parse().unwrap()),
                    tips_enabled: true,
                },
            };
            let result = execute(command,
                || { loaded.set(true); ready(Ok(None)) },
                |operation, request| {
                    submitted.set(true);
                    assert_eq!(operation, key);
                    assert_eq!(serde_json::to_value(request).unwrap(), json!({"expected_version":1, "display_name":"Alice", "lightning_address":"alice@example.test", "tips_enabled":true}));
                    ready(if succeeded { Ok(profile()) } else { Err(AdminClientError::HumanCredentialsMissing) })
                },
            ).await;
            assert!(!loaded.get());
            assert!(submitted.get());
            match result {
                Ok(ProfileOutput::ProfileChanged {
                    idempotency_key,
                    profile: value,
                }) => {
                    assert!(succeeded);
                    assert_eq!(idempotency_key, key);
                    assert_eq!(value, profile());
                }
                Err(CliError::ProfileChange {
                    idempotency_key,
                    source: AdminClientError::HumanCredentialsMissing,
                }) => {
                    assert!(!succeeded);
                    assert_eq!(idempotency_key, key);
                }
                _ => panic!("unexpected mutation result"),
            }
        }
    }

    #[tokio::test]
    async fn recipient_mutations_submit_the_selected_state_and_preserve_retry_identity() {
        for succeeded in [true, false] {
            let key = Uuid::new_v4();
            let loaded = Cell::new(false);
            let submitted = Cell::new(false);
            let command = TipRecipientInvocation::Change {
                idempotency_key: key,
                request: PutActiveTipRecipientRequest {
                    expected_version: ProfileVersion::new(2).unwrap(),
                    user_id: None,
                },
            };
            let result = execute_recipient(
                command,
                || {
                    loaded.set(true);
                    ready(Ok(recipient(true)))
                },
                |operation, request| {
                    submitted.set(true);
                    assert_eq!(operation, key);
                    assert_eq!(
                        serde_json::to_value(request).unwrap(),
                        json!({"user_id":null, "expected_version":2})
                    );
                    ready(if succeeded {
                        Ok(recipient(false))
                    } else {
                        Err(AdminClientError::HumanCredentialsMissing)
                    })
                },
            )
            .await;
            assert!(!loaded.get());
            assert!(submitted.get());
            match result {
                Ok(ProfileOutput::RecipientChanged {
                    idempotency_key,
                    recipient: value,
                }) => {
                    assert!(succeeded);
                    assert_eq!(idempotency_key, key);
                    assert_eq!(value, recipient(false));
                }
                Err(CliError::ProfileChange {
                    idempotency_key,
                    source: AdminClientError::HumanCredentialsMissing,
                }) => {
                    assert!(!succeeded);
                    assert_eq!(idempotency_key, key);
                }
                _ => panic!("unexpected mutation result"),
            }
        }
    }

    #[test]
    fn profile_output_distinguishes_unconfigured_current_and_accepted_state() {
        for json_output in [false, true] {
            for (result, expected) in [
                (
                    ProfileOutput::Profile(None),
                    if json_output {
                        "\"profile\":null"
                    } else {
                        "not configured"
                    },
                ),
                (ProfileOutput::Profile(Some(profile())), "Alice"),
                (
                    ProfileOutput::ProfileChanged {
                        idempotency_key: Uuid::nil(),
                        profile: profile(),
                    },
                    "00000000-0000-0000-0000-000000000000",
                ),
                (
                    ProfileOutput::Recipient(recipient(false)),
                    if json_output {
                        "\"user_id\":null"
                    } else {
                        "No active recipient"
                    },
                ),
                (
                    ProfileOutput::RecipientChanged {
                        idempotency_key: Uuid::nil(),
                        recipient: recipient(true),
                    },
                    "00000000-0000-0000-0000-000000000000",
                ),
            ] {
                let mut output = Vec::new();
                write_output(&mut output, result, json_output).unwrap();
                let output = String::from_utf8(output).unwrap();
                assert!(output.contains(expected), "{output}");
                if json_output {
                    assert!(serde_json::from_str::<serde_json::Value>(&output).is_ok());
                }
            }
        }
    }

    #[test]
    fn failed_profile_changes_preserve_retry_identity_and_error_category() {
        for (status, expected_exit) in [
            (StatusCode::BAD_REQUEST, 65),
            (StatusCode::FORBIDDEN, 77),
            (StatusCode::PRECONDITION_FAILED, 75),
            (StatusCode::SERVICE_UNAVAILABLE, 69),
        ] {
            let operation = Uuid::new_v4();
            let error = CliError::ProfileChange {
                idempotency_key: operation,
                source: AdminClientError::HttpStatus {
                    status,
                    problem: Some(AdminProblem {
                        code: "profile_error".into(),
                        message: "safe failure".into(),
                    }),
                    request_id: Some(Uuid::nil()),
                },
            };
            assert_eq!(error_exit(&error), expected_exit);
            for json_output in [false, true] {
                let mut output = Vec::new();
                write_error(&mut output, &error, expected_exit, json_output).unwrap();
                let output = String::from_utf8(output).unwrap();
                assert!(output.contains(&operation.to_string()));
                assert!(output.contains("safe failure"));
                if json_output {
                    assert!(serde_json::from_str::<serde_json::Value>(&output).is_ok());
                }
            }
        }
    }
}