Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,14 +204,14 @@ history. Aborts if the destination already has a drive with the same slug.
| `switchboard docs list [--drive <slug>]` | List documents (all drives, or filtered by `--drive`; add `--type` to filter) |
| `switchboard docs get <id-or-name> [--drive <slug>] [--state] [--out <file>]` | Get document details (auto-detects drive; `--state` includes full state) |
| `switchboard docs tree [<slug>]` | Hierarchical folder/file view — all drives if no argument, single drive if slug given |
| `switchboard docs create` | Interactive creation with drive picker (or pass `--type`, `--name`, `--drive`) |
| `switchboard docs create [--parent-folder <id>]` | Interactive creation with drive picker (or pass `--type`, `--name`, `--drive`; `--parent-folder` places it inside a folder) |
| `switchboard docs delete <ids-or-names...>` | Delete one or more documents — batch API (use `-y` to skip confirmation) |
| `switchboard docs rename <id> <name>` | Rename a document |
| `switchboard docs parents <id>` | Show parent documents (reverse tree traversal) |
| `switchboard docs add-to <parent> <ids...>` | Add documents as children of a parent |
| `switchboard docs remove-from <parent> <ids...>` | Remove documents from a parent |
| `switchboard docs move <ids...> --from <src> --to <dst>` | Move documents between parents |
| `switchboard docs apply <id> --actions '<json>' [--file <file>] [--wait] [--allow-literal-escapes]` | Dispatch raw actions via `mutateDocument` — pass actions inline or from a file; `--wait` blocks until async completion. Refuses string fields containing a literal `\n`/`\t`/`\r` (a double-encoding bug that stores `\n` in note bodies) unless `--allow-literal-escapes` |
| `switchboard docs apply <id> --actions '<json>' [--file <file>] [--wait] [--allow-literal-escapes]` | Dispatch raw actions via `mutateDocument` — pass actions inline or from a file; `--wait` blocks until async completion and fails if any action was rejected. Refuses string fields containing a literal `\n`/`\t`/`\r` (a double-encoding bug that stores `\n` in note bodies) unless `--allow-literal-escapes` |
| `switchboard docs mutate <id-or-name> [--op <op>] [--input '<json>'] [--input-file <file>] [--drive <slug>] [--allow-literal-escapes]` | Interactive field-by-field editor — omit `--op` for operation picker; pass `--input` / `--input-file` for scripting. Same literal-escape guard as `apply` |

### Folders
Expand Down Expand Up @@ -272,8 +272,8 @@ All export commands support operation filters: `--action-types <types>` (comma-s
|---------|-------------|
| `switchboard watch docs [--type <type>] [--drive <id>] [--doc <id>] [--exec <cmd>]` | Stream document change events via WebSocket. Enriched output includes slug, timestamps, revisions, and context. `--exec` runs a command for each event with JSON on stdin and `$SWITCHBOARD_EVENT` set |
| `switchboard watch job <job-id>` | Stream job status updates |
| `switchboard jobs status <job-id>` | Get current job status with visual progression bar |
| `switchboard jobs wait <job-id> [--timeout <secs>]` | Block until a job completes via WebSocket subscription (no polling) |
| `switchboard jobs status <job-id>` | Get current job status with visual progression bar, and what became of each action the job was given |
| `switchboard jobs wait <job-id> [--timeout <secs>]` | Block until a job completes via WebSocket subscription (no polling). Exits non-zero, naming the action and the reason, when the job's actions did not all apply |
| `switchboard jobs watch <job-id>` | Stream job status updates via WebSocket with visual progression bar |
| `switchboard sync touch <input>` | Create/update a sync channel |
| `switchboard sync push <envelopes>` | Push sync envelopes |
Expand Down
29 changes: 28 additions & 1 deletion specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ Maps to GraphQL:
switchboard docs list [--drive <slug>] [--type <type>] # Also supports --format svg/png/mermaid --out <file>
switchboard docs get <id-or-name> [--drive <slug>] [--state] [--out <file>]
switchboard docs tree [<slug>]
switchboard docs create [--type <type>] [--name <name>] [--drive <slug>]
switchboard docs create [--type <type>] [--name <name>] [--drive <slug>] [--parent-folder <id>]
switchboard docs delete <ids-or-names...> [-y]
switchboard docs rename <id-or-name> <new-name>
switchboard docs parents <id-or-name>
Expand Down Expand Up @@ -890,6 +890,27 @@ switchboard jobs watch <job-id> # Stream updates vi

For long-running mutations dispatched via `mutateDocumentAsync` (e.g., `docs apply`).

**Per-action outcomes.** A reducer error or a permission denial does not fail the
job — the operation is written anyway and the job still reaches `READ_READY`. The
job's `result` reports what became of each submitted action, so `jobs status` and
`jobs wait` name the ones that did not apply:

```
$ switchboard jobs wait abc123
Job abc123 finished: READ_READY (1/2 applied)
✗ a2 [global#5]: reducer error: name is required
```

`jobs wait` (and therefore `docs apply --wait`) exits 1 in that case. `jobs status`
only reports, and exits 0. `--format json` prints the job object as the server sent
it, `result` included — nothing is reshaped. A server that does not report
per-action outcomes prints the plain status line and exits as before.

The tally counts the actions that produced an operation — an action that produced
none has no entry to report. So the server's own `allApplied` can say the batch fell
short while every action it detailed applied; `jobs wait` says exactly that and still
exits 1, rather than inventing a count of actions it cannot name.

---

### 14. Sync Channels
Expand Down Expand Up @@ -1217,6 +1238,12 @@ $ switchboard docs get Acaldas --drive builders --state --format json | jq '.sta
$ switchboard docs create --type powerhouse/invoice --name "Q1 Invoice" --drive my-drive --format json
[{"id": "41d2cae7-...", "name": "Q1 Invoice", ...}]

# Create inside a folder (created at the root, then moved). A failed move
# exits non-zero but still prints the id, so a script never loses it:
$ switchboard docs create --type powerhouse/invoice --name "Q1 Invoice" \
--drive my-drive --parent-folder 8f21c0de-... --format json
{"id": "41d2cae7-...", "folderMoveFailed": "..."}

# Mutate a document
$ switchboard docs mutate 41d2cae7-... --op editInvoice --input '{"amount": 2000}' --format json

Expand Down
145 changes: 139 additions & 6 deletions src/cli/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,65 @@ pub fn print_tree(nodes: &[Value], parent: Option<&str>, indent: &str) {
}
}

