@deepdockai/cli 1.1.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,31 +8,30 @@ Everything action-specific (fields, types, patterns) comes from the live OpenAPI
8
8
  from __future__ import annotations
9
9
 
10
10
  import os
11
+ import re
11
12
  import time
12
13
  from dataclasses import dataclass, field, replace
13
- from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
14
- from urllib.parse import quote
14
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union
15
+ from urllib.parse import quote, unquote
15
16
 
16
17
  import httpx
17
18
 
18
19
  # A flat JSON value as the action's schema declares it: a number is a number, never its text.
19
20
  InputValue = Union[str, int, float, bool]
21
+ T = TypeVar("T")
20
22
 
21
23
 
22
24
  class DeepdockError(Exception):
23
25
  """Deepdock answered `{ "error": { "code", ... } }`. Switch on `code`, never on `message`."""
24
26
 
25
27
  def __init__(self, status: int, code: str, message: str, request_id: Optional[str] = None,
26
- systems: Optional[List[str]] = None, version: Optional[str] = None,
27
- reason: Optional[str] = None, created: Optional[Dict[str, Any]] = None,
28
+ systems: Optional[List[str]] = None, created: Optional[Dict[str, Any]] = None,
28
29
  uncertain: Optional[bool] = None):
29
30
  super().__init__(message)
30
31
  self.status = status
31
32
  self.code = code
32
33
  self.request_id = request_id
33
34
  self.systems = systems
34
- self.version = version # system_version_unverified: the version the system last reported, None when it reported none
35
- self.reason = reason # system_version_unverified: unverified_version, unparseable or unreported
36
35
  self.created = created # applied_unverified, outcome_unknown with no rollback: {"chartId"} or None
37
36
  self.retry_after: Optional[str] = None # the Retry-After header as sent (seconds), when the answer carried one
38
37
  self.uncertain = uncertain # outcome_unknown: True when the write may or may not have landed
@@ -66,6 +65,45 @@ class WriteResult:
66
65
  replayed: bool
67
66
 
68
67
 
68
+ @dataclass
69
+ class Download:
70
+ """A file action's answer: the bytes, the type the action declares, and the name to save it under."""
71
+ content: bytes
72
+ content_type: str
73
+ filename: Optional[str]
74
+
75
+
76
+ def _filename(disposition: Optional[str]) -> Optional[str]:
77
+ # Deepdock sends filename* (UTF-8) beside an ASCII filename; the name is already safe to save on
78
+ # Windows, and can carry personal data (a patient's name in a document title).
79
+ if disposition is None:
80
+ return None
81
+ extended = re.search(r"filename\*=UTF-8''([^;]+)", disposition, re.IGNORECASE)
82
+ if extended:
83
+ try:
84
+ return unquote(extended.group(1).strip(), errors="strict")
85
+ except UnicodeDecodeError:
86
+ pass # a malformed escape: fall back to the ASCII name
87
+ plain = re.search(r'filename="([^"]*)"', disposition, re.IGNORECASE)
88
+ return plain.group(1) if plain else None
89
+
90
+
91
+ def _unwrap(r: httpx.Response) -> Tuple[Any, Optional[str]]:
92
+ try:
93
+ body = r.json()
94
+ except ValueError:
95
+ raise DeepdockTransportError(f"non-JSON answer with status {r.status_code}")
96
+ if isinstance(body, dict) and "error" in body:
97
+ e = body["error"]
98
+ err = DeepdockError(r.status_code, e["code"], e["message"], e.get("requestId"), e.get("systems"),
99
+ e.get("created"), e.get("uncertain"))
100
+ err.retry_after = r.headers.get("retry-after")
101
+ raise err
102
+ if not isinstance(body, dict) or "data" not in body:
103
+ raise DeepdockTransportError(f"unexpected body with status {r.status_code}")
104
+ return body["data"], body.get("nextCursor")
105
+
106
+
69
107
  class Deepdock:
70
108
  def __init__(self, api_key: str, base: Optional[str] = None, timeout: float = 35.0,
71
109
  client: Optional[httpx.Client] = None, max_attempts: int = 3, sleep=time.sleep):
@@ -80,35 +118,44 @@ class Deepdock:
80
118
  self.c = client or httpx.Client(base_url=base.rstrip("/"), timeout=timeout)
81
119
  self.c.headers["Authorization"] = f"Bearer {api_key}"
82
120
 
83
- def _send(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers]:
121
+ def _retrying(self, once: Callable[[], T]) -> T:
84
122
  attempt = 1
85
123
  while True:
86
124
  try:
87
- return self._send_once(method, path, **kw)
125
+ return once()
88
126
  except DeepdockError as e:
89
127
  if attempt >= self.max_attempts or e.status != 503 or e.code != "target_busy":
90
128
  raise
91
129
  self._sleep(_retry_wait(e.retry_after))
92
130
  attempt += 1
93
131
 
94
- def _send_once(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers]:
132
+ def _request(self, method: str, path: str, **kw: Any) -> httpx.Response:
95
133
  try:
96
- r = self.c.request(method, path, **kw)
97
- except httpx.HTTPError as e: # timeouts and network errors
134
+ return self.c.request(method, path, **kw)
135
+ except httpx.HTTPError as e: # timeouts, network errors, and a body cut off mid-way
98
136
  raise DeepdockTransportError(f"no answer from Deepdock: {type(e).__name__}") from e
99
- try:
100
- body = r.json()
101
- except ValueError:
102
- raise DeepdockTransportError(f"non-JSON answer with status {r.status_code}")
103
- if isinstance(body, dict) and "error" in body:
104
- e = body["error"]
105
- err = DeepdockError(r.status_code, e["code"], e["message"], e.get("requestId"), e.get("systems"),
106
- e.get("version"), e.get("reason"), e.get("created"), e.get("uncertain"))
107
- err.retry_after = r.headers.get("retry-after")
108
- raise err
109
- if not isinstance(body, dict) or "data" not in body:
137
+
138
+ def _send(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers, Optional[str]]:
139
+ def once() -> Tuple[Any, httpx.Headers, Optional[str]]:
140
+ r = self._request(method, path, **kw)
141
+ data, next_cursor = _unwrap(r)
142
+ return data, r.headers, next_cursor
143
+ return self._retrying(once)
144
+
145
+ def _download_once(self, path: str, params: Dict[str, InputValue]) -> Download:
146
+ r = self._request("POST", path, json=params)
147
+ if not 200 <= r.status_code < 300:
148
+ _unwrap(r)
110
149
  raise DeepdockTransportError(f"unexpected body with status {r.status_code}")
111
- return body["data"], r.headers
150
+ # Once the bytes flow, a failure can only end the body early. Content-Length counts encoded
151
+ # bytes, so it is compared only on a body sent as is.
152
+ declared = r.headers.get("content-length")
153
+ encoded = r.headers.get("content-encoding", "identity") != "identity"
154
+ if declared is not None and not encoded and int(declared) != len(r.content):
155
+ raise DeepdockTransportError(f"download ended at {len(r.content)} of {declared} bytes")
156
+ return Download(content=r.content,
157
+ content_type=r.headers.get("content-type", "application/octet-stream"),
158
+ filename=_filename(r.headers.get("content-disposition")))
112
159
 
113
160
  @staticmethod
114
161
  def _action_path(device_id: str, system: str, action: str) -> str:
@@ -116,15 +163,21 @@ class Deepdock:
116
163
 
117
164
  def read(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
118
165
  limit: Optional[int] = None, cursor: Optional[str] = None) -> Page:
119
- """Runs a read action: a POST whose JSON body holds the inputs and the paging fields, no
166
+ """Runs a read action with `cardinality: many`: a POST whose JSON body holds the inputs and the paging fields, no
120
167
  Idempotency-Key. Pass `next_cursor` back as `cursor` for the next page."""
121
168
  body: Dict[str, InputValue] = dict(params)
122
169
  if limit is not None:
123
170
  body["limit"] = limit
124
171
  if cursor is not None:
125
172
  body["cursor"] = cursor
126
- data, _ = self._send("POST", self._action_path(device_id, system, action), json=body)
127
- return Page(items=data["items"], next_cursor=data.get("nextCursor"))
173
+ data, _, next_cursor = self._send("POST", self._action_path(device_id, system, action), json=body)
174
+ return Page(items=data, next_cursor=next_cursor)
175
+
176
+ def read_one(self, device_id: str, system: str, action: str, params: Dict[str, InputValue]) -> Dict[str, Any]:
177
+ """Runs a single-record read (`cardinality: one`): the answer's `data` is the record itself.
178
+ A record that does not exist raises DeepdockError with status 404 and code "not_found"."""
179
+ data, _, _ = self._send("POST", self._action_path(device_id, system, action), json=params)
180
+ return data
128
181
 
129
182
  def read_all(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
130
183
  limit: Optional[int] = None) -> Iterator[Dict[str, Any]]:
@@ -137,6 +190,13 @@ class Deepdock:
137
190
  return
138
191
  cursor = page.next_cursor
139
192
 
193
+ def download(self, device_id: str, system: str, action: str, params: Dict[str, InputValue]) -> Download:
194
+ """Runs a file action (`file: true` in the action index): a POST like a read, answered with the file's
195
+ bytes instead of JSON. A refusal raises DeepdockError as for any action; a body that ends short of its
196
+ Content-Length raises DeepdockTransportError, and the download can be run again. The client's timeout
197
+ applies between bytes, so a large file streams as long as it keeps moving."""
198
+ return self._retrying(lambda: self._download_once(self._action_path(device_id, system, action), params))
199
+
140
200
  def write(self, device_id: str, system: str, action: str, operation: str, idempotency_key: str,
141
201
  body: Dict[str, InputValue]) -> WriteResult:
142
202
  """Runs a write action: POST for operation "create", PATCH for "update" (from the action index; any
@@ -144,22 +204,22 @@ class Deepdock:
144
204
  action's schema declares. Any other `operation` raises ValueError before anything is sent."""
145
205
  if operation not in ("create", "update"):
146
206
  raise ValueError(f"operation must be 'create' or 'update', got {operation!r}")
147
- data, headers = self._send("PATCH" if operation == "update" else "POST",
207
+ data, headers, _ = self._send("PATCH" if operation == "update" else "POST",
148
208
  self._action_path(device_id, system, action), json=body,
149
209
  headers={"Idempotency-Key": idempotency_key})
150
210
  return WriteResult(data=data, replayed=headers.get("Idempotent-Replayed") == "true")
151
211
 
152
212
  def systems(self, device_id: str) -> List[Dict[str, Any]]:
153
213
  """The device's systems and each action's state. A live call: can answer device_offline."""
154
- data, _ = self._send("GET", f"/v1/devices/{quote(device_id, safe='')}/systems")
214
+ data, _, _ = self._send("GET", f"/v1/devices/{quote(device_id, safe='')}/systems")
155
215
  return data
156
216
 
157
217
  def pair(self, code: str, label: Optional[str] = None) -> Dict[str, Any]:
158
- """Claims a device by the pairing code it shows. Keep the returned `id`."""
218
+ """Pairs a device by the pairing code it shows. Keep the returned `id`."""
159
219
  body: Dict[str, str] = {"code": code}
160
220
  if label is not None:
161
221
  body["label"] = label
162
- data, _ = self._send("POST", "/v1/devices", json=body)
222
+ data, _, _ = self._send("POST", "/v1/devices", json=body)
163
223
  return data
164
224
 
165
225
  def release(self, device_id: str) -> None:
@@ -170,13 +230,13 @@ class Deepdock:
170
230
  # Pending writes: one attempt against persisted state. Persist the row BEFORE the first send, so a
171
231
  # crash between send and answer cannot produce a second record under a new key. A job retries rows
172
232
  # left in "sent" with backoff (seconds, then minutes, for hours if the device stays offline).
173
- # For system_version_unverified and device_outdated, poll the device's `writes` / `outdated` before
174
- # retrying: they take longer than minutes.
233
+ # For device_outdated, poll the device's `outdated` and `blockedActions` before retrying: it takes longer than minutes.
234
+ # version_not_covered is not retried: Deepdock has to approve the installed version first.
175
235
  # --------------------------------------------------------------------------------------------------
176
236
 
177
237
  CONFLICT_RETRIES = 5 # a running write finishes within seconds; beyond this, treat it as unknown
178
238
 
179
- RETRY_SAME_KEY = {"device_offline", "device_syncing", "device_outdated", "system_version_unverified",
239
+ RETRY_SAME_KEY = {"device_offline", "device_syncing", "device_outdated",
180
240
  "target_busy", "temporarily_unavailable", "internal_error", "action_paused",
181
241
  "system_unavailable"}
182
242
 
@@ -13,10 +13,6 @@ export class DeepdockError extends Error {
13
13
  readonly code: string
14
14
  readonly requestId?: string
15
15
  readonly systems?: string[]
16
- /** system_version_unverified: the version the system last reported, `null` when it reported none. */
17
- readonly version?: string | null
18
- /** system_version_unverified: `unverified_version`, `unparseable` or `unreported`. */
19
- readonly reason?: string
20
16
  /** applied_unverified, outcome_unknown on a system with no rollback: the entry, or `null` when not known. */
21
17
  readonly created?: { chartId?: string } | null
22
18
  /** outcome_unknown: `true` when the write may or may not have landed. */
@@ -26,8 +22,6 @@ export class DeepdockError extends Error {
26
22
 
27
23
  constructor(status: number, code: string, message: string, requestId?: string,
28
24
  systems?: string[],
29
- version?: string | null,
30
- reason?: string,
31
25
  created?: { chartId?: string } | null,
32
26
  uncertain?: boolean,
33
27
  ) {
@@ -37,8 +31,6 @@ export class DeepdockError extends Error {
37
31
  this.code = code
38
32
  this.requestId = requestId
39
33
  this.systems = systems
40
- this.version = version
41
- this.reason = reason
42
34
  this.created = created
43
35
  this.uncertain = uncertain
44
36
  }
@@ -52,9 +44,10 @@ export class DeepdockTransportError extends Error {
52
44
  }
53
45
  }
54
46
 
55
- type ErrorBody = { code: string; message: string; requestId?: string; systems?: string[]; version?: string | null; reason?: string; created?: { chartId?: string } | null; uncertain?: boolean }
56
- type Envelope<T> = { data: T } | { error: ErrorBody }
47
+ type ErrorBody = { code: string; message: string; requestId?: string; systems?: string[]; created?: { chartId?: string } | null; uncertain?: boolean }
48
+ type Envelope<T> = { data: T; nextCursor?: string | null } | { error: ErrorBody }
57
49
 
50
+ /** One page of a `many` read: `items` is the answer's `data` array, `nextCursor` its top-level sibling. */
58
51
  export type Page<Item> = { items: Item[]; nextCursor: string | null }
59
52
  export type WriteResult<T> = { data: T; replayed: boolean }
60
53
  /** A flat JSON value as the action's schema declares it: a number is a number, never its text. */
@@ -63,19 +56,13 @@ export type InputValue = string | number | boolean
63
56
  export type WriteOperation = 'create' | 'update'
64
57
  export type ActionInput = Record<string, InputValue>
65
58
 
66
- export type SystemStatus = 'running' | 'stopped' | 'missing' | 'unknown'
59
+ /** `missing`: never found on the PC; `vanished`: found once and not any more. */
60
+ export type SystemStatus = 'running' | 'stopped' | 'missing' | 'unknown' | 'vanished'
67
61
  /** The database access the device last reported; `null` while none is known. */
68
62
  export type SystemAccess = 'ok' | 'outdated' | 'missing' | 'password_missing' | 'not_set_up' | null
69
63
 
70
- /**
71
- * Whether writes on the system run. `unverified` makes writes answer system_version_unverified:
72
- * `unverified_version` clears once Deepdock verifies the version; `unparseable` does not clear by
73
- * waiting (contact Deepdock); `unreported` clears once the device reports the system's version (a
74
- * write verified for one exact release needs it).
75
- */
76
- export type SystemWrites =
77
- | { state: 'verified' | 'unknown' | 'partial' }
78
- | { state: 'unverified'; reason: 'unverified_version' | 'unparseable' | 'unreported' }
64
+ /** Why a system's `version` is missing, when the device says. */
65
+ export type VersionIssue = 'not_installed' | 'not_found' | 'unreadable'
79
66
 
80
67
  export type Device = {
81
68
  id: string
@@ -94,13 +81,15 @@ export type Device = {
94
81
  systems: {
95
82
  system: string
96
83
  version: string | null
84
+ versionIssue: VersionIssue | null
97
85
  status: SystemStatus
98
86
  access: SystemAccess
99
87
  /** Set when `access` is the last known value (the device could not read it): when it last did. */
100
88
  accessLastCheckedAt: string | null
101
89
  lockedActions: string[] | null
102
90
  reportedAt: string
103
- writes: SystemWrites
91
+ /** Actions this device's client cannot run yet: each answers device_outdated until it updates. Absent when none. */
92
+ blockedActions?: string[]
104
93
  }[]
105
94
  }
106
95
 
@@ -119,6 +108,7 @@ export type DeviceSystem = {
119
108
  system: string
120
109
  label: string | null
121
110
  version?: string
111
+ versionIssue?: VersionIssue
122
112
  status: SystemStatus
123
113
  access: SystemAccess
124
114
  /** Set when `access` is the last known value (the device could not read it): when it last did. */
@@ -142,6 +132,45 @@ export type DeepdockOptions = {
142
132
  sleep?: (ms: number) => Promise<void>
143
133
  }
144
134
 
135
+ type SendInit = { method: string; headers?: Record<string, string>; body?: string }
136
+
137
+ /** A file action's answer: the bytes, the type the action declares, and the name to save it under. */
138
+ export type Download = { bytes: Uint8Array; contentType: string; filename: string | null }
139
+
140
+ const unwrap = async <T>(res: Response): Promise<{ data: T; nextCursor: string | null }> => {
141
+ let body: Envelope<T>
142
+ try {
143
+ body = (await res.json()) as Envelope<T>
144
+ } catch {
145
+ throw new DeepdockTransportError(`non-JSON answer with status ${res.status}`)
146
+ }
147
+ if (body !== null && typeof body === 'object' && 'error' in body) {
148
+ const { code, message, requestId, systems, created, uncertain } = body.error
149
+ const error = new DeepdockError(res.status, code, message, requestId, systems, created, uncertain)
150
+ error.retryAfter = res.headers.get('retry-after') ?? undefined
151
+ throw error
152
+ }
153
+ if (body === null || typeof body !== 'object' || !('data' in body)) {
154
+ throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
155
+ }
156
+ return { data: body.data, nextCursor: body.nextCursor ?? null }
157
+ }
158
+
159
+ // Deepdock sends `filename*` (UTF-8) beside an ASCII `filename`; the name is already safe to save
160
+ // on Windows, and can carry personal data (a patient's name in a document title).
161
+ const filenameOf = (disposition: string | null): string | null => {
162
+ if (disposition === null) return null
163
+ const extended = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]
164
+ if (extended !== undefined) {
165
+ try {
166
+ return decodeURIComponent(extended.trim())
167
+ } catch {
168
+ // A malformed escape: fall back to the ASCII name.
169
+ }
170
+ }
171
+ return /filename="([^"]*)"/i.exec(disposition)?.[1] ?? null
172
+ }
173
+
145
174
  /** Longest wait between two attempts, whatever `Retry-After` asks for. */
146
175
  const MAX_RETRY_WAIT_MS = 15_000
147
176
  const DEFAULT_RETRY_WAIT_MS = 1_000
@@ -189,13 +218,10 @@ export class Deepdock {
189
218
  this.sleep = sleep
190
219
  }
191
220
 
192
- private async send<T>(
193
- path: string,
194
- init: { method: string; headers?: Record<string, string>; body?: string },
195
- ): Promise<{ data: T; headers: Headers }> {
221
+ private async retrying<R>(once: () => Promise<R>): Promise<R> {
196
222
  for (let attempt = 1; ; attempt++) {
197
223
  try {
198
- return await this.sendOnce<T>(path, init)
224
+ return await once()
199
225
  } catch (err) {
200
226
  if (
201
227
  attempt >= this.maxAttempts ||
@@ -210,38 +236,75 @@ export class Deepdock {
210
236
  }
211
237
  }
212
238
 
213
- private async sendOnce<T>(
214
- path: string,
215
- init: { method: string; headers?: Record<string, string>; body?: string },
216
- ): Promise<{ data: T; headers: Headers }> {
217
- let res: Response
239
+ private async fetchOnce(path: string, init: SendInit, signal: AbortSignal): Promise<Response> {
218
240
  try {
219
- res = await this.fetchImpl(`${this.base}${path}`, {
241
+ return await this.fetchImpl(`${this.base}${path}`, {
220
242
  method: init.method,
221
243
  headers: { Authorization: `Bearer ${this.apiKey}`, ...init.headers },
222
244
  body: init.body,
223
- signal: AbortSignal.timeout(this.timeoutMs),
245
+ signal,
224
246
  })
225
247
  } catch (err) {
226
248
  // TimeoutError from AbortSignal.timeout, AbortError, or a network TypeError.
227
249
  throw new DeepdockTransportError(`no answer from Deepdock: ${(err as Error).name}`)
228
250
  }
229
- let body: Envelope<T>
251
+ }
252
+
253
+ private send<T>(path: string, init: SendInit): Promise<{ data: T; headers: Headers; nextCursor: string | null }> {
254
+ return this.retrying(async () => {
255
+ const res = await this.fetchOnce(path, init, AbortSignal.timeout(this.timeoutMs))
256
+ return { ...(await unwrap<T>(res)), headers: res.headers }
257
+ })
258
+ }
259
+
260
+ private async downloadOnce(path: string, init: SendInit): Promise<Download> {
261
+ // The timeout bounds the wait for the answer and then each gap between two chunks, not the
262
+ // whole transfer: a large file streams for longer than one attempt's timeout.
263
+ const deadline = new AbortController()
264
+ let timer = setTimeout(() => deadline.abort(), this.timeoutMs)
265
+ const chunks: Uint8Array[] = []
266
+ let size = 0
267
+ let res: Response
230
268
  try {
231
- body = (await res.json()) as Envelope<T>
232
- } catch {
233
- throw new DeepdockTransportError(`non-JSON answer with status ${res.status}`)
269
+ res = await this.fetchOnce(path, init, deadline.signal)
270
+ if (!res.ok) {
271
+ await unwrap<unknown>(res)
272
+ throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
273
+ }
274
+ const reader = res.body?.getReader()
275
+ try {
276
+ while (reader) {
277
+ const { done, value } = await reader.read()
278
+ if (done) break
279
+ chunks.push(value)
280
+ size += value.byteLength
281
+ clearTimeout(timer)
282
+ timer = setTimeout(() => deadline.abort(), this.timeoutMs)
283
+ }
284
+ } catch (err) {
285
+ throw new DeepdockTransportError(`download cut off: ${(err as Error).name}`)
286
+ }
287
+ } finally {
288
+ clearTimeout(timer)
289
+ }
290
+ const bytes = new Uint8Array(size)
291
+ let offset = 0
292
+ for (const chunk of chunks) {
293
+ bytes.set(chunk, offset)
294
+ offset += chunk.byteLength
234
295
  }
235
- if (body !== null && typeof body === 'object' && 'error' in body) {
236
- const { code, message, requestId, systems, version, reason, created, uncertain } = body.error
237
- const error = new DeepdockError(res.status, code, message, requestId, systems, version, reason, created, uncertain)
238
- error.retryAfter = res.headers.get('retry-after') ?? undefined
239
- throw error
296
+ // Once the bytes flow, a failure can only end the body early. Content-Length counts encoded
297
+ // bytes, so it is compared only on a body sent as is.
298
+ const declared = res.headers.get('content-length')
299
+ const encoded = (res.headers.get('content-encoding') ?? 'identity') !== 'identity'
300
+ if (declared !== null && !encoded && Number(declared) !== bytes.byteLength) {
301
+ throw new DeepdockTransportError(`download ended at ${bytes.byteLength} of ${declared} bytes`)
240
302
  }
241
- if (body === null || typeof body !== 'object' || !('data' in body)) {
242
- throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
303
+ return {
304
+ bytes,
305
+ contentType: res.headers.get('content-type') ?? 'application/octet-stream',
306
+ filename: filenameOf(res.headers.get('content-disposition')),
243
307
  }
244
- return { data: body.data, headers: res.headers }
245
308
  }
246
309
 
247
310
  private actionPath(deviceId: string, system: string, action: string): string {
@@ -249,7 +312,7 @@ export class Deepdock {
249
312
  }
250
313
 
251
314
  /**
252
- * Runs a read action: a POST whose JSON body holds the inputs and the paging fields, no
315
+ * Runs a read action with `cardinality: many`: a POST whose JSON body holds the inputs and the paging fields, no
253
316
  * Idempotency-Key. Pass `nextCursor` back as `cursor` for the next page.
254
317
  */
255
318
  async read<Item>(
@@ -262,11 +325,24 @@ export class Deepdock {
262
325
  const body: ActionInput = { ...input }
263
326
  if (page.limit !== undefined) body.limit = page.limit
264
327
  if (page.cursor !== undefined) body.cursor = page.cursor
328
+ const { data, nextCursor } = await this.send<Item[]>(this.actionPath(deviceId, system, action), {
329
+ method: 'POST',
330
+ headers: { 'Content-Type': 'application/json' },
331
+ body: JSON.stringify(body),
332
+ })
333
+ return { items: data, nextCursor }
334
+ }
335
+
336
+ /**
337
+ * Runs a single-record read (`cardinality: one`): the answer's `data` is the record itself. A
338
+ * record that does not exist throws a DeepdockError with status 404 and code `not_found`.
339
+ */
340
+ async readOne<Row>(deviceId: string, system: string, action: string, input: ActionInput): Promise<Row> {
265
341
  return (
266
- await this.send<Page<Item>>(this.actionPath(deviceId, system, action), {
342
+ await this.send<Row>(this.actionPath(deviceId, system, action), {
267
343
  method: 'POST',
268
344
  headers: { 'Content-Type': 'application/json' },
269
- body: JSON.stringify(body),
345
+ body: JSON.stringify(input),
270
346
  })
271
347
  ).data
272
348
  }
@@ -287,6 +363,21 @@ export class Deepdock {
287
363
  } while (cursor !== undefined)
288
364
  }
289
365
 
366
+ /**
367
+ * Runs a file action (`file: true` in the action index): a POST like a read, answered with the
368
+ * file's bytes instead of JSON. A refusal is a DeepdockError as for any action; a body that ends
369
+ * short of its Content-Length is a DeepdockTransportError, and the download can be run again.
370
+ */
371
+ download(deviceId: string, system: string, action: string, input: ActionInput): Promise<Download> {
372
+ return this.retrying(() =>
373
+ this.downloadOnce(this.actionPath(deviceId, system, action), {
374
+ method: 'POST',
375
+ headers: { 'Content-Type': 'application/json' },
376
+ body: JSON.stringify(input),
377
+ }),
378
+ )
379
+ }
380
+
290
381
  /**
291
382
  * Runs a write action: POST for a `create`, PATCH for an `update`. Take `operation` from the
292
383
  * action index; any other method answers 405 with `Allow` naming the right one. `input` values
@@ -314,7 +405,7 @@ export class Deepdock {
314
405
  return (await this.send<DeviceSystem[]>(`/v1/devices/${encodeURIComponent(deviceId)}/systems`, { method: 'GET' })).data
315
406
  }
316
407
 
317
- /** Claims a device by the pairing code it shows. Keep the returned `id`. */
408
+ /** Pairs a device by the pairing code it shows. Keep the returned `id`. */
318
409
  async pair(code: string, label?: string): Promise<Device> {
319
410
  const body: PairBody = label === undefined ? { code } : { code, label }
320
411
  return (
@@ -335,8 +426,8 @@ export class Deepdock {
335
426
  * Pending writes: one attempt against persisted state. Persist the row BEFORE the first send, so a
336
427
  * crash between send and answer cannot produce a second record under a new key. A job retries rows
337
428
  * left in `sent` with backoff (seconds, then minutes, for hours if the device stays offline).
338
- * For system_version_unverified and device_outdated, poll the device's `writes` / `outdated` before
339
- * retrying: they take longer than minutes.
429
+ * For device_outdated, poll the device's `outdated` and `blockedActions` before retrying: it takes longer than minutes.
430
+ * version_not_covered is not retried: Deepdock has to approve the installed version first.
340
431
  * ---------------------------------------------------------------------------------------------- */
341
432
 
342
433
  export type PendingStatus = 'pending' | 'sent' | 'done' | 'unknown' | 'refused'
@@ -363,7 +454,6 @@ const RETRY_SAME_KEY = new Set([
363
454
  'device_offline',
364
455
  'device_syncing',
365
456
  'device_outdated',
366
- 'system_version_unverified',
367
457
  'target_busy',
368
458
  'temporarily_unavailable',
369
459
  'internal_error',
@@ -25,9 +25,9 @@ The Deepdock client installed on the customer's Windows PC next to their system.
25
25
  outwards to Deepdock; nothing in the customer's network is opened to the internet. A device is
26
26
  identified by a UUID (`id`), carries a `label`, `hostname`, `os`, `clientVersion`, `status`
27
27
  (`connected`, `offline` or `inactive`), `lastSeenAt`, `lastKnownAt`, `claimedAt` (may be `null`), `outdated` (an
28
- assigned action needs a newer client: it answers `device_outdated`) and the `systems` it reported (each with a `writes` state; reads always work). `verified`: writes run. `unknown`: no version was reported, and writes go through. `partial`: some writes run and some are refused. `unverified`: a write answers `system_version_unverified`; with `reason: unverified_version` it works once Deepdock has verified that version, with `reason: unparseable` retrying does not help and you contact Deepdock.
28
+ assigned action needs a newer client: it answers `device_outdated`) and the `systems` it reported (each with a `versionIssue` when `version` is missing, and `blockedActions` when this device's client cannot run some actions yet: those answer `device_outdated` until the client updates, the others keep running). An action whose system runs a program version Deepdock has not yet approved for it answers `version_not_covered`; nothing is sent to the system, and it works once Deepdock has approved that version.
29
29
 
30
- - **Pair**: claim a device for your organisation with the 6-character code it shows while unpaired.
30
+ - **Pair**: take a device into your organisation with the 6-character code it shows while unpaired.
31
31
  - **Release**: `DELETE /v1/devices/{deviceId}` gives the device back; it shows a new code.
32
32
  - **Inactive**: a paired device that has not connected for 7 days. It stays yours and is active again
33
33
  when it connects.
@@ -51,11 +51,14 @@ has a display `label` (may be `null`), a `version` the device reported (may be a
51
51
  | device `lastKnownAt` | ISO time or `null` | the time of the device's last report while it is not connected. `null` while it is connected | show the last known state with this time; it may be out of date |
52
52
  | system `status` | `running` | the customer's program is running on the device | normal |
53
53
  | system `status` | `stopped` | the program is installed but not running | calls answer `system_unavailable`; the site starts the program |
54
- | system `status` | `missing` | the program was not found where the device expects it | calls answer `system_unavailable`; contact the site and Deepdock |
54
+ | system `status` | `missing` | the device has never found the program on this PC | the PC does not run it; calls answer `system_unavailable` |
55
+ | system `status` | `vanished` | the device found the program once and cannot find it now | check that it is still installed on that PC; calls answer `system_unavailable`; contact the site and Deepdock |
55
56
  | system `status` | `unknown` | the device could not tell whether the program runs (its probe failed or is unavailable on that PC) | do not read it as stopped; the device decides when a call arrives |
56
57
  | system `access` | `ok`, `outdated`, `missing`, `password_missing`, `not_set_up`, or `null` | the database access the device last reported (`null`: none known yet) | `outdated` refuses the actions that need the missing right with `access_outdated`, `missing` (the account cannot log in) and `password_missing` (the account exists but its stored password is not on the PC) refuse every action with `access_missing`; the customer repeats "Erneut einrichten" in the Deepdock client, the incident closes by itself once `access` is `ok`, nothing to resume |
57
58
  | system `accessLastCheckedAt` | ISO time or `null` | set when `access` is the last known value because the device could not read it (its database stopped or unreachable): when it last read it. `null` when the latest report read it | show the access as last known, with this time; nothing to do until the device reads it again |
59
+ | system `versionIssue` | `not_installed`, `not_found`, `unreadable`, or `null` | why `version` is missing, when the device says: its database service is not on the PC, its program file was not found, or the file carries no readable version. `null` (absent on `GET .../systems`) with a version, and from a device that does not say | show the reason beside the missing version; there is nothing to do on your side |
58
60
  | system `lockedActions` | list of action names or `null` | the actions the device reports locked because its database account lacks a right they need, under the spec set it runs now. `null`: no verdict yet, or the verdict is for an older spec set | do not offer a locked action as available; it answers `access_outdated` until the customer repeats "Erneut einrichten" |
61
+ | system `blockedActions` | list of action names, or absent | the actions this device's Deepdock client cannot run yet, because they need something only a newer client can do. Absent: none | do not offer a listed action as available; a call answers `device_outdated` and nothing runs, until the client updates itself and the action leaves the list |
59
62
  | action state | `active` | the action can be called | normal |
60
63
  | action state | `paused` | the action is paused with a `reason` and `pausedAt` | calls answer `action_paused`; show the feature as paused, poll `GET .../systems` at a low rate |
61
64
  | pause `reason` | `structure_changed` | the system changed in a way the action depends on (for example a vendor update); Deepdock reviews and resumes | wait; nothing to do on your side |
@@ -7,7 +7,7 @@ Never hard-code an action's fields. Three sources, each authoritative for one th
7
7
  | Which systems and actions does my organisation have? | `deepdock systems list --json` | CLI sign-in |
8
8
  | What does this device run, and is each action active or paused? | `GET /v1/devices/{deviceId}/systems` | organisation |
9
9
  | Which actions can I call on this device's system, with which schemas? | `GET /v1/devices/{deviceId}/systems/{system}/actions` | organisation |
10
- | The exact paths, operations, fields, patterns, enums, lengths, responses | `deepdock systems openapi <system>` (CLI sign-in) or `GET /v1/systems/{system}/openapi.json` (API key); per device `deepdock actions list <device> <system>` (CLI sign-in) | CLI sign-in or API key |
10
+ | The exact paths, operations, fields, patterns, enums, lengths, responses | `deepdock systems openapi <system>` (CLI sign-in) or `GET /v1/systems/{system}/openapi.json` (API key); per device `deepdock actions list <deviceId> <system>` (CLI sign-in) | CLI sign-in or API key |
11
11
 
12
12
  ## The OpenAPI document
13
13
 
@@ -39,7 +39,7 @@ What to read off it:
39
39
  `cursor` (opaque). An optional input is not in `required` and its description says what an
40
40
  omitted value becomes. A write's `Idempotency-Key` header
41
41
  parameter carries its own pattern (8 to 128 characters of `A-Z a-z 0-9 _ -`).
42
- - **Responses**: a read's `200` is `{ data: { items: [...], nextCursor } }`; a create's `201` and a
42
+ - **Responses**: a read's `200` is `{ data: [...], nextCursor }` for `cardinality: many` (`nextCursor` only when the read can page) and `{ data: { ...record } }` for `cardinality: one`, which answers `404 not_found` when nothing matches; a file action's `200` is the file's bytes under its declared content type, with `Content-Disposition` and, when known, `Content-Length` ([calling-actions.md](calling-actions.md#file-actions)); a create's `201` and a
43
43
  replayed `200`; an update's `200`. Item and result fields are typed `string`, `integer` or `number`,
44
44
  often nullable (`["integer", "null"]`). The `Error` schema's `code` enum is the full list of codes.
45
45
  - **`servers`**: the base URL of the API.
@@ -57,7 +57,8 @@ curl "$BASE/v1/devices/$DEVICE/systems/example-erp/actions" \
57
57
  ```
58
58
 
59
59
  Answers `{ data: [ { name, operation, method, description, input, output } ] }`, filtered to your assigned
60
- actions, with the same JSON Schemas the OpenAPI document carries. Use it at runtime to confirm an
60
+ actions, with the same JSON Schemas the OpenAPI document carries. A file action also carries
61
+ `file: true`: it answers with the file's bytes, not JSON. Use it at runtime to confirm an
61
62
  action exists before offering it in your UI, or to validate input client-side before sending.
62
63
 
63
64
  ## The device's systems