onetaskgraph-core 0.2.58

The onetaskgraph engine: the plugin registry, global-id qualification, and the plan every response carries.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! The envelopes and parameter shapes of `docs/plugin-protocol.md`.
//!
//! Every type here is a restatement of that document, and every *work* type inside one
//! comes from `onetaskgraph-plugin-api` unchanged — the protocol says the JSON shape of a
//! contract type "is what `onetaskgraph schema` emits for the type of the same name", so
//! re-spelling `Task` or `Capabilities` here would create a second place the contract
//! lives and a way for the two to disagree. What this module adds is only what the
//! contract has no type for: the envelope, the handshake, and the per-method wrappers.
//!
//! Nothing here uses `deny_unknown_fields`, and that is §2.1 rather than an oversight: a
//! reader on either side ignores members it does not know, which is what lets a later
//! version add an optional field without a version bump.

use std::collections::BTreeMap;
use std::path::Path;

use onetaskgraph_plugin_api::{
    Capabilities, Comment, CommentBody, Direction, Document, DocumentQuery, ItemWrite, MetadataKey,
    Metering, NativeId, NewComment, Page, PageRequest, Priority, Project, ProjectQuery,
    SourceError, Status, StatusCategory, Task, TaskQuery, TaskRef, TaskUpdate, TaskUpdateOutcome,
    WriteSupport,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// The protocol version this build speaks. `docs/plugin-protocol.md` specifies 2.
///
/// Version 2 added `delete_task` and `delete_project` (§4.10). The handshake matches
/// versions exactly, so a plugin speaking 1 is refused by name rather than being asked
/// for a method it has never heard of halfway through undoing a copy.
pub(crate) const PROTOCOL_VERSION: u32 = 2;

/// Every status category this build knows, in the order the vocabulary lists them (§3.5).
pub(crate) const STATUS_VOCABULARY: [StatusCategory; 8] = [
    StatusCategory::Draft,
    StatusCategory::Backlog,
    StatusCategory::Todo,
    StatusCategory::Queued,
    StatusCategory::InProgress,
    StatusCategory::Done,
    StatusCategory::Cancelled,
    StatusCategory::Unknown,
];

/// Whether `category` is one a peer that lists no statuses was not written against (§3.5).
///
/// A wildcard-free match, so a category added to the vocabulary does not compile until
/// somebody decides here whether a peer that predates it can be handed it.
pub(crate) const fn after_the_first_vocabulary(category: StatusCategory) -> bool {
    match category {
        StatusCategory::Queued => true,
        StatusCategory::Draft
        | StatusCategory::Backlog
        | StatusCategory::Todo
        | StatusCategory::InProgress
        | StatusCategory::Done
        | StatusCategory::Cancelled
        | StatusCategory::Unknown => false,
    }
}

/// One category as the wire spells it.
pub(crate) fn spelled(category: StatusCategory) -> String {
    serde_json::to_value(category)
        .ok()
        .and_then(|word| word.as_str().map(str::to_owned))
        .expect("a status category serialises as its own word")
}

/// Every category this build knows, as a handshake lists them.
pub(crate) fn vocabulary() -> Vec<String> {
    STATUS_VOCABULARY.into_iter().map(spelled).collect()
}

/// Whether a handshake's `statuses` member lists every category this build knows.
///
/// An absent member is the first vocabulary, so it lists none of the categories added
/// after it.
pub(crate) fn knows_every_category(statuses: Option<&[String]>) -> bool {
    let Some(listed) = statuses else {
        return false;
    };
    STATUS_VOCABULARY
        .into_iter()
        .filter(|category| after_the_first_vocabulary(*category))
        .all(|category| listed.contains(&spelled(category)))
}

/// One request line: `{ "id": …, "method": …, "params": … }` (§2).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Request {
    /// Unique within the connection, echoed in the response.
    pub(crate) id: String,
    /// One of the names in §4, or `initialize`.
    pub(crate) method: String,
    /// Present even when empty, which is why it is not `Option`.
    pub(crate) params: Value,
}

/// One response line: an `id` and exactly one of `result` and `error` (§2).
///
/// Both members are optional here so that "both present" and "neither present" are
/// *representable* — they are the protocol violations §6.3 names, and a shape that could
/// not hold them would turn a violation into a parse error that says something else.
/// [`Response::outcome`] is where the pair is reduced to the one thing it may be.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Response {
    /// The request's `id`, echoed.
    pub(crate) id: String,
    /// Present on success.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) result: Option<Value>,
    /// Present on failure.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) error: Option<SourceError>,
}