/// Bounded: the server has just failed to answer within its full request
/// timeout, and this hint only decorates a message printed either way.
const CREATE_HINT_LOOKUP: std::time::Duration = std::time::Duration::from_secs(10);

/// Guidance for a `createDocument` timeout: the request reached the server,
/// so the document may exist. A name match is never reported as proof — the
/// drive may simply have held one already.
async fn timed_out_create_hint(
client: &crate::graphql::GraphQLClient,
drive_id: &str,
name: &str,
parent_folder: Option<&str>,
) -> String {
let at_root = tokio::time::timeout(CREATE_HINT_LOOKUP, fetch_drive_nodes(client, drive_id))
.await
.ok()
.and_then(|fetched| fetched.ok())
.and_then(|(_, _, nodes)| root_document_named(&nodes, name));

match at_root {
Some(doc_id) => {
let placement = match parent_folder {
Some(folder) => format!(
" It is at the drive root, not in folder {folder}; if it is the one just \
created, place it with \
`switchboard docs move {doc_id} --from {drive_id} --to {folder}`."
),
None => String::new(),
};
format!(
"The create may well have taken effect: drive {drive_id} holds a document \
named \"{name}\" at its root (id {doc_id}).{placement} Check that document \
before re-running `docs create` — if it is the one just created, re-running \
makes a duplicate."
)
}
None => format!(
"The create may still have been applied. Check drive {drive_id} for a document \
named \"{name}\" (`switchboard docs list --drive {drive_id}`) before re-running \
`docs create`, or you will end up with a duplicate."
),
}
}

/// Root only: `createDocument` lands the document there, and the
/// `--parent-folder` move has not run yet.
fn root_document_named(nodes: &[Value], name: &str) -> Option<String> {
nodes
.iter()
.find(|n| {
n["kind"].as_str() == Some("file")
&& matches!(n["parentFolder"].as_str(), None | Some(""))
&& n["name"]
.as_str()
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))
})
.and_then(|n| n["id"].as_str().map(|id| id.to_string()))
}

