kcode-k1-web-code-ktool-service 0.1.2

Own per-user K1 Web coding services for Web-code Ktools
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
use kcode_k1_access::AccessContext;
use kcode_k1_groups::K1Groups;
use kcode_k1_objects::K1Objects;
use kcode_k1_web_code_authority::authorize_workspace;
pub use kcode_k1_web_code_document::{CodeDocument, Language};
use kcode_k1_web_code_runtime::{K1WebCodeRuntime, RuntimeError};
pub use kcode_k1_web_code_runtime::{
    RuntimeConfig as ServiceConfig, RuntimeRevisions as ServiceRevisions,
};
pub use kcode_k1_web_code_session::{CheckEvidence, DocumentPart, OpenedLibrary};
use kcode_k1_web_code_session::{SessionError, SessionScope};
pub use kcode_k1_web_coding::{CheckOutcome, PublishResult};
use kcode_k1_web_coding::{K1WebCoding, WebCodingError};
use kcode_k1_web_package::{SourcePackage, WebFamily, WebId};
use kcode_k1_web_projection::K1WebProjection;
use kcode_k1_web_source_object::{CaptureStateError, SourceObjectCapture};
use std::fmt::{Display, Formatter};
use std::sync::Arc;

pub use kcode_k1_objects::TxId;

const EMPTY_DOCUMENTATION: &[u8] = b"<!-- k1-web/v1\n{\"dependencies\":[]}\n-->\n";
type ServiceResult<T> = Result<T, ServiceError>;

pub struct FreshCheck {
    pub outcome: CheckOutcome,
    evidence: CheckEvidence,
}

impl FreshCheck {
    pub fn evidence(&self) -> &CheckEvidence {
        &self.evidence
    }
}

pub struct PublishCompletion {
    pub source_object: TxId,
    pub publication: PublishResult,
    pub precheck: Option<CheckOutcome>,
    pub evidence: CheckEvidence,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ServiceFailure {
    State,
    Authorization,
    WorkspaceDenied,
    SourceUnavailable,
    LanguageRequired,
    LanguageMismatch,
    ForeignHandle,
    StaleSource,
    InvalidDocument,
    CheckFailed,
    SourcePreservation,
    PublicReleaseDenied,
    Publication,
    Dependency,
}

#[derive(Debug)]
pub struct ServiceError {
    failure: ServiceFailure,
    message: String,
    source_object: Option<TxId>,
    session_error: Option<SessionError>,
}

impl ServiceError {
    pub fn failure(&self) -> ServiceFailure {
        self.failure
    }

    pub fn source_object(&self) -> Option<TxId> {
        self.source_object
    }

    fn new(failure: ServiceFailure, message: impl Into<String>) -> Self {
        Self {
            failure,
            message: message.into(),
            source_object: None,
            session_error: None,
        }
    }

    fn from_session(error: SessionError) -> Self {
        let failure = match &error {
            SessionError::ForeignHandle => ServiceFailure::ForeignHandle,
            SessionError::StaleSource => ServiceFailure::StaleSource,
            SessionError::InvalidDocument(_) => ServiceFailure::InvalidDocument,
        };
        let message = match &error {
            SessionError::ForeignHandle => {
                "opened library does not belong to this service and user".to_owned()
            }
            SessionError::StaleSource => {
                "opened library is not the current exact source".to_owned()
            }
            SessionError::InvalidDocument(message) => message.clone(),
        };
        Self {
            failure,
            message,
            source_object: None,
            session_error: Some(error),
        }
    }

    fn with_source_object(mut self, source_object: Option<TxId>) -> Self {
        self.source_object = source_object;
        self
    }
}

impl Display for ServiceError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ServiceError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.session_error
            .as_ref()
            .map(|error| error as &(dyn std::error::Error + 'static))
    }
}

struct Inner {
    runtime: K1WebCodeRuntime,
    groups: Arc<K1Groups>,
    objects: Arc<K1Objects>,
    session: SessionScope,
}

#[derive(Clone)]
pub struct K1WebCodeKtoolService {
    inner: Arc<Inner>,
}

impl K1WebCodeKtoolService {
    pub fn new(
        config: ServiceConfig,
        groups: Arc<K1Groups>,
        objects: Arc<K1Objects>,
        projection: Arc<K1WebProjection>,
    ) -> Self {
        Self {
            inner: Arc::new(Inner {
                runtime: K1WebCodeRuntime::new(config, projection),
                groups,
                objects,
                session: SessionScope::new(),
            }),
        }
    }