impl Response {
    /// A response carrying a result.
    pub(crate) fn ok(id: String, result: Value) -> Self {
        Self {
            id,
            result: Some(result),
            error: None,
        }
    }

    /// A response carrying a failure.
    pub(crate) fn failed(id: String, error: SourceError) -> Self {
        Self {
            id,
            result: None,
            error: Some(error),
        }
    }

    /// The one thing this envelope may say, or `None` when it says both or neither.
    ///
    /// Returning `None` rather than a guess is §6.3: an envelope with both members is a
    /// protocol violation, and picking one of them would run the caller against a shape
    /// the peer did not mean.
    pub(crate) fn outcome(self) -> Option<Result<Value, SourceError>> {
        match (self.result, self.error) {
            (Some(result), None) => Some(Ok(result)),
            (None, Some(error)) => Some(Err(error)),
            _ => None,
        }
    }
}

/// `initialize` parameters (§3).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct InitializeParams {
    /// The version the engine is speaking.
    pub(crate) protocol_version: u32,
    /// For the plugin's diagnostics only.
    pub(crate) engine: EngineIdentity,
    /// The configured name — for error messages, and for recognising itself in a
    /// recorded qualified id (§3.2).
    pub(crate) source_name: String,
    /// This source's settings, verbatim.
    pub(crate) config: Value,
    /// Only the variables this plugin's configuration names (§3.1).
    pub(crate) secrets: BTreeMap<String, String>,
    /// The status categories this engine knows (§3.5).
    ///
    /// Optional, and absent means the first vocabulary: an engine written before `queued`
    /// sends none, and a plugin answering it reports a category outside that vocabulary as
    /// `unknown`, keeping its name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) statuses: Option<Vec<String>>,
    /// The absolute directory holding the configuration document that supplied this
    /// source's block (§3).
    ///
    /// Optional, and absent when the block came from no one document — the environment
    /// layer or a flag — in which case a relative path the plugin declares keeps resolving
    /// against the working directory. A plugin written before the member ignores it (§2.1)
    /// and behaves exactly as it did.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) document_dir: Option<DocumentDir>,
}

/// `document_dir` (§3.8): an absolute directory whose name is a string.
///
/// Checked wherever one is made — by the engine from the configuration layer, and by the
/// reference host from the wire — so a relative one cannot be sent or measured from. A
/// relative directory would be measured from the child's working directory, which is the
/// very answer the member exists to replace.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub(crate) struct DocumentDir(String);

impl DocumentDir {
    /// `directory`, or why it cannot be sent as one.
    pub(crate) fn new(directory: &Path) -> Result<Self, String> {
        let spelled = directory.to_str().ok_or_else(|| {
            format!(
                "the document directory {} is not valid UTF-8, so it cannot be written into \
                 the handshake",
                directory.display()
            )
        })?;
        if !directory.is_absolute() {
            return Err(format!(
                "the document directory {spelled:?} is not an absolute path, so there is no \
                 one directory to measure this source's relative paths from"
            ));
        }
        Ok(Self(spelled.to_owned()))
    }

    /// The directory itself.
    pub(crate) fn as_path(&self) -> &Path {
        Path::new(&self.0)
    }
}

impl TryFrom<String> for DocumentDir {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(Path::new(&value))
    }
}

impl From<DocumentDir> for String {
    fn from(value: DocumentDir) -> Self {
        value.0
    }
}

/// Who is asking, for the plugin's diagnostics (§3).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EngineIdentity {
    /// The engine's name.
    pub(crate) name: String,
    /// The engine's own version. Advisory.
    pub(crate) version: String,
}

