BREP_plm 0.13.0

The BREP PLM server: parts, revisions, lifecycle, checkout, BOMs and configurable workflows over an embedded SQLite store, with a browser UI and the document API the BREP CAD app stores through.
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
//! Workspaces over HTTP. The rules are in [`crate::workspace`].
//!
//! A file upload is the raw bytes as the body, as for attachments
//! ([`super::attachments`]): its media type as `Content-Type`, its folder and
//! name in the query string. It streams to disk and is refused with `413` the
//! moment it passes the attachment limit.

use axum::body::Body;
use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::Response;
use axum::Json;
use serde::Deserialize;
use serde_json::{json, Value};

use super::attachments::{receive, stream_blob};
use super::{blocking, require_user, Shared};
use crate::workspace::Promote;
use crate::Error;

fn media_type(headers: &HeaderMap) -> String {
    headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("")
        .to_string()
}

fn seq(db: &Shared) -> u64 {
    db.read(|state| state.seq)
}

/// The workspaces the caller may open, their own first.
pub async fn list_workspaces(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let browsable = db.read(|state| state.settings.workspaces_browsable);
    Ok(Json(json!({ "workspaces": db.workspaces(&user), "browsable": browsable })))
}

#[derive(Debug, Deserialize, Default)]
pub struct FolderQuery {
    /// A user id or username; empty is the caller.
    #[serde(default)]
    pub owner: String,
    /// A folder id; empty is the top.
    #[serde(default)]
    pub parent: String,
}

