Skip to main content

dsp_cli/client/
mod.rs

1//! Client layer (3a of ADR-0008) — the `DspClient` trait and its HTTP impl.
2//!
3//! The trait is the primary test seam (T2 from ADR-0009): production wires
4//! up the HTTP impl, action tests wire up `MockDspClient`. Translation
5//! between DSP-API vocabulary (ontology, class, property) and dsp-cli
6//! vocabulary (data-model, resource-type, field) happens here and *only*
7//! here — see `docs/dev/domain-language.md`.
8
9mod builtins;
10pub mod http;
11pub(crate) mod jwt;
12
13pub(crate) use builtins::builtin_data_models;
14pub(crate) use builtins::builtin_resource_types;
15
16use std::collections::HashMap;
17
18use crate::diagnostic::Diagnostic;
19use crate::model::auth::LoginResponse;
20use crate::model::{
21    CreateDumpOutcome, DataModel, DataModelDetail, DataModelStructure, DumpTask, Project,
22    ProjectDetail, ProjectRef, ResourceDetail, ResourcePage, ResourceTypeDetail, Vocabulary,
23    VocabularyTree,
24};
25
26/// The `DspClient` trait. Methods are added as commands need them.
27pub trait DspClient {
28    /// Authenticate against the DSP-API at `server` with the given credentials.
29    ///
30    /// Returns a [`LoginResponse`] with the token, resolved user identity, and
31    /// optional expiry extracted from the JWT. The caller owns cache persistence.
32    fn login(&self, server: &str, user: &str, password: &str) -> Result<LoginResponse, Diagnostic>;
33
34    /// Resolve a project identifier (IRI, shortcode, or shortname) on `server`
35    /// to a [`ProjectRef`].
36    ///
37    /// `project` may be an HTTP(S) IRI, a 4-hex-digit shortcode, or a shortname.
38    /// The classifier logic (IRI vs shortcode vs shortname) and URL encoding live
39    /// in the HTTP impl. This endpoint is public — no bearer token required.
40    fn resolve_project(&self, server: &str, project: &str) -> Result<ProjectRef, Diagnostic>;
41
42    /// Trigger a new server-side project dump on `server` for the project
43    /// identified by `project_iri`.
44    ///
45    /// `project_iri` is URL-encoded inside the implementation before being
46    /// inserted into the request URL. `dump_id` values returned from this call
47    /// are URL-safe (base64url) and inserted verbatim in subsequent requests.
48    ///
49    /// Returns a [`CreateDumpOutcome`]:
50    /// - `Created(task)` — a fresh dump was triggered; `task.status` is `InProgress`.
51    /// - `Exists { id }` — the server reports an existing dump via a conflict response;
52    ///   `id` is the existing dump's server-assigned identifier, and the existing dump
53    ///   belongs to the same project that was requested. The action decides what to do
54    ///   with it (adopt / replace / error).
55    /// - `ExistsForOtherProject { id, project_iri }` — an existing dump belongs to a
56    ///   **different** project; the DSP-API holds one dump server-wide, and the slot is
57    ///   occupied by `project_iri`'s dump. The action must never silently use or destroy
58    ///   this dump on behalf of the requested project.
59    ///
60    /// Other error conditions (auth, not-found, network) propagate as `Err(Diagnostic)`.
61    fn create_project_dump(
62        &self,
63        server: &str,
64        project_iri: &str,
65        skip_assets: bool,
66        token: &str,
67    ) -> Result<CreateDumpOutcome, Diagnostic>;
68
69    /// Fetch the current status of an ongoing or completed project dump.
70    ///
71    /// `dump_id` is URL-safe (base64url) and inserted verbatim into the request
72    /// URL. `project_iri` is URL-encoded inside the implementation.
73    ///
74    /// Returns a [`DumpTask`] with the current `status`. The action poll loop
75    /// calls this repeatedly until the status is `Completed` or `Failed`.
76    fn get_project_dump_status(
77        &self,
78        server: &str,
79        project_iri: &str,
80        dump_id: &str,
81        token: &str,
82    ) -> Result<DumpTask, Diagnostic>;
83
84    /// Stream the completed dump archive into `dest`.
85    ///
86    /// `dump_id` is URL-safe and inserted verbatim. `project_iri` is URL-encoded
87    /// inside the implementation. The HTTP impl uses a client without a read
88    /// timeout (but retains the connect timeout) so large archives do not time out
89    /// mid-stream.
90    ///
91    /// Returns the number of bytes written on success. The action owns the output
92    /// filename — `Content-Disposition` from the server is intentionally ignored.
93    fn download_project_dump(
94        &self,
95        server: &str,
96        project_iri: &str,
97        dump_id: &str,
98        token: &str,
99        dest: &mut dyn std::io::Write,
100    ) -> Result<u64, Diagnostic>;
101
102    /// Delete the server-side dump identified by `dump_id`.
103    ///
104    /// `dump_id` is URL-safe and inserted verbatim. `project_iri` is URL-encoded
105    /// inside the implementation.
106    ///
107    /// Returns `Ok(())` on success. Fails with `Conflict` if the dump is still
108    /// being produced and cannot yet be deleted.
109    fn delete_project_dump(
110        &self,
111        server: &str,
112        project_iri: &str,
113        dump_id: &str,
114        token: &str,
115    ) -> Result<(), Diagnostic>;
116
117    /// List all projects on the server.
118    ///
119    /// Public endpoint; `token` is sent as a bearer when `Some` so an
120    /// authenticated caller sees their full set, but a missing token is not an
121    /// error. Returns projects in server order (the action layer sorts).
122    fn list_projects(&self, server: &str, token: Option<&str>) -> Result<Vec<Project>, Diagnostic>;
123
124    /// Fetch the full detail of a single project (for `project describe`).
125    ///
126    /// Auth is optional (project metadata is public, ADR-0007); a token is sent
127    /// when present, mirroring `list_projects`. `project` may be an IRI,
128    /// 4-hex-digit shortcode, or shortname — the classifier logic lives in the
129    /// HTTP impl.
130    fn describe_project(
131        &self,
132        server: &str,
133        project: &str,
134        token: Option<&str>,
135    ) -> Result<ProjectDetail, Diagnostic>;
136
137    /// List a project's own data-models (DSP-API "ontologies") via
138    /// `GET /v2/ontologies/metadata/{project_iri}`.
139    ///
140    /// `project_iri` must be a resolved project IRI (the action resolves the
141    /// user-supplied identifier via `resolve_project` first). Auth is optional
142    /// (the endpoint is public); `token` is sent as a bearer when `Some`. Returns
143    /// project data-models in server order (the action sorts). Platform built-ins
144    /// are NOT included here — the action appends them when `--include-builtins`
145    /// is set (see `builtin_data_models`).
146    fn list_data_models(
147        &self,
148        server: &str,
149        project_iri: &str,
150        token: Option<&str>,
151    ) -> Result<Vec<DataModel>, Diagnostic>;
152
153    /// Fetch a single data-model's full content and summarise its child
154    /// resource-types, via `GET /v2/ontologies/allentities/{data_model_iri}`.
155    ///
156    /// `data_model_iri` must be a resolved data-model IRI (the action resolves the
157    /// user-supplied name-or-IRI against the project's data-models first). Auth is
158    /// optional (the endpoint is public); `token` is sent as a bearer when `Some`.
159    /// Returns the data-model identity/label/last-modified plus its resource-types
160    /// (sorted by name). `allLanguages` is intentionally NOT requested, so labels
161    /// are plain strings.
162    fn describe_data_model(
163        &self,
164        server: &str,
165        data_model_iri: &str,
166        token: Option<&str>,
167    ) -> Result<DataModelDetail, Diagnostic>;
168
169    /// Fetch the full detail of a single resource-type within a data-model, via
170    /// `GET /v2/ontologies/allentities/{data_model_iri}`.
171    ///
172    /// Fetches the data-model's `allentities` response, finds the class whose
173    /// local name (case-insensitive) or full IRI matches `resource_type`, and
174    /// returns the full [`ResourceTypeDetail`] including all fields (project and
175    /// built-in), representation kind, and project superclasses. Cross-data-model
176    /// fields are resolved by fetching sibling ontologies as needed (Decision 9).
177    ///
178    /// Returns `Err(Diagnostic::NotFound(...))` when no class in the queried
179    /// ontology's `@graph` matches `resource_type`. The hint message referencing
180    /// `resource-type list` is the caller's responsibility (ADR-0001: the ACTION
181    /// layer owns the hint in dsp-cli vocabulary; the client owns the wire logic).
182    ///
183    /// Auth is optional; `token` is forwarded as a bearer when `Some`.
184    /// Mirrors the doc style of `describe_data_model`.
185    fn describe_resource_type(
186        &self,
187        server: &str,
188        data_model_iri: &str,
189        resource_type: &str,
190        token: Option<&str>,
191    ) -> Result<ResourceTypeDetail, Diagnostic>;
192
193    /// Fetch per-resource-class instance counts for a project, via
194    /// `GET {server}/v3/projects/{enc(project_iri)}/resourcesPerOntology`.
195    ///
196    /// The endpoint groups counts by ontology, but this method flattens the
197    /// response into a single `HashMap<String, u64>` keyed by full
198    /// resource-class IRI → its instance count (`itemCount`). Flat rather than
199    /// grouped because it serves two consumers: `resource-type list` filters
200    /// the map down to the target data-model's classes, and `resource-type
201    /// describe` picks out one entry.
202    ///
203    /// **Semantics — read carefully, this differs from [`Self::list_resources`]:**
204    /// `itemCount` counts **non-deleted** resources but is **NOT
205    /// permission-filtered** — it includes resources the caller may not be
206    /// allowed to see (a deliberate server-side performance tradeoff, since
207    /// computing exact per-caller visible counts would require evaluating
208    /// permissions over every instance). This is a different contract from
209    /// `list_resources`, which IS permission-filtered. Callers that surface
210    /// this count to a user must disclose that it may over-count relative to
211    /// what that user can actually see.
212    ///
213    /// Auth is optional (mirrors `list_data_models`); `token` is sent as a
214    /// bearer when `Some`, omitted when `None` (public endpoint).
215    ///
216    /// Status mapping:
217    /// - `200` → parse and flatten into the returned map.
218    /// - `404` → `Err(Diagnostic::NotFound(...))` (project not found).
219    /// - `401`/`403` and everything else → the shared `map_unexpected_status`
220    ///   mapping (401/403 already map to `AuthRequired` there; no bespoke arm
221    ///   needed here).
222    ///
223    /// NEVER log the token.
224    fn resource_counts(
225        &self,
226        server: &str,
227        project_iri: &str,
228        token: Option<&str>,
229    ) -> Result<HashMap<String, u64>, Diagnostic>;
230
231    /// Fetch the relation graph of a single data-model, via
232    /// `GET /v2/ontologies/allentities/{data_model_iri}`.
233    ///
234    /// Returns all directed edges (link relations and inheritance relations)
235    /// between resource-types in the data-model, sorted per D6 by
236    /// `(source, kind, field, target)`.
237    ///
238    /// Cross-data-model targets are tagged with `target_data_model =
239    /// Some(prefix)`. System targets (knora-api, knora-base, etc.) have
240    /// `target_data_model = None` and `is_builtin` set per the asymmetric rules
241    /// (see `Relation.is_builtin` docs). The action layer filters `is_builtin`
242    /// edges based on `--include-builtins`.
243    ///
244    /// Only one `allentities` request is made (no sibling fetch — v1 limitation).
245    /// Cross-data-model link fields whose property node is absent from this
246    /// data-model's graph are silently skipped.
247    ///
248    /// Auth is optional; `token` is forwarded as a bearer when `Some`.
249    fn data_model_structure(
250        &self,
251        server: &str,
252        data_model_iri: &str,
253        token: Option<&str>,
254    ) -> Result<DataModelStructure, Diagnostic>;
255
256    /// List resource instances of a given resource-type within a project.
257    ///
258    /// Issues `GET {server}/v2/resources` with:
259    /// - query param `resourceClass=<resource_type_iri>` (URL-encoded by reqwest;
260    ///   maps to the DSP-API `resourceClass` query parameter — wire name unchanged)
261    /// - query param `page=<page>` (zero-based)
262    /// - query param `schema=complex` (baked in — never a trait parameter, per D4;
263    ///   complex carries per-resource `creationDate`/`lastModificationDate`, which
264    ///   `simple` omits — the extra value objects are ignored by the envelope DTO)
265    /// - header `x-knora-accept-project: <project_iri>`
266    ///
267    /// `token` is sent as a bearer when `Some`; omitted when `None` (anonymous
268    /// path). Bearer auth is NOT required by the endpoint — omitting it is valid
269    /// and returns only publicly-visible resources.
270    ///
271    /// `may_have_more_results` defaults to `false` when the
272    /// `knora-api:mayHaveMoreResults` key is absent from the response (D5 spec).
273    ///
274    /// `order_by` is the already-resolved complex-schema property IRI (never a bare
275    /// field name) — passed to the wire verbatim as `orderByProperty`. `None` omits
276    /// the query param; `Some(iri)` appends `orderByProperty=<iri>`.
277    fn list_resources(
278        &self,
279        server: &str,
280        project_iri: &str,
281        resource_type_iri: &str,
282        order_by: Option<&str>,
283        page: u32,
284        token: Option<&str>,
285    ) -> Result<ResourcePage, Diagnostic>;
286
287    /// Fetch the full envelope metadata of a single resource by its IRI.
288    ///
289    /// Issues `GET {server}/v2/resources/{enc(resource_iri)}?schema=complex`.
290    /// `token` is sent as a bearer when `Some`; omitted when `None` (anonymous
291    /// path — the endpoint does not require auth, but anonymous callers see only
292    /// publicly-visible resources).
293    ///
294    /// Returns a [`ResourceDetail`] with the resource's label, IRI, resource-type,
295    /// optional ARK URL and timestamps, the owning project and user IRIs, and two
296    /// translated permission facets (`visibility` + `your_access`).
297    ///
298    /// When `with_values` is `true`, the implementation **may** issue additional,
299    /// deduplicated, non-fatal ontology (`/v2/ontologies/allentities`) and
300    /// `/v2/node` fetches to resolve field labels and list-node labels; the method
301    /// is therefore **not** always a single round-trip when `with_values == true`.
302    /// `ResourceDetail.values` is set to `Some(...)` on success or when the
303    /// resource has no value fields.  Mock implementations should set
304    /// `values: None` when `with_values == false` and `values: Some(...)` when
305    /// `with_values == true`.
306    ///
307    /// When `with_values` is `false` (the default) the method behaves exactly as
308    /// the 8b implementation: a single HTTP request, `values: None`.
309    ///
310    /// Status mapping:
311    /// - `200` → parse and return `ResourceDetail`.
312    /// - `404` → `Err(Diagnostic::NotFound(...))`.
313    /// - `401`/`403` → `Err(Diagnostic::AuthRequired(...))` with a "log in" hint
314    ///   (deliberate: an anonymous caller describing a private resource gets 403,
315    ///   and `AuthRequired` with a login hint is the right UX for an auth-optional read).
316    /// - Other non-2xx → `Err(Diagnostic::ServerError(...))`.
317    /// - Transport failure → `Err(Diagnostic::Network(...))`.
318    ///
319    /// NEVER log the token.
320    fn describe_resource(
321        &self,
322        server: &str,
323        resource_iri: &str,
324        token: Option<&str>,
325        with_values: bool,
326    ) -> Result<ResourceDetail, Diagnostic>;
327
328    /// Probe `server` to confirm that `token` is currently accepted.
329    ///
330    /// Issues `GET {server}/v2/authentication` with `Authorization: Bearer
331    /// <token>`. The server is the authority — no local JWT validation is
332    /// performed.
333    ///
334    /// - `200` (or any 2xx) → `Ok(())`.
335    /// - `401` **and** `403` → `Err(Diagnostic::AuthRequired(...))`. Both map
336    ///   to the same variant because they share the same user-facing meaning:
337    ///   the token is not currently accepted. This is also why an expired token
338    ///   surfaces as `AuthRequired` rather than a distinct error kind — the
339    ///   server rejects it with `401`, which is handled identically to `403`.
340    /// - Any other non-2xx → `Err(Diagnostic::ServerError(...))`.
341    /// - Transport failure → `Err(Diagnostic::Network(...))`.
342    fn verify_token(&self, server: &str, token: &str) -> Result<(), Diagnostic>;
343
344    /// List a project's vocabularies (DSP-API "lists") via
345    /// `GET /admin/lists?projectIri={enc(project_iri)}`.
346    ///
347    /// `project_iri` must be a resolved project IRI (the action resolves the
348    /// user-supplied identifier via `resolve_project` first). Auth is optional
349    /// (the endpoint is public); `token` is sent as a bearer when `Some`,
350    /// mirroring `list_data_models`. Returns vocabularies in server order (the
351    /// action sorts).
352    ///
353    /// `node_count` and `depth` are always `None` here — the root-listing
354    /// endpoint carries neither, and fetching each vocabulary's tree to derive
355    /// them is `--count`'s job (an action-layer concern: one extra fetch per
356    /// vocabulary, opt-in and disclosed, not baked into every `list` call).
357    fn list_vocabularies(
358        &self,
359        server: &str,
360        project_iri: &str,
361        token: Option<&str>,
362    ) -> Result<Vec<Vocabulary>, Diagnostic>;
363
364    /// Fetch a single vocabulary's full tree, via `GET /admin/lists/{enc(iri)}`.
365    ///
366    /// `iri` may address either a vocabulary root or one of its nodes — the
367    /// response is polymorphic on which key it carries (`list` for a root,
368    /// `node` for a node). When it is a root, the tree is built directly from
369    /// the response. When it is a node, the response's own subtree payload is
370    /// discarded and the implementation resolves upward: it reads
371    /// `hasRootNode` from the node response and issues a second
372    /// `GET /admin/lists/{enc(hasRootNode)}`, which MUST resolve to the root
373    /// shape — one resolution hop only, no retry loop. A failed root fetch
374    /// (either call) is a **hard error**, not a degrade: the vocabulary is
375    /// what gets rendered, so there is nothing to fall back to.
376    ///
377    /// Returns a [`VocabularyTree`] with `requested_node` set to `Some(iri)`
378    /// when the originally-addressed IRI turned out to be a node, `None` when
379    /// it was already a root. Children are position-ordered (the server
380    /// already sorts; the implementation re-sorts defensively) and walked
381    /// **iteratively** while parsing, since this is the layer closest to
382    /// untrusted server input.
383    ///
384    /// Auth is optional (public endpoint); `token` is sent as a bearer when
385    /// `Some`, mirroring `list_data_models`.
386    fn describe_vocabulary(
387        &self,
388        server: &str,
389        iri: &str,
390        token: Option<&str>,
391    ) -> Result<VocabularyTree, Diagnostic>;
392}