/// The `initialize` result (§3).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct InitializeResult {
    /// The version the plugin will speak.
    ///
    /// Optional so that an omitted one is a refusal this engine can *name* — §6.2 makes
    /// omitting it and answering in another version the same failure, and a required
    /// field would surface it as a parse error naming neither version.
    #[serde(default)]
    pub(crate) protocol_version: Option<u32>,
    /// The plugin kind, as the plugin reports it.
    pub(crate) kind: HandshakePluginKind,
    /// Read once; the engine does not ask again.
    pub(crate) capabilities: Capabilities,
    /// Whether this plugin can be written through (§3.3).
    ///
    /// Optional, and absent means [`WriteSupport::Unsupported`]: §2.1 lets a later
    /// version add a member without a version bump, and a plugin written against version
    /// 1 before there was a write side says nothing here and is read as the read-only
    /// source it is.
    #[serde(default)]
    pub(crate) writes: Option<WriteSupport>,
    /// Whether this plugin answers `metering` (§3.4).
    ///
    /// Optional, and absent means it does not: a plugin written before there was metering
    /// says nothing here, is never sent the method, and is reported as not metering.
    #[serde(default)]
    pub(crate) meters: bool,
    /// The status categories this plugin knows (§3.5).
    ///
    /// Optional, and absent means the first vocabulary — the seven categories before
    /// `queued` — so a plugin written before there was a `queued` is never handed one.
    /// Strings rather than categories, so a plugin listing a category this engine has never
    /// heard of is read rather than refused.
    #[serde(default)]
    pub(crate) statuses: Option<Vec<String>>,
    /// Whether this plugin answers `set_task_status` and `set_delivered_by`, and holds a
    /// task's `delivers` and `delivered_by` (§3.6).
    ///
    /// Optional, and absent means it does not: such a plugin is never sent either method, and
    /// never handed a task carrying either list.
    #[serde(default)]
    pub(crate) task_updates: bool,
    /// Whether this plugin answers `set_task_metadata`, `set_project_metadata` and
    /// `set_document_metadata` (§3.7).
    ///
    /// Optional, and absent means it does not: such a plugin is never sent any of the three,
    /// and each is refused by name before anything is sent.
    #[serde(default)]
    pub(crate) metadata_updates: bool,
    /// Whether this plugin answers `set_task_content` (§3.9).
    ///
    /// Optional, and absent means it does not: such a plugin is never sent the method, and a
    /// content write naming it is refused by name before anything is sent.
    #[serde(default)]
    pub(crate) content_updates: bool,
    /// Whether this plugin answers `update_task` (§3.10).
    ///
    /// Optional, and absent means it does not: such a plugin is never sent the method, and a
    /// targeted update naming it is carried out through the reads and `write_task` it already
    /// answers — correct, and merely not minimal.
    #[serde(default)]
    pub(crate) targeted_updates: bool,
}

/// The `metering` result (§4.14).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct MeteringResult {
    /// The plugin's running totals, or `null` when it has none to give.
    #[serde(default)]
    pub(crate) metering: Option<Metering>,
}

/// A plugin's non-empty, open-vocabulary kind from the handshake.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub(crate) struct HandshakePluginKind(String);

impl HandshakePluginKind {
    /// Validate a kind at the process boundary.
    pub(crate) fn new(kind: impl Into<String>) -> Result<Self, &'static str> {
        let kind = kind.into();
        if kind.trim().is_empty() {
            Err("plugin kind must contain a non-whitespace character")
        } else {
            Ok(Self(kind))
        }
    }

    /// Recover the peer's spelling after it has been validated.
    pub(crate) fn into_string(self) -> String {
        self.0
    }
}

impl TryFrom<String> for HandshakePluginKind {
    type Error = &'static str;

    fn try_from(kind: String) -> Result<Self, Self::Error> {
        Self::new(kind)
    }
}

impl From<HandshakePluginKind> for String {
    fn from(kind: HandshakePluginKind) -> Self {
        kind.0
    }
}

/// `get_task` and `get_project` parameters (§4.4).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct IdParams {
    /// The source's own opaque id.
    pub(crate) id: NativeId,
}

/// The `get_task` result (§4.4): a task, or `null` when there is no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct TaskResult {
    /// The task, or `null`.
    #[serde(default)]
    pub(crate) task: Option<Task>,
}

/// The `get_project` result (§4.4).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ProjectResult {
    /// The project, or `null`.
    #[serde(default)]
    pub(crate) project: Option<Project>,
}

/// The `get_document` result (§4.11): a document, or `null` when there is no such one.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DocumentResult {
    /// The document, or `null`.
    #[serde(default)]
    pub(crate) document: Option<Document>,
}

