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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Deferred workspace I/O batches.
use super::{
AuthorizedWorkspaceReadAccess, AuthorizedWorkspaceWriteAccess, PluginWorkspaceIoBudget,
PluginWorkspaceIoCommitError, PluginWorkspaceIoCompletion,
PluginWorkspaceIoIdentityMismatchSource, PluginWorkspaceIoReport,
PluginWorkspaceIoWorkerEnqueueError, PluginWorkspaceIoWorkerQueue,
PluginWorkspaceObserveOutcome, PluginWorkspaceReadByteLimit, PluginWorkspaceReadSuccess,
PluginWorkspaceWriteByteLimit, PluginWorkspaceWriteSuccess,
};
use super::{
access::{PluginWorkspaceReadToken, PluginWorkspaceWriteToken},
budget::{PluginWorkspaceIoRequestLedger, PluginWorkspaceNonDeferredReadPermit},
report::{PluginWorkspaceReadCompletion, PluginWorkspaceWriteCompletion},
};
use crate::{
fs_utils::{EscapedDisplayText, FilesystemConfig},
plugin::{PluginIdentity, WorkspacePath},
};
use std::fmt::{Debug, Formatter};
/// V1 workspace I/O execution policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PluginWorkspaceIoExecutionModel {
/// Host imports queue bounded workspace requests during a guest update, then execute them
/// synchronously through `fs_utils` only after the guest returns successfully.
DeferredSynchronous,
}
/// Workspace I/O accepted during one guest update but not yet committed to filesystem policy.
#[derive(Eq, PartialEq)]
pub struct PendingPluginWorkspaceIoBatch {
/// Shared request budget for deferred and task-style workspace work.
request_ledger: PluginWorkspaceIoRequestLedger,
/// Accepted workspace operations.
requests: Vec<PendingPluginWorkspaceIo>,
}
impl PendingPluginWorkspaceIoBatch {
/// Creates an empty pending workspace I/O batch.
///
/// The only v1 execution model is deferred synchronous I/O: requests are accepted while the
/// guest update is running, but no filesystem operation is performed until the batch is sealed
/// after successful guest return.
#[must_use]
pub const fn new(identity: PluginIdentity, budget: PluginWorkspaceIoBudget) -> Self {
Self::from_validated_budget(identity, budget)
}
/// Creates an empty pending workspace I/O batch from an already-validated budget proof.
#[must_use]
pub(in crate::plugin) const fn from_validated_budget(
identity: PluginIdentity,
budget: PluginWorkspaceIoBudget,
) -> Self {
Self {
request_ledger: PluginWorkspaceIoRequestLedger::new(identity, budget),
requests: Vec::new(),
}
}
/// Returns the v1 execution model for this batch.
#[must_use]
pub const fn execution_model(&self) -> PluginWorkspaceIoExecutionModel {
PluginWorkspaceIoExecutionModel::DeferredSynchronous
}
/// Returns the plugin identity for display and serialization.
#[must_use]
pub fn identity(&self) -> &str {
self.identity_proof().as_str()
}
/// Returns the validated identity retained before the successful-return boundary.
#[must_use]
pub const fn identity_proof(&self) -> &PluginIdentity {
self.request_ledger.identity_proof()
}
/// Queues a workspace read that has already passed plugin capability authorization.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoCommitError`] when the batch is full.
pub fn push_read(
&mut self,
access: AuthorizedWorkspaceReadAccess,
) -> Result<(), PluginWorkspaceIoCommitError> {
self.ensure_access_identity(access.identity_proof())?;
let token = access.into_policy_token();
self.push(PendingPluginWorkspaceIo::Read(token))
}
/// Queues a workspace write that has already passed plugin capability authorization.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoCommitError`] when the payload exceeds the write budget or the
/// batch is full.
pub fn push_write(
&mut self,
access: AuthorizedWorkspaceWriteAccess,
bytes: impl Into<Vec<u8>>,
) -> Result<(), PluginWorkspaceIoCommitError> {
self.ensure_access_identity(access.identity_proof())?;
let token = access.into_policy_token();
let payload = PluginWorkspaceWritePayload::try_new(
bytes,
self.request_ledger.max_write_bytes_limit(),
)?;
self.push(PendingPluginWorkspaceIo::Write { token, payload })
}
/// Returns the number of queued workspace operations.
#[must_use]
pub const fn request_count(&self) -> usize {
self.requests.len()
}
/// Returns requests charged against the cap but tracked outside this I/O batch.
#[must_use]
pub const fn non_deferred_request_count(&self) -> usize {
self.request_ledger.non_deferred_request_count()
}
/// Returns all workspace requests accepted during this update session.
#[must_use]
pub const fn accepted_request_count(&self) -> usize {
self.request_ledger
.accepted_request_count(self.request_count())
}
/// Returns the read byte cap shared by deferred reads and direct guest observations.
#[must_use]
pub const fn max_read_bytes(&self) -> u64 {
self.request_ledger.max_read_bytes()
}
/// Charges a non-queued direct observation against the per-update request cap.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoCommitError`] when the session has already spent its request
/// budget.
pub(in crate::plugin::host) fn charge_direct_observation(
&mut self,
) -> Result<PluginWorkspaceReadByteLimit, PluginWorkspaceIoCommitError> {
Ok(self.prepare_non_deferred_read()?.commit())
}
/// Reads a workspace file directly through filesystem policy for guest delivery.
///
/// Direct observations are not deferred I/O work, but they still belong to this update's
/// workspace request ledger. The access proof identity is checked before charging budget or
/// touching filesystem policy.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoCommitError`] when the access proof belongs to another plugin
/// or the session has already spent its request budget.
pub(in crate::plugin::host) fn observe_existing(
&mut self,
access: AuthorizedWorkspaceReadAccess,
filesystem: &FilesystemConfig,
) -> Result<PluginWorkspaceObserveOutcome, PluginWorkspaceIoCommitError> {
self.ensure_access_identity(access.identity_proof())?;
let max_read_bytes = self.charge_direct_observation()?;
let outcome = access
.into_policy_token()
.read_existing(filesystem, max_read_bytes)
.map(|file| {
PluginWorkspaceReadSuccess::new(
EscapedDisplayText::from_path(&file.path),
file.bytes,
)
});
Ok(PluginWorkspaceObserveOutcome::from_read_result(outcome))
}
/// Prepares a read request whose durable work is tracked by another pending batch.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoCommitError`] when the session has already spent its request
/// budget.
pub(in crate::plugin::host) fn prepare_non_deferred_read(
&mut self,
) -> Result<PluginWorkspaceNonDeferredReadPermit<'_>, PluginWorkspaceIoCommitError> {
self.request_ledger
.prepare_non_deferred_read(self.requests.len())
}
/// Seals workspace I/O after a guest update returns successfully.
#[must_use]
pub fn seal(self) -> SealedPluginWorkspaceIoBatch {
let Self {
request_ledger,
requests,
} = self;
let ledger = request_ledger.into_parts();
SealedPluginWorkspaceIoBatch {
identity: ledger.identity,
budget: ledger.budget,
requests,
}
}
/// Discards workspace I/O after a guest update fails before successful return.
#[must_use]
pub fn discard(self) -> PluginWorkspaceIoDiscardReport {
let Self {
request_ledger,
requests,
} = self;
let ledger = request_ledger.into_parts();
PluginWorkspaceIoDiscardReport {
identity: ledger.identity,
discarded_requests: requests.len(),
}
}
/// Queues one workspace operation.
fn push(
&mut self,
request: PendingPluginWorkspaceIo,
) -> Result<(), PluginWorkspaceIoCommitError> {
self.request_ledger
.ensure_deferred_request_budget(self.requests.len())?;
self.requests.push(request);
Ok(())
}
/// Checks that a workspace access proof belongs to this batch's plugin.
fn ensure_access_identity(
&self,
access_identity: &PluginIdentity,
) -> Result<(), PluginWorkspaceIoCommitError> {
if access_identity != self.identity_proof() {
return Err(PluginWorkspaceIoCommitError::IdentityMismatch {
mismatch_source: PluginWorkspaceIoIdentityMismatchSource::AccessProof,
batch_identity: self.identity_proof().clone(),
provided_identity: access_identity.clone(),
});
}
Ok(())
}
}
impl Debug for PendingPluginWorkspaceIoBatch {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PendingPluginWorkspaceIoBatch")
.field("identity", &self.identity_proof())
.field("execution_model", &self.execution_model())
.field("request_count", &self.request_count())
.field("request_ledger", &self.request_ledger)
.field(
"request_shapes",
&self
.requests
.iter()
.map(PendingPluginWorkspaceIo::shape)
.collect::<Vec<_>>(),
)
.finish()
}
}
/// Workspace I/O from a guest update that reached the successful-return boundary.
#[derive(Eq, PartialEq)]
pub struct SealedPluginWorkspaceIoBatch {
/// Stable plugin identity for diagnostics.
identity: PluginIdentity,
/// Per-update workspace I/O budget.
budget: PluginWorkspaceIoBudget,
/// Accepted workspace operations.
requests: Vec<PendingPluginWorkspaceIo>,
}
impl SealedPluginWorkspaceIoBatch {
/// Returns the plugin identity.
#[must_use]
pub fn identity(&self) -> &str {
self.identity_proof().as_str()
}
/// Returns the identity proof retained across the successful-return boundary.
#[must_use]
pub const fn identity_proof(&self) -> &PluginIdentity {
&self.identity
}
/// Returns the request count.
#[must_use]
pub const fn request_count(&self) -> usize {
self.requests.len()
}
/// Returns whether this sealed batch carries no filesystem-policy work.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.requests.is_empty()
}
/// Enqueues sealed workspace I/O for host-owned filesystem-policy execution.
///
/// Failed admission returns the still-sealed batch so callers can retry or explicitly discard
/// it without losing successful-return work as a side effect of queue saturation.
///
/// # Errors
///
/// Returns [`PluginWorkspaceIoWorkerEnqueueError`] when the worker queue rejects admission.
pub fn enqueue(
self,
queue: &mut PluginWorkspaceIoWorkerQueue,
) -> Result<(), PluginWorkspaceIoWorkerEnqueueError> {
queue.push(self)
}
/// Discards sealed workspace I/O that will not be retried before filesystem policy execution.
#[must_use]
pub fn discard(self) -> PluginWorkspaceIoDiscardReport {
let Self {
identity,
budget: _budget,
requests,
} = self;
PluginWorkspaceIoDiscardReport {
identity,
discarded_requests: requests.len(),
}
}
/// Executes sealed workspace I/O synchronously through `fs_utils`.
///
/// This is the v1 stepping stone before an async worker exists. It preserves the observable
/// async contract by keeping requests discardable until successful guest return and by routing
/// all filesystem access through policy tokens.
#[must_use]
pub fn execute_synchronous(self, filesystem: &FilesystemConfig) -> PluginWorkspaceIoReport {
let mut completions = Vec::with_capacity(self.requests.len());
for request in self.requests {
completions.push(match request {
PendingPluginWorkspaceIo::Read(token) => {
let path = WorkspacePath::from_ref(token.workspace_path());
let outcome = token
.read_existing(filesystem, self.budget.max_read_bytes_limit())
.map(|file| {
PluginWorkspaceReadSuccess::new(
EscapedDisplayText::from_path(&file.path),
file.bytes,
)
});
PluginWorkspaceIoCompletion::Read(PluginWorkspaceReadCompletion::new(
path, outcome,
))
}
PendingPluginWorkspaceIo::Write { token, payload } => {
let path = WorkspacePath::from_ref(token.workspace_path());
let outcome = token
.write_atomic(payload.as_bytes(), filesystem, payload.max_size())
.map(PluginWorkspaceWriteSuccess::new);
PluginWorkspaceIoCompletion::Write(PluginWorkspaceWriteCompletion::new(
path, outcome,
))
}
});
}
PluginWorkspaceIoReport::new(self.identity, completions)
}
}
impl Debug for SealedPluginWorkspaceIoBatch {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SealedPluginWorkspaceIoBatch")
.field("identity", &self.identity)
.field(
"execution_model",
&PluginWorkspaceIoExecutionModel::DeferredSynchronous,
)
.field("budget", &self.budget)
.field("request_count", &self.requests.len())
.field(
"request_shapes",
&self
.requests
.iter()
.map(PendingPluginWorkspaceIo::shape)
.collect::<Vec<_>>(),
)
.finish()
}
}
/// Report from discarding workspace I/O before filesystem policy execution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PluginWorkspaceIoDiscardReport {
/// Stable plugin identity for diagnostics.
identity: PluginIdentity,
/// Number of requests discarded before filesystem policy execution.
discarded_requests: usize,
}
impl PluginWorkspaceIoDiscardReport {
/// Returns the plugin identity for display and serialization.
#[must_use]
pub fn identity(&self) -> &str {
self.identity_proof().as_str()
}
/// Returns the validated identity retained by the discard report.
#[must_use]
pub const fn identity_proof(&self) -> &PluginIdentity {
&self.identity
}
/// Returns the number of discarded workspace I/O requests.
#[must_use]
pub const fn discarded_requests(&self) -> usize {
self.discarded_requests
}
}
/// Deferred workspace I/O operation.
#[derive(Eq, PartialEq)]
enum PendingPluginWorkspaceIo {
/// Deferred workspace read.
Read(PluginWorkspaceReadToken),
/// Deferred workspace write.
Write {
/// Filesystem-policy bridge token.
token: PluginWorkspaceWriteToken,
/// Payload already checked against the write byte cap.
payload: PluginWorkspaceWritePayload,
},
}
impl PendingPluginWorkspaceIo {
/// Returns a redacted diagnostic shape.
fn shape(&self) -> PendingPluginWorkspaceIoShape {
match self {
Self::Read(token) => PendingPluginWorkspaceIoShape::Read {
path_byte_len: token.workspace_relative_path().len(),
},
Self::Write { token, payload } => PendingPluginWorkspaceIoShape::Write {
path_byte_len: token.workspace_relative_path().len(),
byte_len: payload.len(),
},
}
}
}
/// Workspace artifact write payload accepted into a pending batch.
#[derive(Eq, PartialEq)]
pub(in crate::plugin::host::workspace_io) struct PluginWorkspaceWritePayload {
/// Payload bytes retained until the successful-return batch reaches filesystem policy.
bytes: Vec<u8>,
/// Cap that admitted these bytes.
max_size: PluginWorkspaceWriteByteLimit,
}
impl PluginWorkspaceWritePayload {
/// Builds a payload proof after checking the workspace write budget.
pub(in crate::plugin::host::workspace_io) fn try_new(
bytes: impl Into<Vec<u8>>,
max_size: PluginWorkspaceWriteByteLimit,
) -> Result<Self, PluginWorkspaceIoCommitError> {
let bytes = bytes.into();
let size = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
if size > max_size.get() {
return Err(PluginWorkspaceIoCommitError::PayloadTooLarge {
size,
max_size: max_size.get(),
});
}
Ok(Self { bytes, max_size })
}
/// Returns the admitted payload bytes.
pub(in crate::plugin::host::workspace_io) fn as_bytes(&self) -> &[u8] {
&self.bytes
}
/// Returns the admitted payload byte length.
pub(in crate::plugin::host::workspace_io) const fn len(&self) -> usize {
self.bytes.len()
}
/// Returns the write cap that admitted the payload.
pub(in crate::plugin::host::workspace_io) const fn max_size(
&self,
) -> PluginWorkspaceWriteByteLimit {
self.max_size
}
}
impl Debug for PluginWorkspaceWritePayload {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PluginWorkspaceWritePayload")
.field("byte_len", &self.len())
.field("max_size", &self.max_size.get())
.finish_non_exhaustive()
}
}
/// Redacted workspace I/O request shape.
#[derive(Clone, Debug, Eq, PartialEq)]
enum PendingPluginWorkspaceIoShape {
/// Deferred read request.
Read {
/// Path bytes.
path_byte_len: usize,
},
/// Deferred write request.
Write {
/// Path bytes.
path_byte_len: usize,
/// Payload byte length for writes.
byte_len: usize,
},
}