    pub fn docs(&self, context: &AccessContext, id: &WebId) -> ServiceResult<Option<String>> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            let source = coding
                .view(id, &|family| self.authorize(context, family))
                .map_err(service_coding_error)?;
            source
                .map(|source| {
                    let opened = self
                        .inner
                        .session
                        .recover(user, source)
                        .map_err(ServiceError::from_session)?;
                    String::from_utf8(opened.document().documentation().to_vec()).map_err(|error| {
                        ServiceError::new(ServiceFailure::InvalidDocument, error.to_string())
                    })
                })
                .transpose()
        })
    }

    pub fn open(
        &self,
        context: &AccessContext,
        id: &WebId,
        language: Option<Language>,
    ) -> ServiceResult<OpenedLibrary> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            self.require_authorized(context, id.family())?;
            let current = coding
                .view(id, &|family| self.authorize(context, family))
                .map_err(service_coding_error)?;
            let candidate = match current {
                Some(source) => {
                    let recovered = self
                        .inner
                        .session
                        .recover(user, source)
                        .map_err(ServiceError::from_session)?;
                    if language.is_some_and(|value| value != recovered.document().language()) {
                        return Err(ServiceError::new(
                            ServiceFailure::LanguageMismatch,
                            "supplied language does not match the current document",
                        ));
                    }
                    recovered
                        .document()
                        .to_source_package()
                        .map_err(document_error)?
                }
                None => CodeDocument::new(
                    id.clone(),
                    EMPTY_DOCUMENTATION.to_vec(),
                    language.ok_or_else(|| {
                        ServiceError::new(
                            ServiceFailure::LanguageRequired,
                            "language is required for an absent library",
                        )
                    })?,
                    Vec::new(),
                )
                .map_err(document_error)?
                .to_source_package()
                .map_err(document_error)?,
            };
            let written = coding
                .write(&candidate, &|family| self.authorize(context, family))
                .map_err(service_coding_error)?;
            self.inner
                .session
                .refresh(user, written)
                .map_err(ServiceError::from_session)
        })
    }

    pub fn validate_current(
        &self,
        context: &AccessContext,
        opened: &OpenedLibrary,
    ) -> ServiceResult<()> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            self.current_source(context, coding, user, opened)?;
            Ok(())
        })
    }

    pub fn overwrite(
        &self,
        context: &AccessContext,
        opened: &OpenedLibrary,
        part: DocumentPart,
        contents: String,
    ) -> ServiceResult<OpenedLibrary> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            let current = self.current_source(context, coding, user, opened)?;
            let candidate = self
                .inner
                .session
                .replacement(user, opened, current.as_ref(), part, contents)
                .map_err(ServiceError::from_session)?;
            let written = coding
                .write(&candidate, &|family| self.authorize(context, family))
                .map_err(service_coding_error)?;
            self.inner
                .session
                .refresh(user, written)
                .map_err(ServiceError::from_session)
        })
    }

    pub fn check(
        &self,
        context: &AccessContext,
        opened: &OpenedLibrary,
    ) -> ServiceResult<FreshCheck> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            let current = self.current_source(context, coding, user, opened)?;
            let outcome = coding
                .check_fresh(opened.document().id(), &|family| {
                    self.authorize(context, family)
                })
                .map_err(service_coding_error)?;
            let evidence = self
                .inner
                .session
                .mint_evidence(user, opened, current.as_ref())
                .map_err(ServiceError::from_session)?;
            Ok(FreshCheck { outcome, evidence })
        })
    }

    pub fn publish(
        &self,
        context: &AccessContext,
        opened: &OpenedLibrary,
        evidence: Option<&CheckEvidence>,
    ) -> ServiceResult<PublishCompletion> {
        let user = user_bytes(context);
        self.with_coding(user, |coding| {
            let current = self.current_source(context, coding, user, opened)?;
            let evidence_matches = evidence
                .map(|value| {
                    self.inner
                        .session
                        .evidence_matches(user, opened, current.as_ref(), value)
                        .map_err(ServiceError::from_session)
                })
                .transpose()?
                .unwrap_or(false);
            let precheck = if evidence_matches {
                None
            } else {
                Some(
                    coding
                        .check_fresh(opened.document().id(), &|family| {
                            self.authorize(context, family)
                        })
                        .map_err(service_coding_error)?,
                )
            };
            let completion_evidence = self
                .inner
                .session
                .mint_evidence(user, opened, current.as_ref())
                .map_err(ServiceError::from_session)?;
            let source_object = SourceObjectCapture::new(self.inner.objects.as_ref());
            let publication = coding.publish_with_source_preservation(
                opened.document().id(),
                &|family| self.authorize(context, family),
                &|source, _digest| source_object.preserve(source),
                &|source, _digest| self.authorize(context, source.id().family()),
            );
            let publication = match publication {
                Ok(value) => value,
                Err(error) => {
                    let captured = source_object.captured();
                    return Err(service_coding_error(error).with_source_object(captured));
                }
            };
            let source_object = source_object.finish().map_err(source_capture_error)?;
            Ok(PublishCompletion {
                source_object,
                publication,
                precheck,
                evidence: completion_evidence,
            })
        })
    }

    fn with_coding<T>(
        &self,
        user: [u8; 12],
        operation: impl FnOnce(&mut K1WebCoding) -> ServiceResult<T>,
    ) -> ServiceResult<T> {
        self.inner
            .runtime
            .with_user(user, |coding| Ok(operation(coding)))
            .map_err(service_runtime_error)?
    }

    fn authorize(&self, context: &AccessContext, family: &WebFamily) -> Result<bool, String> {
        authorize_workspace(context, &self.inner.groups, family)
    }

    fn require_authorized(&self, context: &AccessContext, family: &WebFamily) -> ServiceResult<()> {
        match self.authorize(context, family) {
            Ok(true) => Ok(()),
            Ok(false) => Err(ServiceError::new(
                ServiceFailure::WorkspaceDenied,
                "workspace is denied",
            )),
            Err(message) => Err(ServiceError::new(ServiceFailure::Authorization, message)),
        }
    }

    fn current_source(
        &self,
        context: &AccessContext,
        coding: &K1WebCoding,
        user: [u8; 12],
        opened: &OpenedLibrary,
    ) -> ServiceResult<Arc<SourcePackage>> {
        let current = coding
            .view(opened.document().id(), &|family| {
                self.authorize(context, family)
            })
            .map_err(service_coding_error)?
            .ok_or_else(|| ServiceError::from_session(SessionError::StaleSource))?;
        self.inner
            .session
            .validate(user, opened, current.as_ref())
            .map_err(ServiceError::from_session)?;
        Ok(current)
    }
}