/// `query_tasks` parameters (§4.5).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct TaskQueryParams {
    /// The predicates the plugin is being asked to apply.
    pub(crate) query: TaskQuery,
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// `query_projects` parameters (§4.6).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ProjectQueryParams {
    /// The predicates the plugin is being asked to apply.
    pub(crate) query: ProjectQuery,
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// `labels` parameters (§4.7).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct LabelParams {
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// `query_documents` parameters (§4.11).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DocumentQueryParams {
    /// The predicates the plugin is being asked to apply.
    pub(crate) query: DocumentQuery,
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// `task_dependencies` and `project_dependencies` parameters (§4.8).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DependencyParams {
    /// The item whose edges are wanted.
    pub(crate) id: NativeId,
    /// Which way to walk.
    pub(crate) direction: Direction,
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// `write_task` parameters (§4.9).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct TaskWriteParams {
    /// The item to create or update, and what to write into it.
    pub(crate) write: ItemWrite<Task>,
}

/// `write_project` parameters (§4.9).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ProjectWriteParams {
    /// The item to create or update, and what to write into it.
    pub(crate) write: ItemWrite<Project>,
}

/// `write_document` parameters (§4.12).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DocumentWriteParams {
    /// The document to create or update, and what to write into it.
    pub(crate) write: ItemWrite<Document>,
}

/// `delete_task`, `delete_project` and `delete_document` parameters (§4.10, §4.12).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeleteParams {
    /// The destination item to remove.
    pub(crate) id: NativeId,
}

/// `task_comments` parameters (§4.15).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CommentsParams {
    /// The task whose comments are wanted.
    pub(crate) task: NativeId,
    /// Where to resume and how much to return.
    pub(crate) page: PageRequest,
}

/// The `task_comments` result (§4.15): a page, or `null` when there is no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CommentsResult {
    /// The page, or `null`.
    #[serde(default)]
    pub(crate) page: Option<Page<Comment>>,
}

/// `add_comment` parameters (§4.16).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct AddCommentParams {
    /// The task to comment on.
    pub(crate) task: NativeId,
    /// What to add.
    pub(crate) comment: NewComment,
}

/// `edit_comment` parameters (§4.16).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EditCommentParams {
    /// The task the comment is on.
    pub(crate) task: NativeId,
    /// The comment to edit.
    pub(crate) comment: NativeId,
    /// Its new body.
    pub(crate) body: CommentBody,
}

/// `delete_comment` parameters (§4.16).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeleteCommentParams {
    /// The task the comment is on.
    pub(crate) task: NativeId,
    /// The comment to remove.
    pub(crate) comment: NativeId,
}

/// The `add_comment` and `edit_comment` result (§4.16): the comment as the source now holds
/// it, or `null` when there is no such task or no such comment on it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CommentResult {
    /// The comment, or `null`.
    #[serde(default)]
    pub(crate) comment: Option<Comment>,
}

/// The `delete_comment` result (§4.16): the id removed, or `null` when there was nothing
/// under it to remove.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeletedCommentResult {
    /// The removed comment's id, or `null`.
    #[serde(default)]
    pub(crate) deleted: Option<NativeId>,
}

/// `set_task_status` parameters (§4.17).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct StatusParams {
    /// The task whose status is set.
    pub(crate) id: NativeId,
    /// The category to set it to.
    pub(crate) category: StatusCategory,
}

/// The `set_task_status` result (§4.17): the status as the plugin now reads it, or `null`
/// when there is no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct StatusResult {
    /// The status, or `null`.
    #[serde(default)]
    pub(crate) status: Option<Status>,
}

/// `set_task_priority` parameters (§4.19).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct PriorityParams {
    /// The task whose priority is set.
    pub(crate) id: NativeId,
    /// The priority to set it to; `none` clears it.
    pub(crate) priority: Priority,
}

/// The `set_task_priority` result (§4.19): the priority as the plugin now reads it, or
/// `null` when there is no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct PriorityResult {
    /// The priority, or `null`. Required: an answer without the member says nothing about
    /// whether the task is there, so it is malformed rather than read as `null`.
    #[serde(deserialize_with = "present")]
    pub(crate) priority: Option<Priority>,
}

/// `set_task_content` parameters (§4.20).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ContentParams {
    /// The task whose content is replaced.
    pub(crate) id: NativeId,
    /// What it holds afterwards, byte for byte.
    pub(crate) content: String,
}

/// The `set_task_content` result (§4.20): the id of the task written, or `null` when there is
/// no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ContentResult {
    /// The task's id, or `null`. Required, for the reason [`PriorityResult::priority`] is.
    #[serde(deserialize_with = "present")]
    pub(crate) id: Option<NativeId>,
}