async fn create(
doc_type: Option<String>,
name: Option<String>,
Expand Down Expand Up @@ -1058,13 +1117,10 @@ async fn create(
// namespaced createDocument mutation that atomically adds the doc to the drive.
let namespace = cache.find_model(&doc_type).map(|m| m.namespace.clone());

let mut vars = serde_json::json!({
let vars = serde_json::json!({
"name": name,
"parentIdentifier": drive_id,
});
if let Some(ref folder_id) = parent_folder {
vars["slug"] = serde_json::json!(folder_id); // parentFolder not directly supported
}

let ns = match &namespace {
Some(ns) if !ns.is_empty() => ns.clone(),
Expand All @@ -1079,7 +1135,17 @@ async fn create(
ns,
);

let create_data = client.query(&mutation, Some(&vars)).await?;
// A read timeout does not mean the create failed; re-running it is what
// produces the duplicate "(copy) 1" documents.
let create_data = match client.query(&mutation, Some(&vars)).await {
Ok(data) => data,
Err(e) if crate::graphql::is_timeout_error(&e) => {
let hint =
timed_out_create_hint(&client, &drive_id, &name, parent_folder.as_deref()).await;
return Err(e.context(hint));
}
Err(e) => return Err(e),
};

let doc_id = create_data
.get(ns.as_str())
Expand All @@ -1098,7 +1164,34 @@ async fn create(
"targetParentFolder": folder_id,
}
});
let _ = client.query(move_mutation, Some(&move_vars)).await;
if let Err(e) = client.query(move_mutation, Some(&move_vars)).await {
let placement = if crate::graphql::is_timeout_error(&e) {
format!(
"the move may or may not have taken effect — check whether it is in folder \
{folder_id} or still at the root of drive {drive_id}, and if it is at the \
root, place it with \
`switchboard docs move {doc_id} --from {drive_id} --to {folder_id}`"
)
} else {
format!(
"it is sitting at the root of drive {drive_id}. Place it with \
`switchboard docs move {doc_id} --from {drive_id} --to {folder_id}`"
)
};
// Returning Err skips the JSON print below, leaving a script no
// way to recover the id of a document that does exist.
if matches!(format, OutputFormat::Json | OutputFormat::Raw) {
print_json(&serde_json::json!({
"id": doc_id,
"folderMoveFailed": format!("{e:#}"),
}));
}
return Err(e.context(format!(
"Document \"{name}\" was created (id {doc_id}) but could not be moved into \
folder {folder_id} — {placement}; do NOT re-run `docs create`, that makes a \
duplicate."
)));
}
}

let data = serde_json::json!({ "id": doc_id });
Expand Down Expand Up @@ -2087,6 +2180,46 @@ fn days_to_ymd(days: u64) -> (u64, u64, u64) {
(y, m, d)
}

#[cfg(test)]
mod create_recovery_tests {
use super::*;
use serde_json::json;

#[test]
fn only_the_drive_root_is_a_candidate() {
let nodes = vec![
json!({ "id": "folder-1", "kind": "folder", "name": "Invoices" }),
json!({ "id": "nested", "kind": "file", "name": "Q1 Invoice",
"parentFolder": "folder-1" }),
];
assert_eq!(root_document_named(&nodes, "Q1 Invoice"), None);

let mut with_root = nodes.clone();
with_root.push(
json!({ "id": "root-doc", "kind": "file", "name": "q1 invoice",
"parentFolder": null }),
);
assert_eq!(
root_document_named(&with_root, "Q1 Invoice"),
Some("root-doc".to_string())
);
}

#[test]
fn an_empty_parent_is_the_root_and_a_folder_is_never_a_match() {
let empty_parent = vec![json!({ "id": "d", "kind": "file", "name": "Notes",
"parentFolder": "" })];
assert_eq!(
root_document_named(&empty_parent, "Notes"),
Some("d".to_string())
);

let folder = vec![json!({ "id": "f", "kind": "folder", "name": "Notes",
"parentFolder": null })];
assert_eq!(root_document_named(&folder, "Notes"), None);
}
}

#[cfg(test)]
mod relationship_tests {
use super::*;
Expand Down
20 changes: 20 additions & 0 deletions src/cli/guide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ COMMANDS
Hierarchical folder/file view
switchboard docs create Interactive document creation
switchboard docs create --type <type> --name <name> --drive <slug>
[--parent-folder <folder-id>]
Scripted creation
switchboard docs delete <ids...> [-y] Delete one or more documents (batch)
switchboard docs rename <id> <name> Rename a document
Expand Down Expand Up @@ -573,6 +574,25 @@ WEBSOCKET-BASED WAITING
real-time status updates, completing as soon as the job finishes.
This is more efficient and responsive than periodic polling.

ACTION OUTCOMES

A reducer error or a permission denial does not fail the job: the
operation is still written and the job still reaches READ_READY. So
`jobs status` and `jobs wait` report what became of each action the
job was given, and `jobs wait` exits non-zero when they did not all
apply:

Job abc123 finished: READ_READY (1/2 applied)
✗ a2 [global#5]: reducer error: name is required

The tally counts the actions that produced an operation. An action
that produced none has no entry, so a server can report the batch as
incomplete while every action it detailed applied — `jobs wait` says
so and still exits non-zero.

Servers that do not report per-action outcomes print the plain
status line, unchanged.

STATUS PROGRESSION

`jobs status`, `jobs watch`, and `jobs wait` display a visual
Expand Down
Loading
Loading