fn user_bytes(context: &AccessContext) -> [u8; 12] {
    *context.user().as_tx_id().as_bytes()
}

fn document_error(error: impl Display) -> ServiceError {
    ServiceError::new(ServiceFailure::InvalidDocument, error.to_string())
}

fn source_capture_error(error: CaptureStateError) -> ServiceError {
    let message = match error {
        CaptureStateError::Poisoned => "source object capture mutex poisoned",
        CaptureStateError::Missing => "publication completed without a captured source object",
    };
    ServiceError::new(ServiceFailure::State, message)
}

fn service_runtime_error(error: RuntimeError) -> ServiceError {
    match error {
        RuntimeError::Coding(error) => service_coding_error(error),
        RuntimeError::LockPoisoned(message) => {
            let message = if message == "runtime slot map mutex poisoned" {
                "service slot map mutex poisoned".to_owned()
            } else {
                message
            };
            ServiceError::new(ServiceFailure::State, message)
        }
    }
}

fn service_coding_error(error: WebCodingError) -> ServiceError {
    let failure = match &error {
        WebCodingError::Authorization(_) => ServiceFailure::Authorization,
        WebCodingError::WorkspaceDenied => ServiceFailure::WorkspaceDenied,
        WebCodingError::CandidateUnavailable => ServiceFailure::SourceUnavailable,
        WebCodingError::CheckFailed(_) => ServiceFailure::CheckFailed,
        WebCodingError::SourcePreservation(_) => ServiceFailure::SourcePreservation,
        WebCodingError::PublicReleaseDenied => ServiceFailure::PublicReleaseDenied,
        WebCodingError::Projection(_) | WebCodingError::ProjectionAfterSubmit { .. } => {
            ServiceFailure::Publication
        }
        WebCodingError::State(_)
        | WebCodingError::Cache(_)
        | WebCodingError::DependencyUnavailable
        | WebCodingError::Podman(_) => ServiceFailure::Dependency,
    };
    ServiceError::new(failure, error.to_string())
}