/// `update_task` parameters (§4.21).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct UpdateParams {
    /// The task updated.
    pub(crate) id: NativeId,
    /// Every field to write, and nothing else.
    pub(crate) update: TaskUpdate,
}

/// The `update_task` result (§4.21): what the update came to, or `null` when there is no such
/// task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct UpdateResult {
    /// The outcome, or `null`. Required, for the reason [`PriorityResult::priority`] is.
    #[serde(deserialize_with = "present")]
    pub(crate) outcome: Option<TaskUpdateOutcome>,
}

/// A member that may be `null` and may not be absent.
///
/// Serde reads an absent `Option` member as `None` of its own accord; naming a deserializer
/// takes that away, so an answer that leaves the member out is refused as the malformed
/// answer it is rather than read as one saying there is no such task.
fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    Option::<T>::deserialize(deserializer)
}

/// `set_delivered_by` parameters (§4.17).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeliveredByParams {
    /// The task whose list is replaced.
    pub(crate) id: NativeId,
    /// The whole list it holds afterwards.
    pub(crate) delivered_by: Vec<TaskRef>,
}

/// The `set_delivered_by` result (§4.17): the list the task now holds, or `null` when there
/// is no such task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct DeliveredByResult {
    /// The list, or `null`.
    #[serde(default)]
    pub(crate) delivered_by: Option<Vec<TaskRef>>,
}

/// `set_task_metadata`, `set_project_metadata` and `set_document_metadata` parameters
/// (§4.18).
///
/// Built only through [`MetadataParams::new`], which deserialization goes through too, so no
/// value of this type holds [`MetadataKey::COPIES_KEY`] with a value that is not links.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "UncheckedMetadataParams")]
pub(crate) struct MetadataParams {
    /// The record whose metadata key is set.
    id: NativeId,
    /// The key: a caller's own dotted key outside the `onetaskgraph.` namespace, or the one
    /// reserved key a copy records where an item landed under, [`MetadataKey::COPIES_KEY`].
    key: MetadataKey,
    /// The value to hold under it: any JSON, `null` included — and for
    /// [`MetadataKey::COPIES_KEY`], only an object of destination source names to qualified
    /// ids of that source.
    value: Value,
}

impl MetadataParams {
    /// One narrow metadata write, once its value is one its key may hold.
    ///
    /// # Errors
    ///
    /// Returns why, when `key` is [`MetadataKey::COPIES_KEY`] and `value` is not links.
    pub(crate) fn new(id: NativeId, key: MetadataKey, value: Value) -> Result<Self, String> {
        if key.is_copies()
            && let Some(malformed) = crate::engine::malformed_links(&value)
        {
            return Err(malformed);
        }
        Ok(Self { id, key, value })
    }

    /// The record whose metadata key is set.
    pub(crate) fn id(&self) -> &NativeId {
        &self.id
    }

    /// The key.
    pub(crate) fn key(&self) -> &MetadataKey {
        &self.key
    }

    /// The value to hold under it.
    pub(crate) fn value(&self) -> &Value {
        &self.value
    }
}

/// [`MetadataParams`] as they arrive, before the value of the one reserved key is checked.
#[derive(Deserialize)]
struct UncheckedMetadataParams {
    id: NativeId,
    #[serde(deserialize_with = "caller_or_copies")]
    key: MetadataKey,
    value: Value,
}

impl TryFrom<UncheckedMetadataParams> for MetadataParams {
    type Error = String;

    fn try_from(params: UncheckedMetadataParams) -> Result<Self, Self::Error> {
        Self::new(params.id, params.key, params.value)
    }
}

/// A narrow metadata write's key as §4.18 admits it: any key [`MetadataKey::new`] accepts,
/// and [`MetadataKey::COPIES_KEY`], which the engine alone sends and nothing a caller types
/// can name.
fn caller_or_copies<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<MetadataKey, D::Error> {
    let key = String::deserialize(deserializer)?;
    if key == MetadataKey::COPIES_KEY {
        return Ok(MetadataKey::copies());
    }
    MetadataKey::new(key).map_err(serde::de::Error::custom)
}

/// The result of any write method (§4.9, §4.12): the id the destination holds the item
/// under.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct WriteResult {
    /// The destination's own id for the item that was written.
    pub(crate) id: NativeId,
}