/// The entries in one folder.
pub async fn list_folder(
    State(db): State<Shared>,
    headers: HeaderMap,
    Query(query): Query<FolderQuery>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let entries = db.workspace_folder(&user, &query.owner, &query.parent)?;
    Ok(Json(json!({ "entries": entries, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct LinksQuery {
    /// A part id or number.
    #[serde(default)]
    pub part: String,
}

/// The folders of the caller's own workspace that link a part (`?part=`).
pub async fn folders_linking(
    State(db): State<Shared>,
    headers: HeaderMap,
    Query(query): Query<LinksQuery>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let folders = db.folders_linking(&user, &query.part)?;
    Ok(Json(json!({ "folders": folders })))
}

/// Every folder the caller may read, linked anywhere or nowhere.
pub async fn list_folders(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    Ok(Json(json!({ "folders": db.workspace_folders(&user), "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct NewFolder {
    #[serde(default)]
    pub parent: String,
    pub name: String,
}

pub async fn create_folder(
    State(db): State<Shared>,
    headers: HeaderMap,
    Json(body): Json<NewFolder>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let made = blocking({
        let db = db.clone();
        move || db.create_folder(&user, &body.parent, &body.name)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct NewLink {
    #[serde(default)]
    pub parent: String,
    /// Empty: the part's number.
    #[serde(default)]
    pub name: String,
    /// A part id or number.
    #[serde(default)]
    pub part: String,
    /// A revision id or label to pin to; empty follows the newest.
    #[serde(default)]
    pub revision: String,
    /// Instead of a part: a folder (or a link to one) to link, the same
    /// folder in each place.
    #[serde(default)]
    pub folder: String,
    /// With `folder`: a user id or username whose Home gets the link, at
    /// its top (the folder's owner only). Empty: the caller's `parent`.
    #[serde(default)]
    pub home: String,
    /// Instead of a part or folder: a file (or a link to one).
    #[serde(default)]
    pub file: String,
    /// Instead: an attachment, on the part `part` (and revision `revision`,
    /// when it is a revision's).
    #[serde(default)]
    pub attachment: String,
}

pub async fn create_link(
    State(db): State<Shared>,
    headers: HeaderMap,
    Json(body): Json<NewLink>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let made = blocking({
        let db = db.clone();
        move || {
            if !body.folder.trim().is_empty() {
                db.link_folder(&user, &body.parent, &body.folder, &body.home)
            } else if !body.file.trim().is_empty() {
                db.link_file(&user, &body.parent, &body.file)
            } else if !body.attachment.trim().is_empty() {
                db.link_attachment(&user, &body.parent, &body.attachment, &body.part, &body.revision)
            } else {
                db.create_link(&user, &body.parent, &body.name, &body.part, &body.revision)
            }
        }
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct NewCopy {
    #[serde(default)]
    pub parent: String,
    /// One of these: a folder, a file, an attachment (with `part` and
    /// `revision` saying whose), or a part (with `revision`, which model).
    #[serde(default)]
    pub folder: String,
    #[serde(default)]
    pub file: String,
    #[serde(default)]
    pub attachment: String,
    #[serde(default)]
    pub part: String,
    #[serde(default)]
    pub revision: String,
    /// For a part whose type takes a typed number: the copy's number.
    #[serde(default)]
    pub number: String,
}

/// Paste a new unique copy of a folder, file, attachment or part into a
/// folder the caller owns (or their Home).
pub async fn create_copy(
    State(db): State<Shared>,
    headers: HeaderMap,
    Json(body): Json<NewCopy>,
) -> Result<Json<Value>, Error> {
    use crate::workspace::CopyOf;
    let user = require_user(&db, &headers)?;
    let answer = blocking({
        let db = db.clone();
        move || {
            let what = if !body.folder.trim().is_empty() {
                CopyOf::Folder(body.folder)
            } else if !body.file.trim().is_empty() {
                CopyOf::File(body.file)
            } else if !body.attachment.trim().is_empty() {
                CopyOf::Attachment { id: body.attachment, part: body.part, revision: body.revision }
            } else if !body.part.trim().is_empty() {
                let part = db.copy_part(&user, &body.parent, &body.part, &body.revision, &body.number)?;
                return Ok(json!({ "part": part }));
            } else {
                return Err(Error::bad_request("name a folder, file, attachment or part to copy"));
            };
            db.paste_copy(&user, &body.parent, &what).map(|entry| json!({ "entry": entry }))
        }
    })
    .await?;
    let mut answer = answer;
    answer["ok"] = json!(true);
    answer["seq"] = json!(seq(&db));
    Ok(Json(answer))
}

/// Every file the caller may read, linked anywhere or nowhere.
pub async fn list_files(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    Ok(Json(json!({ "files": db.workspace_files(&user), "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct NewFile {
    #[serde(default)]
    pub parent: String,
    #[serde(default)]
    pub name: String,
}

/// Upload a new file: version 1.
pub async fn create_file(
    State(db): State<Shared>,
    headers: HeaderMap,
    Query(query): Query<NewFile>,
    body: Body,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    // Refuse a bad name before reading the bytes.
    crate::workspace::clean_name(&query.name)?;
    let staged = receive(&db, &headers, body).await?;
    let media = media_type(&headers);
    let made = blocking({
        let db = db.clone();
        move || db.create_file(&user, &query.parent, &query.name, &media, staged)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": made, "seq": seq(&db) })))
}

/// One entry.
pub async fn get_entry(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    Ok(Json(json!({ "entry": db.workspace_entry(&user, &id)? })))
}

/// Rename, move, or pin / unpin a link.
pub async fn update_entry(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
    Json(body): Json<Value>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let changed = blocking({
        let db = db.clone();
        move || db.update_entry(&user, &id, &body)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct DeleteQuery {
    /// Delete a folder with everything in it.
    #[serde(default)]
    pub recursive: bool,
}

/// Remove an entry. Never a part or a revision.
pub async fn delete_entry(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(query): Query<DeleteQuery>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let removed = blocking({
        let db = db.clone();
        move || db.delete_entry(&user, &id, query.recursive)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "removed": removed, "seq": seq(&db) })))
}

/// Replace a file's bytes; the old version is kept.
pub async fn replace_file(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
    body: Body,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    // Refuse a caller who may not write before reading the bytes.
    db.read(|state| crate::workspace::check_may_change(state, &user, &id))?;
    let expected = headers.get(axum::http::header::IF_MATCH).and_then(|v| v.to_str().ok()).map(|v| v.trim_matches('"').to_string());
    if expected.as_ref().is_some_and(|v| !crate::attach::is_sha256(v)) { return Err(Error::bad_request("If-Match must name the current file hash")); }
    let staged = super::attachments::receive_with_empty(&db, &headers, body, true).await?;
    let media = media_type(&headers);
    let changed = blocking({
        let db = db.clone();
        move || db.replace_file_checked(&user, &id, &media, staged, expected)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct ContentQuery {
    /// Which version; absent or 0 is the current one.
    #[serde(default)]
    pub version: u32,
    #[serde(default)]
    pub inline: bool,
}

/// Download a file, or one of its versions.
pub async fn download(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
    Query(query): Query<ContentQuery>,
) -> Result<Response, Error> {
    let user = require_user(&db, &headers)?;
    let (name, version) = db.workspace_file(&user, &id, query.version)?;
    stream_blob(&db, &name, &version.media_type, &version.sha256, version.size, query.inline).await
}

/// A file's versions, oldest first.
pub async fn versions(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    Ok(Json(json!({ "versions": db.workspace_versions(&user, &id)? })))
}

/// Make an old version current again (as a new version).
pub async fn restore(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path((id, version)): Path<(String, u32)>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let changed = blocking({
        let db = db.clone();
        move || db.restore_version(&user, &id, version)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "entry": changed, "seq": seq(&db) })))
}

#[derive(Debug, Deserialize, Default)]
pub struct PromoteBody {
    /// A part id or number.
    pub part: String,
    /// A revision id or label; empty attaches to the part.
    #[serde(default)]
    pub revision: String,
    #[serde(default)]
    pub version: u32,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub note: String,
}

/// Promote a file to an attachment on a part or revision.
pub async fn promote(
    State(db): State<Shared>,
    headers: HeaderMap,
    Path(id): Path<String>,
    Json(body): Json<PromoteBody>,
) -> Result<Json<Value>, Error> {
    let user = require_user(&db, &headers)?;
    let ask = Promote {
        part: body.part,
        revision: body.revision,
        version: body.version,
        name: body.name,
        kind: body.kind,
        note: body.note,
    };
    let made = blocking({
        let db = db.clone();
        move || db.promote(&user, &id, &ask)
    })
    .await?;
    Ok(Json(json!({ "ok": true, "attachment": made, "seq": seq(&db) })))
}