mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 08:39:02 +03:00
docs(cli-rs): explain plugin loading and approval by artifact
Keep the file-descriptor, quarantine, dependency and crash-record constraints beside the code they govern. Drop step names, reviewer annotations and TS line numbers. Nine loader and record tests passed.
This commit is contained in:
@@ -1,25 +1,5 @@
|
||||
//! Containment of plugin calls (synthesis 4.4 and 4.5, phase P4c). Every call into a plugin, on either path, runs
|
||||
//! through [`Monitor::call`]: it reads the clock before and after, so the plugin cannot opt out and does not report its
|
||||
//! own time, and while a run record is attached it names the call in the record for the watchdog and a restart. On
|
||||
//! Linux the time the thread waited on a run queue meanwhile is not the plugin's: a loaded machine's, it is not charged.
|
||||
//! The overrun is judged by the CPU time the thread used in the call ([`thread_cpu`]), where the OS can say: a page
|
||||
//! fault served from swap or disk, a wait on a lock or a sleep is the machine's, not the plugin's work (FT-13). Wall
|
||||
//! time stays the hang watchdog's.
|
||||
//!
|
||||
//! The budget acts after a call returns, because a call on the UI thread cannot be stopped:
|
||||
//!
|
||||
//! - **frame budget**: [`Limits::frame`] per plugin per frame, summed over its calls; [`Limits::all`] for all plugins
|
||||
//! together. A frame is what runs from one paint to the next: the host closes the open frames at the start of each
|
||||
//! paint ([`Monitor::close`]), and a call in a later frame closes its plugin's frame too.
|
||||
//! - **slow**: over the frame budget in more than [`Limits::slow`] of the last [`Limits::window`] frames the plugin ran
|
||||
//! in. It informs only, once a session, because wall time on a loaded machine is noisy.
|
||||
//! - **overrun**: one call that used more CPU than [`Limits::overrun`] (wall time less the run-queue wait where the OS
|
||||
//! tells no CPU time). The caller fails an external plugin; for a built-in it is a host
|
||||
//! bug, logged and counted ([`Monitor::host_overruns`]). A plugin's first call after `setup` is exempt, because its
|
||||
//! pages are cold. Loading a library, `setup` and `dispose` are timed and do not count: they are its load.
|
||||
//!
|
||||
//! Each build of a plugin has its own slot and statistics: a reload starts afresh.
|
||||
//! - **hang**: a call not returned after [`Limits::hang`]; the watchdog acts ([`watchdog`]).
|
||||
//! Measures plugin calls using the host clock. The monitor tracks slow calls, frame budgets and mailbox pressure;
|
||||
//! the parent uses the run record to attribute a crash to the active build.
|
||||
|
||||
pub mod record;
|
||||
pub mod watchdog;
|
||||
@@ -73,8 +53,7 @@ pub fn filter_panics() {
|
||||
});
|
||||
}
|
||||
|
||||
/// The limits of the budget. These are starting values (synthesis 7, decision 5); `OPENCODE_PLUGIN_LIMITS` changes
|
||||
/// them ([`Limits::parse`]).
|
||||
/// Plugin call budgets. Override the defaults with `OPENCODE_PLUGIN_LIMITS`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Per plugin per frame.
|
||||
@@ -220,9 +199,7 @@ pub struct Monitor {
|
||||
record: OnceCell<(Arc<Record>, Instant)>,
|
||||
/// Told when a call returns whose hang notice the watchdog painted: the plugin and how long the call took.
|
||||
on_notice: RefCell<Option<Rc<OnNotice>>>,
|
||||
/// The plugins whose slow news the user was told this session, by ID: once a plugin and session, whatever the
|
||||
/// cause and however often it is enabled again or rebuilt (4.14 `reported-once`; final review big-boi 10). Each
|
||||
/// build's state, counters and causes stay its own.
|
||||
/// Report a slow plugin once per plugin ID per session, even after reload.
|
||||
told: RefCell<std::collections::HashSet<String>>,
|
||||
}
|
||||
|
||||
@@ -250,15 +227,13 @@ struct Stats {
|
||||
host_total: Duration,
|
||||
/// All its calls since its setup, but the setup's.
|
||||
calls_total: Duration,
|
||||
/// Its calls in a frame of the host's count, whatever closed P4c's window: what the scheduler's budget reads.
|
||||
/// Host frame counter used by the scheduler's budget.
|
||||
counted: Option<(u64, Duration)>,
|
||||
/// The frames at the end of which its mailbox was full, the last [`Limits::window`] (synthesis 4.2, reviews
|
||||
/// bigboi 10 and carbon 5.4); whether that was told; and the sends its mailbox refused so far.
|
||||
/// Full-mailbox frames within the reporting window, notification status and refused sends.
|
||||
backlog: VecDeque<u64>,
|
||||
told_backlog: bool,
|
||||
refused: u64,
|
||||
/// Whether the backlog made it slow when the monitor last looked: a change of it is a change of slow too (review
|
||||
/// carbon-12).
|
||||
/// Whether the backlog made it slow when the monitor last looked: a change of it is a change of slow too.
|
||||
backlog_slow: bool,
|
||||
}
|
||||
|
||||
@@ -392,8 +367,7 @@ impl Monitor {
|
||||
|
||||
/// The frame calls count in now. OpenTUI counts a paint's frame up after its animations and deferred work and
|
||||
/// before its layout and draws; a call inside the frame ([`in_frame`]: `layout`, a canvas's draw) counts in the
|
||||
/// frame the paint started in. So a frame is a paint's calls and the calls since the paint before it (review
|
||||
/// carbon 4.1).
|
||||
/// frame the paint started in. So a frame is a paint's calls and the calls since the paint before it.
|
||||
pub fn frame(&self) -> u64 {
|
||||
self.painted().saturating_sub(u64::from(IN_FRAME.with(Cell::get)))
|
||||
}
|
||||
@@ -407,7 +381,7 @@ impl Monitor {
|
||||
/// closes as [`Monitor::close`] does: the calls of a timer's tick with nothing to paint count as one frame, not
|
||||
/// summed with every later tick until a paint comes. `None`, and nothing ends, when a call that is no timer's runs
|
||||
/// in the frame open now: its time stays the scheduler's ([`Monitor::spent`]) until a paint ends the frame, as for
|
||||
/// any call (big-boi tm-1).
|
||||
/// any call.
|
||||
pub fn close_idle(&self, painted: u64) -> Option<Vec<(String, String)>> {
|
||||
if self.plain.get() == Some(self.frame()) {
|
||||
return None;
|
||||
@@ -431,7 +405,7 @@ impl Monitor {
|
||||
let limits = self.limits();
|
||||
self.all.get().is_some_and(|(_, sum)| sum > limits.all)
|
||||
|| self.plugins.borrow().iter().any(|stats| {
|
||||
// A backlog that makes it slow ends with frames, which the closes must see (review carbon-12).
|
||||
// A backlog that makes it slow ends with frames, which the closes must see.
|
||||
stats.window.is_some_and(|(_, sum)| sum > limits.frame) || stats.backlog_slow
|
||||
})
|
||||
}
|
||||
@@ -471,7 +445,7 @@ impl Monitor {
|
||||
|
||||
/// The slot of `artifact`, made on first use: each build has its own. A library is opened (and its load timed)
|
||||
/// before its ID is known: its build keeps that one slot once it is named, so a crash in its load and in its
|
||||
/// activation names the same artifact (final review big-boi 11).
|
||||
/// activation names the same artifact.
|
||||
pub fn slot(&self, artifact: &Artifact) -> Slot {
|
||||
let mut plugins = self.plugins.borrow_mut();
|
||||
if let Some(index) = plugins.iter().position(|stats| stats.artifact == *artifact) {
|
||||
@@ -504,9 +478,8 @@ impl Monitor {
|
||||
}
|
||||
|
||||
/// Whether a crash in a call of `slot` names its artifact: always without a record, as no parent restarts the
|
||||
/// client then. An external build is named by its build, its target and digest, whatever ID the record could hold
|
||||
/// beside them; a built-in by its ID. An external build the record cannot name is not admitted (final review
|
||||
/// big-boi 11; re-review: the same build loaded again after its ID was too long to hold).
|
||||
/// client then. An external build is named by its build, its target and digest, whatever ID the record could
|
||||
/// hold beside them; a built-in by its ID. An external build the record cannot name is not admitted.
|
||||
pub fn attributed(&self, slot: Slot) -> bool {
|
||||
let Some((record, _)) = self.record.get() else { return true };
|
||||
let plugins = self.plugins.borrow();
|
||||
@@ -552,12 +525,8 @@ impl Monitor {
|
||||
(value, self.account(slot, kind, charged, cpu))
|
||||
}
|
||||
|
||||
/// Runs `work`, the host's own work for the plugin in `slot`'s nodes (building them, laying out a list's window,
|
||||
/// copying a decoded image in), timed apart from the plugin's calls: it is not in the plugin's frame budget, the
|
||||
/// limits of 4.2 bound it, and a slow plugin's details show it beside its calls (synthesis 4.4, "host time for
|
||||
/// plugin X").
|
||||
/// Work of another plugin nested in it (a nested slot's view and the host's work for its nodes) is that plugin's,
|
||||
/// and not this one's (review carbon 5.2).
|
||||
/// Times host-side work separately from plugin calls. Rendering widgets, laying out a list and copying an image
|
||||
/// must not consume the plugin's call budget.
|
||||
pub fn host(&self, slot: Slot, work: &mut dyn FnMut()) {
|
||||
let clock = self.clock.borrow().clone();
|
||||
self.nested.borrow_mut().push(Duration::ZERO);
|
||||
@@ -654,8 +623,8 @@ impl Monitor {
|
||||
}
|
||||
|
||||
/// A paint starts: every frame before the one now open ends; the open one goes on through the paint, so a paint
|
||||
/// does not cut one frame's calls in two, and ends at a later paint (review carbon 4.1). Returns the plugins that
|
||||
/// became slow, with what a slow frame costs.
|
||||
/// does not cut one frame's calls in two, and ends at a later paint. Returns the plugins that became slow, with
|
||||
/// what a slow frame costs.
|
||||
pub fn close(&self) -> Vec<(String, String)> {
|
||||
self.closing.set(false);
|
||||
let (limits, frame) = (self.limits(), self.frame());
|
||||
@@ -677,7 +646,7 @@ impl Monitor {
|
||||
news
|
||||
}
|
||||
|
||||
/// Whether a plugin became slow or stopped being slow since the last call, which the plugin list shows (P6b).
|
||||
/// Whether a plugin became slow or stopped being slow since the last call, which the plugin list shows.
|
||||
pub fn take_flipped(&self) -> bool {
|
||||
// Every plugin's flag is taken, not only up to the first that is set.
|
||||
let mut flipped = false;
|
||||
|
||||
@@ -1,28 +1,9 @@
|
||||
//! The run record (synthesis 4.5): one private mapped file per client, which the parent creates and keeps. Around
|
||||
//! every plugin call the host stores which plugin and which call runs. It also holds what a restart needs: the session
|
||||
//! on screen and the composer's draft, written as one snapshot whenever either changes. After a crash or a hang the
|
||||
//! parent reads what it says, and hands it to the next client in that client's own record.
|
||||
//! Shared crash record for the client, its parent and watchdog. Each atomic word has one access type.
|
||||
//! Plugin identity slots publish their checksum between calls; a checksum mismatch identifies no plugin.
|
||||
//! The session and draft use two slots: commit the new slot only after writing the complete snapshot.
|
||||
//!
|
||||
//! Every field has one access type and fields never overlap, so the UI thread, the watchdog and the parent may use the
|
||||
//! record at once:
|
||||
//!
|
||||
//! - **Words** (`AtomicU64`): the call state with its generation, the running call, its start, the call the
|
||||
//! watchdog claimed, the call whose notice it painted, the committed snapshot, whether the terminal was taken.
|
||||
//! - **Names** (bytes, published by a checksum word): each plugin slot's identity, written before the slot's first
|
||||
//! call, and once more when an external build that loaded before its ID was known is named with it (final review
|
||||
//! big-boi 11): between calls, so no crash names a slot while it is written. An identity is the plugin's ID and, for
|
||||
//! an external plugin, its target and build, so a crash names the artifact and not only an ID another plugin may
|
||||
//! share. A build whose identity the record cannot hold is not admitted ([`Record::holds`]).
|
||||
//! - **Snapshots** (bytes, two slots): the session and the draft. A writer fills the slot that is not committed, then
|
||||
//! commits it with one word, so a crash in the middle leaves the previous whole snapshot.
|
||||
//! - **Handoff** (bytes): what the parent tells the next client: the crash it restarts after, and safe mode.
|
||||
//!
|
||||
//! A call's life: `enter` stores the call and its start, then the state `running(g)`; `leave` swaps `running(g)` for
|
||||
//! `idle(g)`. The watchdog ends a client only after it swapped `running(g)` for `hung(g)`: a call that returned first
|
||||
//! keeps it from killing the client, and once it won, the call it claimed is the one the record names.
|
||||
//!
|
||||
//! A plugin can still write the page (a wild write): checksums make garbage name nobody. A valid wrong name cannot be
|
||||
//! told from a right one, and a crash names the last call, not the cause.
|
||||
//! The watchdog may terminate the client only after claiming the same running call generation. A successful
|
||||
//! return wins that race by marking the generation idle. The record identifies the last call, not the cause.
|
||||
|
||||
// The record views its mapping as atomics: each view below says why it is sound.
|
||||
#![allow(unsafe_code)]
|
||||
@@ -84,13 +65,13 @@ pub const KINDS: &[&str] = &[
|
||||
"update",
|
||||
"unmount",
|
||||
"draw",
|
||||
// P3: a surface's `layout` and its scroll handler.
|
||||
// a surface's `layout` and its scroll handler.
|
||||
"layout",
|
||||
"on-scroll",
|
||||
// P2: a key, paste, pointer, hover or close event to a surface's or a layer's handler, and a select's search.
|
||||
// a key, paste, pointer, hover or close event to a surface's or a layer's handler, and a select's search.
|
||||
"handle",
|
||||
"search",
|
||||
// P6b: the handlers of a change of the plugins the host lists.
|
||||
// the handlers of a change of the plugins the host lists.
|
||||
"on-plugins",
|
||||
// await-cancel: the handlers of a request its mount's close cancelled.
|
||||
"on-cancelled",
|
||||
|
||||
@@ -10,8 +10,6 @@ fn fault() -> Artifact {
|
||||
Artifact::external("example.fault", "/plugins/fault", "00000000deadbeef")
|
||||
}
|
||||
|
||||
// Expected: inside a call the record names its build (ID, target, digest) and call; after it, nobody. A built-in is
|
||||
// named by its ID alone, so a crash in it is never taken for an external build of the same ID.
|
||||
#[test]
|
||||
fn a_crash_names_the_build_and_the_call() {
|
||||
let (_dir, record) = record();
|
||||
@@ -27,9 +25,6 @@ fn a_crash_names_the_build_and_the_call() {
|
||||
assert!(record.leave(builtin));
|
||||
}
|
||||
|
||||
// Expected (bigboi 6, carbon 1): the watchdog claims a call only while it runs. A call that returned first keeps it
|
||||
// from claiming, so a client that is not hung is never ended; once it claimed, the call cannot leave, and the record
|
||||
// names the claimed call even if another one's word were written later.
|
||||
#[test]
|
||||
fn the_watchdog_claims_only_a_running_call() {
|
||||
let (_dir, record) = record();
|
||||
@@ -49,8 +44,6 @@ fn the_watchdog_claims_only_a_running_call() {
|
||||
);
|
||||
}
|
||||
|
||||
// Expected: a coherent read names nothing while the state and the call disagree: a stale start cannot pair with
|
||||
// another call's identity.
|
||||
#[test]
|
||||
fn a_torn_read_names_nobody() {
|
||||
let (_dir, record) = record();
|
||||
@@ -64,8 +57,6 @@ fn a_torn_read_names_nobody() {
|
||||
assert_eq!(record.running(), None, "a call word that fails its checksum names nobody");
|
||||
}
|
||||
|
||||
// Expected (carbon 6, bigboi 4): identities are kept whole or not at all. One too long for an entry stays unnamed
|
||||
// rather than be cut to a prefix another plugin may have; a slot past the table is unnamed; flipped bytes name nobody.
|
||||
#[test]
|
||||
fn an_identity_is_whole_or_unnamed() {
|
||||
let (_dir, record) = record();
|
||||
@@ -85,8 +76,6 @@ fn an_identity_is_whole_or_unnamed() {
|
||||
assert_eq!(record.named(1), Some(fault()));
|
||||
}
|
||||
|
||||
// Expected (bigboi 8): a snapshot is published whole. A writer interrupted while it fills the other slot leaves the
|
||||
// previous snapshot readable; a draft too long to keep is dropped, and says so.
|
||||
#[test]
|
||||
fn a_snapshot_survives_a_crash_in_the_middle_of_a_write() {
|
||||
let (_dir, record) = record();
|
||||
@@ -112,7 +101,6 @@ fn a_snapshot_survives_a_crash_in_the_middle_of_a_write() {
|
||||
assert_eq!(record.snapshot(), Some(exact));
|
||||
}
|
||||
|
||||
// Expected: the handoff reads back as written, and garbage reads as no handoff.
|
||||
#[test]
|
||||
fn the_handoff_reads_back() {
|
||||
let (_dir, record) = record();
|
||||
@@ -130,8 +118,6 @@ fn the_handoff_reads_back() {
|
||||
assert_eq!(record.handoff(), Handoff::default());
|
||||
}
|
||||
|
||||
// Expected (bigboi 7): a record is opened only from a file that is one, and a second mapping of the same file (the
|
||||
// client's, and the parent's that reads it after) sees the same words.
|
||||
#[test]
|
||||
fn a_handed_over_record_is_the_same_record() {
|
||||
let (dir, record) = record();
|
||||
@@ -145,8 +131,6 @@ fn a_handed_over_record_is_the_same_record() {
|
||||
assert!(Record::open(stranger).is_err());
|
||||
}
|
||||
|
||||
// Expected (carbon 1): the watchdog never pairs one call's identity or start with another call's generation, however
|
||||
// the UI thread's stores and its reads interleave. Each call here has slot and start that follow from its generation.
|
||||
#[test]
|
||||
fn a_running_call_is_read_whole_under_contention() {
|
||||
let (_dir, record) = record();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `budget` (synthesis 4.14): the slow state, the overrun and the hang follow the rule of 4.4 exactly at each
|
||||
//! boundary. The clock and the frame counter are injected, so nothing sleeps.
|
||||
//! `budget`: the slow state, the overrun and the hang follow the rule of 4.4 exactly at each boundary. The clock and
|
||||
//! the frame counter are injected, so nothing sleeps.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
@@ -55,8 +55,6 @@ impl Bench {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (4.4): slow is over the frame budget in more than 12 of the last 120 frames the plugin ran in. 12 is not
|
||||
// slow and 13 is; the news comes once, as the frame that makes it slow ends, and says what a slow frame costs.
|
||||
#[test]
|
||||
fn twelve_slow_frames_of_120_are_not_slow_and_thirteen_are() {
|
||||
for (over, slow) in [(12, false), (13, true)] {
|
||||
@@ -70,8 +68,6 @@ fn twelve_slow_frames_of_120_are_not_slow_and_thirteen_are() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected: the frame budget is per frame, summed over the calls: exactly 1 ms is in it, 1 ms and 1 ns is over it,
|
||||
// and two calls of 0.6 ms in one frame are over it.
|
||||
#[test]
|
||||
fn the_frame_budget_is_a_sum_and_its_limit_is_inside() {
|
||||
for (calls, over) in [
|
||||
@@ -90,8 +86,6 @@ fn the_frame_budget_is_a_sum_and_its_limit_is_inside() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected: the window is the last 120 frames the plugin ran in. Frames without a call of it do not count, old ones
|
||||
// fall out and the flag clears, and a plugin that is slow again is not told twice in a session.
|
||||
#[test]
|
||||
fn the_window_rolls_and_the_news_comes_once_a_session() {
|
||||
let bench = Bench::new();
|
||||
@@ -121,8 +115,6 @@ fn the_window_rolls_and_the_news_comes_once_a_session() {
|
||||
assert!(!bench.monitor.is_slow("p"));
|
||||
}
|
||||
|
||||
// Expected: the record stamps a call with the monotonic clock, which the watchdog reads, also while a test injects the
|
||||
// budget's clock: a call that started now has run for no time, however far the injected clock is.
|
||||
#[test]
|
||||
fn the_record_keeps_the_watchdogs_clock() {
|
||||
let bench = Bench::new();
|
||||
@@ -135,8 +127,6 @@ fn the_record_keeps_the_watchdogs_clock() {
|
||||
assert!(started.is_some_and(|started| started < 60_000), "{started:?}");
|
||||
}
|
||||
|
||||
// Expected (4.4): one call over 100 ms is an overrun, 100 ms is not. The first call after `setup` is exempt, as its
|
||||
// pages are cold, and only that one; `setup` and `dispose` never are overruns and count for no frame.
|
||||
#[test]
|
||||
fn an_overrun_is_one_call_over_100_ms_and_a_cold_first_call_is_exempt() {
|
||||
let bench = Bench::new();
|
||||
@@ -166,9 +156,6 @@ fn an_overrun_is_one_call_over_100_ms_and_a_cold_first_call_is_exempt() {
|
||||
assert!(!fresh.monitor.is_slow("p"));
|
||||
}
|
||||
|
||||
// Expected: the time the thread waited on a run queue during a call is the machine's load, not the plugin's, so it is
|
||||
// not charged: 150 ms with 50 ms of it queued is 100 ms and no overrun, with 50 ms less a nanosecond it is one. Time
|
||||
// queued before the call is not the call's.
|
||||
#[test]
|
||||
fn time_on_a_run_queue_is_not_charged() {
|
||||
for (waited, overrun) in [(Duration::from_millis(50), false), (Duration::from_millis(50) - NS, true)] {
|
||||
@@ -187,10 +174,6 @@ fn time_on_a_run_queue_is_not_charged() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (FT-13): the overrun judges the CPU time the call used, where the OS tells it. A call that blocks for 250 ms
|
||||
// without the CPU (a sleep, as a page fault served from swap, a lock or a slow disk is) is no overrun, though its wall
|
||||
// time is over the limit; that wall time stays in what the frame budget and the slow report count. One that keeps the
|
||||
// CPU for 150 ms is an overrun. On the real clocks.
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn an_overrun_is_judged_by_cpu_time_not_wall_time() {
|
||||
@@ -211,8 +194,6 @@ fn an_overrun_is_judged_by_cpu_time_not_wall_time() {
|
||||
assert!(busy.cpu.is_some_and(|cpu| cpu >= Duration::from_millis(150)) && busy.overrun, "{busy:?}");
|
||||
}
|
||||
|
||||
// Expected (Linux): what the kernel says this thread waited on a run queue grows while another thread holds its only
|
||||
// CPU, and the call that waited is charged less than its wall time by about that much.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn the_kernel_tells_the_time_on_a_run_queue() {
|
||||
@@ -254,7 +235,6 @@ fn pin(cpu: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected: a call within a call is part of the outer one: it is not timed apart, and the outer one counts all.
|
||||
#[test]
|
||||
fn a_nested_call_is_part_of_the_outer_one() {
|
||||
let bench = Bench::new();
|
||||
@@ -270,7 +250,6 @@ fn a_nested_call_is_part_of_the_outer_one() {
|
||||
assert!(outer.overrun);
|
||||
}
|
||||
|
||||
// Expected (4.4): 4 ms for all plugins together in a frame; exactly 4 ms is in it.
|
||||
#[test]
|
||||
fn all_plugins_share_four_ms_a_frame() {
|
||||
for (each, over) in [(Duration::from_millis(1), 0), (Duration::from_millis(1) + US, 1)] {
|
||||
@@ -289,7 +268,6 @@ fn all_plugins_share_four_ms_a_frame() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (4.5): the watchdog paints its notice at 0.5 s, once a call, and ends the client at 2 s.
|
||||
#[test]
|
||||
fn the_watchdog_notices_at_half_a_second_and_acts_at_two() {
|
||||
let limits = Limits::default();
|
||||
@@ -306,7 +284,6 @@ fn the_watchdog_notices_at_half_a_second_and_acts_at_two() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected: the limits are starting values the environment can change, entry by entry.
|
||||
#[test]
|
||||
fn the_limits_parse_from_text() {
|
||||
let limits = Limits::parse("frame=2ms, overrun=250ms,hang=3s,notice=750000us,window=60,slow=6,all=8ms").unwrap();
|
||||
@@ -328,8 +305,6 @@ fn the_limits_parse_from_text() {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (bigboi, carbon 7): a frame ends at the paint, not at the plugin's next call. Thirteen expensive frames and
|
||||
// then silence make the plugin slow when the next paint closes the last one, with the news once.
|
||||
#[test]
|
||||
fn the_last_expensive_frame_closes_at_the_paint() {
|
||||
let bench = Bench::new();
|
||||
@@ -342,7 +317,7 @@ fn the_last_expensive_frame_closes_at_the_paint() {
|
||||
}
|
||||
}
|
||||
assert!(!bench.monitor.is_slow("p"));
|
||||
// A paint starting in the frame open does not end it; the next paint, a frame on, does (review carbon 4.1).
|
||||
// A paint starting in the frame open does not end it; the next paint, a frame on, does.
|
||||
assert!(bench.monitor.close().is_empty());
|
||||
bench.frame.set(bench.frame.get() + 1);
|
||||
assert_eq!(bench.monitor.close(), [("p".to_owned(), "99.0 ms a frame".to_owned())]);
|
||||
@@ -358,8 +333,6 @@ fn the_last_expensive_frame_closes_at_the_paint() {
|
||||
assert!(bench.monitor.wants_close());
|
||||
}
|
||||
|
||||
// Expected: the report is the plugin's p50, p99 and worst per call kind, and the news names the median of its slow
|
||||
// frames, not the first or the worst.
|
||||
#[test]
|
||||
fn the_report_says_the_percentiles_and_the_news_the_median() {
|
||||
let bench = Bench::new();
|
||||
@@ -374,8 +347,6 @@ fn the_report_says_the_percentiles_and_the_news_the_median() {
|
||||
assert_eq!(bench.monitor.report("p").as_deref(), Some("slow (p50/p99/worst): render-slot 14.0/26.0/26.0 ms"));
|
||||
}
|
||||
|
||||
// Expected (carbon 7): each build has its own statistics. A new build of a slow plugin starts fresh, and the report of
|
||||
// an ID is its newest build's.
|
||||
#[test]
|
||||
fn a_new_build_starts_with_fresh_statistics() {
|
||||
let bench = Bench::new();
|
||||
@@ -389,8 +360,6 @@ fn a_new_build_starts_with_fresh_statistics() {
|
||||
assert_eq!(bench.monitor.report("p"), None);
|
||||
}
|
||||
|
||||
// Expected (carbon 1): a call that unwinds still leaves the record and the nesting, so the next call is timed and the
|
||||
// watchdog sees no call running.
|
||||
#[test]
|
||||
fn a_call_that_unwinds_leaves_the_record() {
|
||||
let bench = Bench::new();
|
||||
@@ -406,8 +375,6 @@ fn a_call_that_unwinds_leaves_the_record() {
|
||||
assert!(bench.call(slot, "run-command", Duration::from_millis(150)).overrun);
|
||||
}
|
||||
|
||||
// Expected (bigboi 6): a call whose notice the watchdog painted tells the host as it returns, with the plugin and its
|
||||
// time, so the host can repaint the line; another call does not.
|
||||
#[test]
|
||||
fn a_call_that_was_noticed_tells_the_host() {
|
||||
let bench = Bench::new();
|
||||
@@ -429,8 +396,6 @@ fn a_call_that_was_noticed_tells_the_host() {
|
||||
assert_eq!(*told.borrow(), [(Artifact::builtin("p"), Duration::from_millis(700))]);
|
||||
}
|
||||
|
||||
// Expected (bigboi 6): the watchdog's decision reads the record: no call, no action; a call that returned is not the
|
||||
// running one; a running call over the limit is to be claimed.
|
||||
#[test]
|
||||
fn the_watchdog_decides_from_the_record() {
|
||||
let dir = opencode_util::temp::tempdir().unwrap();
|
||||
@@ -447,8 +412,6 @@ fn the_watchdog_decides_from_the_record() {
|
||||
assert_eq!(decide(&limits, &record, s(3), generation).0, Action::Wait);
|
||||
}
|
||||
|
||||
// Expected (reload-fresh): a build set up again (disabled and enabled) starts with fresh statistics, as a new build
|
||||
// does.
|
||||
#[test]
|
||||
fn a_build_set_up_again_starts_fresh() {
|
||||
let bench = Bench::new();
|
||||
@@ -460,8 +423,6 @@ fn a_build_set_up_again_starts_fresh() {
|
||||
assert_eq!(bench.monitor.report("p"), None);
|
||||
}
|
||||
|
||||
// Expected (bigboi 6): the notice thread paints only a call that still runs: one that returned before its turn is not
|
||||
// marked noticed, so the host does not say it responded.
|
||||
#[test]
|
||||
fn the_notice_is_only_for_a_running_call() {
|
||||
let dir = opencode_util::temp::tempdir().unwrap();
|
||||
@@ -484,8 +445,6 @@ fn the_notice_is_only_for_a_running_call() {
|
||||
assert!(record.leave(live));
|
||||
}
|
||||
|
||||
// Expected (review carbon-4): the monitor says each time a plugin becomes slow or stops being slow, also after the one
|
||||
// news a session the toast tells, and nothing while it stays as it was.
|
||||
#[test]
|
||||
fn every_change_of_slow_is_said_once() {
|
||||
let bench = Bench::new();
|
||||
@@ -504,9 +463,6 @@ fn every_change_of_slow_is_said_once() {
|
||||
assert!(!bench.monitor.take_flipped());
|
||||
}
|
||||
|
||||
// Expected (4.4, Pl: "host time for plugin X"): the host's own work for a plugin's nodes is timed apart from the
|
||||
// plugin's calls. It is the plugin's host time, beside its calls in a slow plugin's details, and it is not in the
|
||||
// plugin's frame budget: a frame whose host work is 5 ms and whose calls are 0.5 ms is under the budget.
|
||||
#[test]
|
||||
fn host_time_is_counted_beside_the_calls_and_not_in_the_budget() {
|
||||
let bench = Bench::new();
|
||||
@@ -531,8 +487,6 @@ fn host_time_is_counted_beside_the_calls_and_not_in_the_budget() {
|
||||
assert!(report.contains("render-slot"), "{report}");
|
||||
}
|
||||
|
||||
// Expected (fixed row; review carbon 5.2): host work for plugin p that runs a nested slot of plugin q, whose view and
|
||||
// host work run inside it, counts p's own 1 ms; q's view is q's call and its host work q's 2 ms.
|
||||
#[test]
|
||||
fn nested_host_work_is_its_own_plugins() {
|
||||
let bench = Bench::new();
|
||||
@@ -557,10 +511,6 @@ fn backlogged(bench: &Bench, slot: Slot, frames: usize) -> Vec<(String, String)>
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Expected (4.14 `reported-once`; final review big-boi 10): the user is told a plugin is slow once a plugin and session,
|
||||
// whichever cause comes first: slow by its calls and then by its backlog is one news; so is the backlog first and its
|
||||
// calls after; and a plugin set up again, or rebuilt, that is slow again tells nothing more. Its state still follows
|
||||
// each cause and each build.
|
||||
#[test]
|
||||
fn slow_is_told_once_a_plugin_and_session_across_causes_and_activations() {
|
||||
// Calls first, then the backlog.
|
||||
@@ -589,9 +539,6 @@ fn slow_is_told_once_a_plugin_and_session_across_causes_and_activations() {
|
||||
assert_eq!(bench.frames(other, 13, 1).len(), 1);
|
||||
}
|
||||
|
||||
// Expected (review carbon-12): the backlog cause changes slow as the calls do: the plugin list hears it when the
|
||||
// backlog makes the plugin slow, also once its news was told, and when the backlog leaves the window with no mail
|
||||
// since, at the paint that closes the frames.
|
||||
#[test]
|
||||
fn a_backlog_that_starts_or_ends_is_a_change_of_slow() {
|
||||
let bench = Bench::new();
|
||||
@@ -611,10 +558,6 @@ fn a_backlog_that_starts_or_ends_is_a_change_of_slow() {
|
||||
assert!(bench.monitor.take_flipped() && bench.monitor.is_slow("p"));
|
||||
}
|
||||
|
||||
// Expected (final review big-boi 11): a build keeps one slot from its load, before its ID is known, to its activation:
|
||||
// a crash in either names the same artifact, by its ID once it is known; a later load of the same build finds that
|
||||
// slot, and a new build gets its own. An ID too long for the record leaves the build named by its target and digest,
|
||||
// never unnamed.
|
||||
#[test]
|
||||
fn a_build_keeps_one_slot_from_its_load_to_its_activation() {
|
||||
let bench = Bench::new();
|
||||
@@ -642,16 +585,12 @@ fn a_build_keeps_one_slot_from_its_load_to_its_activation() {
|
||||
let long = Artifact::external(&"x".repeat(record::NAME_BYTES), "/p", "0000000000000002");
|
||||
assert_eq!(bench.monitor.slot(&long), other);
|
||||
assert_eq!(crashed(other, "setup"), Some(Artifact::external("", "/p", "0000000000000002")));
|
||||
// The same build loaded again, before its ID is known: its build names it, so it is admitted (re-review big-boi
|
||||
// 11), and it is the same slot.
|
||||
let again = bench.monitor.slot(&Artifact::external("", "/p", "0000000000000002"));
|
||||
assert_eq!(again, other);
|
||||
assert!(bench.monitor.attributed(again), "the same build is refused on its reload");
|
||||
assert!(bench.monitor.attributed(active), "a build named with its ID");
|
||||
}
|
||||
|
||||
// Expected (final review big-boi 11): a build whose identity the record cannot hold, by its length or past the record's
|
||||
// slots, is not attributed, so the loader does not admit it; without a record every build is.
|
||||
#[test]
|
||||
fn a_build_the_record_cannot_name_is_not_attributed() {
|
||||
let bench = Bench::new();
|
||||
@@ -674,8 +613,6 @@ fn a_build_the_record_cannot_name_is_not_attributed() {
|
||||
assert_eq!(record.snapshot(), Some(snapshot));
|
||||
}
|
||||
|
||||
// Expected (big-boi tm-1): a timer's idle close ends a frame of timer calls alone, as a frame of its own with no
|
||||
// paint. A frame where another call ran too is left for a paint to end, so that call's time stays the scheduler's.
|
||||
#[test]
|
||||
fn an_idle_close_leaves_a_frame_with_other_work_for_its_paint() {
|
||||
let bench = Bench::new();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! The watchdog (synthesis 4.5). A plugin call holds the UI thread and cannot be stopped, so two threads watch the run
|
||||
//! record instead:
|
||||
//! The watchdog. A plugin call holds the UI thread and cannot be stopped, so two threads watch the run record instead:
|
||||
//!
|
||||
//! - **The deadline thread** reads the running call every 20 ms. It allocates nothing, logs nothing and does no I/O
|
||||
//! that can block: at [`Limits::notice`] it hands the call to the notice thread without waiting, and at
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
//! Approval of project plugins (rich-plugins 3.9, decision O-125): a native build found in a project's
|
||||
//! `.opencode/plugins` runs only once the user approved it, and so does a TypeScript plugin there that the JS host
|
||||
//! would run (P7). A decision names an [`Artifact`]: the directory it was found as, the real path of its library, and
|
||||
//! the SHA-256 of the bytes that are loaded; for a TypeScript plugin, the real path of the directory and the SHA-256 of
|
||||
//! its files ([`Artifact::tree`]). A changed library, another
|
||||
//! path to it, or the same library found as another plugin directory (another project's) is pending again. The global
|
||||
//! `plugins` directory and `cli.json` entries need none: a project cannot write them.
|
||||
//!
|
||||
//! The decisions are kept in one file of the client's state directory, read at each lookup, so another client's
|
||||
//! decision applies at the next reconcile. An update is one read, change and replace under a lock, so concurrent
|
||||
//! clients never lose or bring back each other's decisions. The file is private to the user; a store the project could
|
||||
//! reach, or that others can write, is not used, and decisions then last as long as the client.
|
||||
//! Project plugins require approval for the discovered directory, resolved path and SHA-256 of the loaded bytes.
|
||||
//! Script approvals hash the directory tree. A changed build or path needs a new decision. Clients share decisions
|
||||
//! through a locked, user-private state file; if the project can reach the file or others can write it, decisions
|
||||
//! stay in memory.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::fs::File;
|
||||
@@ -23,7 +15,7 @@ use serde_json::Value;
|
||||
/// The file of the decisions in the client's state directory.
|
||||
pub const FILE: &str = "plugin-approvals.json";
|
||||
|
||||
/// The largest library the loader reads (carbon-5): a bigger file is refused before anything is allocated for it.
|
||||
/// The largest library the loader reads: a bigger file is refused before anything is allocated for it.
|
||||
pub const LIMIT: u64 = 512 * 1024 * 1024;
|
||||
|
||||
/// What an approval names: the plugin directory it was found as, the real path of its library, and the SHA-256 of the
|
||||
@@ -38,9 +30,9 @@ pub struct Artifact {
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
/// Opens the library `file` of plugin directory `target` once and hashes what it reads (bigboi-5). The returned
|
||||
/// handle is the file that was hashed, for [`Artifact::bytes`]. An error when the file is not a regular file, is
|
||||
/// over [`LIMIT`], or its name led to another file by the time it was read.
|
||||
/// Opens the library `file` of plugin directory `target` once and hashes what it reads. The returned handle is the
|
||||
/// file that was hashed, for [`Artifact::bytes`]. An error when the file is not a regular file, is over [`LIMIT`],
|
||||
/// or its name led to another file by the time it was read.
|
||||
pub fn open(target: &Path, file: &Path) -> Result<(Self, File), String> {
|
||||
let error = |error: std::io::Error| format!("{}: {error}", file.display());
|
||||
let path = std::fs::canonicalize(file).map_err(error)?;
|
||||
@@ -78,20 +70,20 @@ impl Artifact {
|
||||
Ok((Self { target: target.to_path_buf(), path, sha256, script: false }, handle))
|
||||
}
|
||||
|
||||
/// The TypeScript plugin directory `target`, which the JS host would run: its real path, and the SHA-256 of what it
|
||||
/// holds. Each file's path and bytes count, in name order, hidden ones and its dependencies in `node_modules` too:
|
||||
/// whatever the JS host may import from it (review carbon-1). The JS host reads the files itself, so a change after
|
||||
/// the hash is what the next reconcile sees: the watcher's, which holds the new files back. A file outside the
|
||||
/// directory that the plugin imports is not part of it.
|
||||
/// The TypeScript plugin directory `target`, which the JS host would run: its real path, and the SHA-256 of what
|
||||
/// it holds. Each file's path and bytes count, in name order, hidden ones and its dependencies in `node_modules`
|
||||
/// too: whatever the JS host may import from it. The JS host reads the files itself, so a change after the hash is
|
||||
/// what the next reconcile sees: the watcher's, which holds the new files back. A file outside the directory that
|
||||
/// the plugin imports is not part of it.
|
||||
pub fn tree(target: &Path) -> Result<Self, String> {
|
||||
let error = |error: std::io::Error| format!("{}: {error}", target.display());
|
||||
let path = std::fs::canonicalize(target).map_err(error)?;
|
||||
if !path.is_dir() {
|
||||
return Err(format!("{}: not a directory", path.display()));
|
||||
}
|
||||
// A tree whose entries did not change since its last hash is not read again (bigboi P8-9): every reconcile asks
|
||||
// for it, and the JS host's answers each start one. What runs is still what was approved: [`Artifact::stage`]
|
||||
// hashes the bytes it copies.
|
||||
// A tree whose entries did not change since its last hash is not read again: every reconcile asks for it, and
|
||||
// the JS host's answers each start one. What runs is still what was approved: [`Artifact::stage`] hashes the
|
||||
// bytes it copies.
|
||||
let print = fingerprint(&path)?;
|
||||
let known =
|
||||
TREES.with(|trees| trees.borrow().get(&path).filter(|(at, _)| *at == print).map(|(_, sha)| sha.clone()));
|
||||
@@ -111,9 +103,9 @@ impl Artifact {
|
||||
}
|
||||
|
||||
/// The tree [`Artifact::tree`] hashed, as a copy under `root` named by its hash, which the JS host imports instead
|
||||
/// of the directory (bigboi P8-1): a save between the approval and the import changes the directory, not the copy.
|
||||
/// The copy is written from the bytes its hash is taken of as they are copied, and kept only if that hash is the
|
||||
/// one approved; else the directory changed since, and nothing of it runs. A copy made before is used again.
|
||||
/// of the directory: a save between the approval and the import changes the directory, not the copy. The copy is
|
||||
/// written from the bytes its hash is taken of as they are copied, and kept only if that hash is the one approved;
|
||||
/// else the directory changed since, and nothing of it runs. A copy made before is used again.
|
||||
pub fn stage(&self, root: &Path) -> Result<PathBuf, String> {
|
||||
let staged = root.join(&self.sha256);
|
||||
if staged.is_dir() {
|
||||
@@ -145,7 +137,7 @@ impl Artifact {
|
||||
}
|
||||
|
||||
/// The bytes of `handle`, the file [`Artifact::open`] hashed, once they are checked to be the ones it hashed: what
|
||||
/// is loaded is what was approved (bigboi-1).
|
||||
/// is loaded is what was approved.
|
||||
pub fn bytes(&self, handle: &mut File) -> Result<Vec<u8>, String> {
|
||||
let error = |error: std::io::Error| format!("{}: {error}", self.path.display());
|
||||
handle.rewind().map_err(error)?;
|
||||
@@ -166,7 +158,7 @@ impl Artifact {
|
||||
thread_local! {
|
||||
/// The last hash of each plugin tree, with the fingerprint of its entries then.
|
||||
static TREES: RefCell<std::collections::HashMap<PathBuf, (u64, String)>> = RefCell::default();
|
||||
/// The bytes of plugin files this thread read to hash them, for the rows that count the work (bigboi P8-9).
|
||||
/// The bytes of plugin files this thread read to hash them, for the rows that count the work.
|
||||
static HASHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
@@ -233,7 +225,7 @@ pub(crate) fn install_root(dir: &Path) -> Option<PathBuf> {
|
||||
(!generation.is_empty() && generation.bytes().all(|byte| byte.is_ascii_digit())).then(|| root.to_path_buf())
|
||||
}
|
||||
|
||||
/// The approval hash of a package of the npm cache (O-162): its own tree's, and its dependencies by the install's
|
||||
/// The approval hash of a package of the npm cache: its own tree's, and its dependencies by the install's
|
||||
/// `package.json` and lockfile.
|
||||
fn install_sha256(tree: &str, root: &Path) -> Result<String, String> {
|
||||
let mut context = ring::digest::Context::new(&ring::digest::SHA256);
|
||||
@@ -362,8 +354,8 @@ pub enum Decision {
|
||||
Declined,
|
||||
}
|
||||
|
||||
/// One decision as it is stored. Paths are kept losslessly (bigboi-7): as text when they are Unicode, else as `hex:`
|
||||
/// and the platform's encoded bytes, which no absolute path starts with.
|
||||
/// One decision as it is stored. Paths are kept losslessly: as text when they are Unicode, else as `hex:` and the
|
||||
/// platform's encoded bytes, which no absolute path starts with.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Stored {
|
||||
target: String,
|
||||
@@ -423,7 +415,7 @@ impl Default for Approvals {
|
||||
|
||||
impl Approvals {
|
||||
/// The decisions kept in `file`, unless the project at `project` could reach it or other users can write its
|
||||
/// directory (bigboi-2): then they last as long as the client, and [`Approvals::unsaved`] says why.
|
||||
/// directory: then they last as long as the client, and [`Approvals::unsaved`] says why.
|
||||
pub fn open(file: PathBuf, project: &Path) -> Self {
|
||||
match trusted(&file, project) {
|
||||
Ok(()) => Self { store: Store::File(file), scratch: RefCell::default() },
|
||||
@@ -557,9 +549,9 @@ fn load(file: &Path) -> Result<Vec<Value>, String> {
|
||||
serde_json::from_slice(&bytes).map_err(|error| format!("not a list of decisions: {error}"))
|
||||
}
|
||||
|
||||
/// Reads, changes and replaces the entries of `file` while holding its lock (bigboi-4, carbon-3). The new file is
|
||||
/// written to a temporary file of its own, private to the user, and renamed over the old one; on any error the old
|
||||
/// file stays and the temporary file goes.
|
||||
/// Reads, changes and replaces the entries of `file` while holding its lock. The new file is written to a temporary
|
||||
/// file of its own, private to the user, and renamed over the old one; on any error the old file stays and the
|
||||
/// temporary file goes.
|
||||
fn update(file: &Path, change: impl FnOnce(&mut Vec<Value>) -> Result<(), String>) -> Result<(), String> {
|
||||
let _lock = lock(file)?;
|
||||
let mut entries = load(file)?;
|
||||
|
||||
@@ -1,37 +1,7 @@
|
||||
//! What a native build asks the platform loader to load with it (bigboi-3; final review big-boi 2, carbon-7): the
|
||||
//! dependencies and search paths an ELF or Mach-O file names, read as the loader that loads that format reads them,
|
||||
//! glibc's or musl's `ld.so` for ELF and `dyld` for Mach-O. The loader opens a build from a private copy that holds
|
||||
//! only that one file, so a dependency comes from the system, from the paths the build names, from the user's own
|
||||
//! loader settings, or, for a relative path, from the current directory, which is the project. An approval names one
|
||||
//! file's bytes (rich-plugins 3.9), so what it covers must not reach code outside it.
|
||||
//!
|
||||
//! The policy is fail-closed: a name or a mechanism it does not know to be safe is refused, not passed.
|
||||
//!
|
||||
//! - No build may name a path the loader resolves against the current directory, a path with a `..` component
|
||||
//! anywhere (which leaves the directory it starts in: the private copy, the client's, or a trusted root), an empty
|
||||
//! search path entry (which glibc reads as the current directory), or a loader token other than the one leading
|
||||
//! origin token, whole: `$ORIGIN` and `${ORIGIN}` on ELF (`$ORIGIN_X` is no token to `ld.so`, so it is a relative
|
||||
//! path), `@loader_path`, `@executable_path` and `@rpath` on Mach-O, each followed by `/` or nothing. A bare name
|
||||
//! is a library `ld.so` searches for; `dyld` reads one as a path, so on Mach-O it is refused.
|
||||
//! - No build may use a mechanism that brings in code the host does not read: ELF's `DT_FILTER`, `DT_AUXILIARY`,
|
||||
//! `DT_AUDIT`, `DT_DEPAUDIT` and `DT_USED`, a dynamic tag the policy does not know, or Mach-O's
|
||||
//! `LC_LOAD_DYLINKER` and `LC_DYLD_ENVIRONMENT`.
|
||||
//! - A project's build may also name no absolute path outside the system's libraries: `/usr/lib`, `/usr/lib64`,
|
||||
//! `/lib` and `/lib64` on Linux and the other ELF systems, `/usr/lib` and `/System` on macOS, each matched by whole
|
||||
//! components. A root is trusted once it and every directory above it, symbolic links resolved, are the
|
||||
//! superuser's and no one else may write them; a path under one that exists must still be under one once its links
|
||||
//! are resolved. A path that does not exist loads nothing (on macOS a system library is in the shared cache and not
|
||||
//! on disk).
|
||||
//! - The user's own loader settings are the user's choice and trusted: `LD_LIBRARY_PATH` and `LD_PRELOAD` on ELF
|
||||
//! systems, the `DYLD_*` paths on macOS, and the system's loader configuration. So a project's build is not
|
||||
//! promised libraries from the system alone. One part of them is not the user's: an empty or relative entry in
|
||||
//! `LD_LIBRARY_PATH` (whose entries glibc splits at `:` and at `;`) or a `DYLD_*` path is read against the current
|
||||
//! directory, so a build that names a library the loader searches for is refused while one is set: on ELF a bare
|
||||
//! name, on Mach-O any library, as `dyld` looks for every library's leaf name in those paths, `@rpath` ones too
|
||||
//! (final re-review big-boi 2).
|
||||
//!
|
||||
//! Windows needs no reading: `win::load_library` searches no directory a project controls. A file that is neither
|
||||
//! ELF nor Mach-O passes here; the platform loader refuses it.
|
||||
//! An approval covers one library, not code it loads from the project. Check ELF and Mach-O dependencies and loader
|
||||
//! search paths before opening the private copy. Reject unknown loading mechanisms, relative paths and traversal.
|
||||
//! Project libraries may use absolute paths only under trusted, root-owned system directories after symlink
|
||||
//! resolution. The user's loader environment remains trusted.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
@@ -348,10 +318,10 @@ const GENERIC_TAGS: &[u64] = &[
|
||||
32, 33, 34, 35, 36, 37,
|
||||
];
|
||||
|
||||
/// Whether dynamic tag `tag` of a file for `machine` is one the policy knows loads no code but what it reads: each of
|
||||
/// [`GENERIC_TAGS`], each of [`GNU_TAGS`], and the processor tags its machine defines (x86-64's
|
||||
/// PLT tags; AArch64's BTI, PAC, variant PCS and memory tags; RISC-V's variant calling convention). A tag in a range
|
||||
/// but not named here is refused (final re-review big-boi 2, and its final pass: tag 31).
|
||||
/// Whether dynamic tag `tag` of a file for `machine` is one the policy knows loads no code but what it reads: each
|
||||
/// of [`GENERIC_TAGS`], each of [`GNU_TAGS`], and the processor tags its machine defines (x86-64's PLT tags;
|
||||
/// AArch64's BTI, PAC, variant PCS and memory tags; RISC-V's variant calling convention). A tag in a range but not
|
||||
/// named here is refused.
|
||||
fn known(tag: u64, machine: u64) -> bool {
|
||||
let processor: &[u64] = match machine {
|
||||
EM_X86_64 => &[0x7000_0000, 0x7000_0001, 0x7000_0003],
|
||||
@@ -406,7 +376,7 @@ fn elf(bytes: &[u8]) -> Option<Vec<Name>> {
|
||||
.into_iter()
|
||||
.take_while(|(tag, _)| *tag != 0)
|
||||
.collect();
|
||||
// A tag that brings in code, or one the policy does not know, is refused by its number (big-boi 2, carbon-7).
|
||||
// A tag that brings in code, or one the policy does not know, is refused by its number.
|
||||
let mut out: Vec<Name> = entries
|
||||
.iter()
|
||||
.filter(|(tag, _)| !known(*tag, machine))
|
||||
@@ -602,10 +572,6 @@ mod tests {
|
||||
(check_with(bytes, false, &policy()).is_ok(), check_with(bytes, true, &policy()).is_ok())
|
||||
}
|
||||
|
||||
// Expected (bigboi-3, final review big-boi 2 and carbon-7): an ELF build names its libraries and search paths,
|
||||
// read as `ld.so` reads them, and the policy refuses what the current directory or a path outside where it starts
|
||||
// would supply, `..` anywhere and a token `ld.so` does not expand; a project's build may name system libraries
|
||||
// only, matched by whole components.
|
||||
#[test]
|
||||
fn elf_dependencies_follow_the_policy() {
|
||||
let plain = elf64(&["libc.so.6", "libm.so.6"], None);
|
||||
@@ -660,10 +626,6 @@ mod tests {
|
||||
assert_eq!(check(b"MZ\x90\x00", true), Ok(()));
|
||||
}
|
||||
|
||||
// Expected (final review carbon-7, big-boi 2; final re-review big-boi 2): a dynamic tag that brings in code the
|
||||
// policy does not read, a filter, an auxiliary filter, an audit library, `DT_USED`, `DT_CONFIG`, or a tag it does
|
||||
// not know, is refused for every build, also one inside the ranges the known tags are in, and a processor tag of
|
||||
// another machine; the tags a toolchain writes pass, a processor's own on its machine.
|
||||
#[test]
|
||||
fn elf_mechanisms_that_load_code_are_refused() {
|
||||
let refused = [
|
||||
@@ -708,9 +670,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (final review big-boi 2): the user's loader settings are trusted, but an empty or relative entry in them
|
||||
// is read against the current directory: a build that names a library the loader searches for is refused while
|
||||
// one is set, and one that names only paths is not.
|
||||
#[test]
|
||||
fn a_relative_loader_path_setting_refuses_a_searched_library() {
|
||||
let searched = elf64(&["libc.so.6"], None);
|
||||
@@ -725,16 +684,13 @@ mod tests {
|
||||
let dyld = Policy { settings: vec![("DYLD_LIBRARY_PATH", value.to_owned())], ..policy() };
|
||||
assert_eq!(check_with(&searched, false, &dyld), Ok(()), "{value:?}");
|
||||
}
|
||||
// glibc splits `LD_LIBRARY_PATH` at `;` too (final re-review big-boi 2).
|
||||
// glibc also splits `LD_LIBRARY_PATH` at semicolons.
|
||||
for value in ["/opt/lib;lib", ";/opt/lib", "/opt/lib;"] {
|
||||
let ld = Policy { settings: vec![("LD_LIBRARY_PATH", value.to_owned())], ..policy() };
|
||||
assert!(check_with(&searched, false, &ld).is_err(), "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (final re-review big-boi 2): `dyld` looks for every library's leaf name in its `DYLD_*` paths, an
|
||||
// `@rpath` name's and an absolute one's too: a relative entry refuses a build that names any library, and an
|
||||
// absolute one does not; it splits them at `:` alone, so a `;` is part of an absolute entry.
|
||||
#[test]
|
||||
fn a_relative_dyld_path_refuses_any_library() {
|
||||
for name in ["@rpath/libx.dylib", "@loader_path/libx.dylib", "/usr/lib/libSystem.B.dylib"] {
|
||||
@@ -753,9 +709,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// Expected (final review big-boi 2): a trusted root is trusted as the loader finds it: a path under one that leads
|
||||
// through a symbolic link out of every root is refused, as is a root someone else may write; one that stays in it
|
||||
// passes. Here the roots are a directory of the user's own, which only the tests may own.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_trusted_root_is_checked_on_the_disk() {
|
||||
@@ -790,9 +743,6 @@ mod tests {
|
||||
assert!(policy().trusts(Path::new("/usr/lib")), "/usr/lib is not a trusted root here");
|
||||
}
|
||||
|
||||
// Expected (bigboi-3, final review big-boi 2 and carbon-7): the same policy for Mach-O load commands, read as
|
||||
// `dyld` reads them, also inside a universal file: a token followed by a separator or nothing, no `..` anywhere,
|
||||
// a bare name refused (`dyld` reads it as a path), and the load commands of a main executable refused.
|
||||
#[test]
|
||||
fn macho_dependencies_follow_the_policy() {
|
||||
let system = macho64(&[(LC_LOAD_DYLIB, "/usr/lib/libSystem.B.dylib")]);
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
//! External plugins (`docs/plugins.md`, "Running plugins"): discovery in `plugins` directories, the `plugins` entries of
|
||||
//! `cli.json`, and loading of native builds (shared libraries on the C ABI of `opencode-plugin-abi`, decision
|
||||
//! O-42) through a [`Backend`], which is [`native::Native`] in the TUI. Targets without a native build
|
||||
//! (TypeScript plugins) run on the JS host ([`crate::pipe`]) when the loader has one, and are listed as skipped
|
||||
//! otherwise.
|
||||
//!
|
||||
//! A [`Loader`] reconciles the targets with the [`Registry`]: it loads new and changed builds, keeps a running
|
||||
//! plugin when its new build fails, and unloads removed ones. The host calls [`Loader::reconcile`] again when a
|
||||
//! directory of [`Loader::watch_dirs`] changes, which gives hot reload. A build found in a project's
|
||||
//! `.opencode/plugins` loads only once the user approved it ([`approval`]).
|
||||
//! Discovers plugin targets and reconciles them with the registry. A failed rebuild leaves the running plugin
|
||||
//! active. Project plugins require approval before loading.
|
||||
|
||||
pub mod approval;
|
||||
pub mod deps;
|
||||
@@ -48,9 +40,8 @@ pub trait Backend {
|
||||
options: Option<&str>,
|
||||
) -> Result<(Definition, ErrorFn), String>;
|
||||
|
||||
/// [`Backend::load`] of a build read whole through one descriptor, with the raw quarantine read through the same
|
||||
/// one ([`quarantine::read`]): what the loaded copy carries is the attribute of the bytes that were read (final
|
||||
/// review big-boi 3). A backend that keeps no quarantine loads the bytes alone.
|
||||
/// Loads bytes and quarantine metadata read from the same descriptor, so replacing the path cannot change which
|
||||
/// attribute travels with the copy.
|
||||
fn load_read(
|
||||
&self,
|
||||
host: &Rc<dyn Host>,
|
||||
@@ -96,8 +87,8 @@ impl Target {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server plugin's TUI part as `GET /api/plugin` reports it (TS `serverTuiPlugins`): its source, and the plugin's ID
|
||||
/// when the server gives one, which the user's `-<id>` removals select (O-162, carbon recheck-1).
|
||||
/// A server plugin's TUI part as `GET /api/plugin` reports it: its source, and the plugin's ID when the server gives
|
||||
/// one, which the user's `-<id>` removals select.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ServerPart {
|
||||
/// A package spec, found in the npm cache ([`npm::resolve`]).
|
||||
@@ -111,7 +102,7 @@ pub enum Found {
|
||||
/// A library, identified at once.
|
||||
Build(Result<Artifact, String>),
|
||||
/// A TypeScript plugin's directory, whose full hash can take seconds with a large `node_modules`: the caller runs
|
||||
/// [`Found::identify`] off the UI thread (FT-2).
|
||||
/// [`Found::identify`] off the UI thread.
|
||||
Tree(PathBuf),
|
||||
/// A Luau plugin's directory, hashed as a TypeScript plugin's tree and approved as a Luau plugin
|
||||
/// ([`crate::luau::artifact`]); also identified off the UI thread.
|
||||
@@ -177,14 +168,14 @@ pub struct Loader {
|
||||
/// The global cache directory TS installs packages into (`~/.cache/opencode`), where a target named by npm
|
||||
/// package is found ([`npm::resolve`]), and nothing installed.
|
||||
npm: Option<PathBuf>,
|
||||
/// The TUI parts of the active server plugins (TS `serverTuiPlugins`), and the `plugins` entries of the user's
|
||||
/// global opencode config, which vouch for the parts they name (O-162).
|
||||
/// The TUI parts of the active server plugins, and the `plugins` entries of the user's global opencode config,
|
||||
/// which vouch for the parts they name.
|
||||
server: RefCell<(Vec<ServerPart>, Vec<String>)>,
|
||||
/// The package each npm spec resolved to, kept while the spec is a target: TS resolves a loaded package's entry
|
||||
/// once a session (`context.tsx:663-665`), so a later install does not move it.
|
||||
/// Cache the resolved entry while the spec remains configured. Installing a newer generation must not move a
|
||||
/// running plugin.
|
||||
packages: RefCell<HashMap<String, npm::Package>>,
|
||||
/// A directory with a `plugin.toml` and no native build runs as a Luau plugin ([`crate::luau`]), its files walked,
|
||||
/// hashed and staged on threads of their own, as a TypeScript plugin's are (FT-2).
|
||||
/// hashed and staged on threads of their own, as a TypeScript plugin's are.
|
||||
#[cfg(luau)]
|
||||
luau: Option<crate::pipe::tree::Trees>,
|
||||
/// A Luau plugin's sources, read and compiled on threads of their own.
|
||||
@@ -192,9 +183,9 @@ pub struct Loader {
|
||||
luau_builds: Option<crate::luau::Builds>,
|
||||
}
|
||||
|
||||
/// The path `realpath` gives (carbon recheck-3): `canonicalize`, without the verbatim prefix it gives on Windows
|
||||
/// (`\\?\C:\x` is `C:\x`), so a path compares with one written as the user or the server writes it, and the JS host
|
||||
/// is handed one Bun and Node read alike.
|
||||
/// The path `realpath` gives: `canonicalize`, without the verbatim prefix it gives on Windows (`\\?\C:\x` is `C:\x`),
|
||||
/// so a path compares with one written as the user or the server writes it, and the JS host is handed one Bun and Node
|
||||
/// read alike.
|
||||
fn real(path: &Path) -> Option<PathBuf> {
|
||||
std::fs::canonicalize(path).ok().map(plain)
|
||||
}
|
||||
@@ -207,8 +198,7 @@ fn plain(path: PathBuf) -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// TS's plugin selector (`matches`, `core/src/plugin/supervisor.ts`, `tui/src/plugin/context.tsx`): `*`, a
|
||||
/// `<prefix>.*`, or the name itself.
|
||||
/// Matches an exact plugin ID, a `prefix.*` selector, or `*`.
|
||||
fn selects(selector: &str, name: &str) -> bool {
|
||||
selector == "*"
|
||||
|| match selector.strip_suffix('*').filter(|prefix| prefix.ends_with('.')) {
|
||||
@@ -348,18 +338,8 @@ impl Loader {
|
||||
Some(directory)
|
||||
}
|
||||
|
||||
/// Whether the user's own configuration names the server part `spec` (a package's spec, or the path the server
|
||||
/// reported, `local` its real path), with the plugin ID `id` (O-162). `user` is the `plugins` entries of the
|
||||
/// global opencode config (`opencode.json`, then `opencode.jsonc`) and then of `cli.json`, in order, removals
|
||||
/// included. They fold as TS's server folds its operations (`supervisor.ts`, carbon recheck-1):
|
||||
/// - a plugin directly under a global `plugin` or `plugins` directory is named first, as discovery adds it before
|
||||
/// any entry (`source.ts` `scan`, `PluginSourceDirectory.discover`), and nothing deeper in it is;
|
||||
/// - an entry that is the spec, or names the path (`./`, `../` and `file://` against the config directory, as TS
|
||||
/// resolves them), names and enables it;
|
||||
/// - a selector (`*`, `<prefix>.*`, `opencode.…`, or the ID) enables it again, without naming it;
|
||||
/// - a `-<selector>` that selects the spec, the path or the ID disables it.
|
||||
///
|
||||
/// It is vouched for when it is named and, after the last entry, enabled.
|
||||
/// Does the user's global configuration vouch for this server part? Project configuration can request a plugin,
|
||||
/// but cannot approve it.
|
||||
fn vouched(&self, user: &[String], spec: &str, local: Option<&Path>, id: Option<&str>) -> bool {
|
||||
let dirs = ["plugin", "plugins"].map(|name| real(&self.config_dir.join(name)));
|
||||
let child = local.is_some_and(|_| {
|
||||
@@ -415,10 +395,7 @@ impl Loader {
|
||||
Self { approvals, ..self }
|
||||
}
|
||||
|
||||
/// The discovered directories, then the configured entries, merged by local path (TS `mergePluginTargets`:
|
||||
/// a later entry replaces an earlier one in its place). Only the global `plugins` directory is not a project's. A
|
||||
/// configured entry also replaces a project's plugin whose library is the same file under another spelling (a link,
|
||||
/// another case, or the library rather than its directory; carbon-4, bigboi-6), so it is not listed twice.
|
||||
/// Merges discovered and configured targets by local path. Later entries replace earlier ones in place.
|
||||
pub fn targets(&self) -> Vec<Target> {
|
||||
let directories = plugin_directories(&self.config_dir, &self.cwd);
|
||||
let discovered = directories.iter().enumerate().flat_map(|(index, directory)| {
|
||||
@@ -429,17 +406,9 @@ impl Loader {
|
||||
project: index > 0,
|
||||
})
|
||||
});
|
||||
// TS's order: the discovered directories, the server plugins' TUI parts, then `cli.json` (`context.tsx:290-309`).
|
||||
// Later entries take precedence: discovery, server parts, then `cli.json`.
|
||||
let (parts, user) = if self.js() { self.server.borrow().clone() } else { Default::default() };
|
||||
// A part that does not resolve is left out, as TS leaves out an optional target it cannot load
|
||||
// (`context.tsx:362-363`). It loads without approval only when the user's own configuration names it: its spec
|
||||
// in `cli.json` or the global opencode config, or its path there or under a global plugin directory. Any other
|
||||
// needs approval as a project's plugin does (O-162): a project's `opencode.json` names packages the server runs
|
||||
// none of, and a path the server reports is its directory, held for the same artifact. A server target never
|
||||
// loads a native build.
|
||||
// A package `cli.json` names, at any version, is `cli.json`'s: TS folds its entries after the server's parts,
|
||||
// so its version replaces the server's for the plugin's ID (`context.tsx:289-309`, `desired.set`), and the
|
||||
// server's part never loads (carbon recheck-2).
|
||||
// Skip unresolved optional parts. Only the user's configuration can vouch for a server part.
|
||||
let configured = self.configured.borrow();
|
||||
let named: Vec<String> = configured.iter().filter_map(|entry| self.package_name(&entry.target)).collect();
|
||||
let server = parts.into_iter().filter_map(|part| {
|
||||
@@ -479,23 +448,22 @@ impl Loader {
|
||||
.as_ref()
|
||||
.map_or_else(|| target.target.clone(), |local| local.to_string_lossy().into_owned())
|
||||
};
|
||||
// A library's file, or a TypeScript plugin's directory (review carbon-1).
|
||||
// A library's file, or a TypeScript plugin's directory.
|
||||
let same_file = |known: &Target| {
|
||||
let file = |target: &Target| {
|
||||
target.library().or_else(|| target.local.clone()).and_then(|file| identity(&file))
|
||||
};
|
||||
file(known).is_some_and(|known| file(&target) == Some(known))
|
||||
};
|
||||
// Only a configured entry stands in for a project's plugin: a server's never does (carbon jsnpm-2).
|
||||
// Only a configured entry stands in for a project's plugin: a server's never does.
|
||||
let alias = |known: &Target| !from_server && known.project && !target.project && same_file(known);
|
||||
// A server part that names a target already found, under any spelling, is that target: one target, one
|
||||
// approval.
|
||||
if from_server && targets.iter().any(|known| key(known) == key(&target) || same_file(known)) {
|
||||
continue;
|
||||
}
|
||||
// A `cli.json` entry replaces a server's part for the same directory in its place, however each spells it
|
||||
// (a link, a Windows verbatim path), as TS merges them by `localSource` (carbon recheck-2): the server's
|
||||
// part is stored by its real path, the entry as written.
|
||||
// Compare real paths so a `cli.json` entry overrides the same server part reached through a symlink or
|
||||
// Windows verbatim path.
|
||||
let real_path = |target: &Target| target.local.as_deref().and_then(real);
|
||||
let same_part = |index: usize, known: &Target| {
|
||||
!from_server
|
||||
@@ -554,8 +522,8 @@ impl Loader {
|
||||
if local_source(&target.target, &self.config_dir).is_none() {
|
||||
continue;
|
||||
}
|
||||
// A TypeScript plugin's modules may sit in its subdirectories, whose saves reload it too (review carbon-2);
|
||||
// its dependencies change by an install, which touches the directory itself. So may a Luau plugin's.
|
||||
// A TypeScript plugin's modules may sit in its subdirectories, whose saves reload it too; its dependencies
|
||||
// change by an install, which touches the directory itself. So may a Luau plugin's.
|
||||
if (self.scripted(&target) || self.luau_target(&target))
|
||||
&& let Some(local) = &target.local
|
||||
{
|
||||
@@ -681,7 +649,7 @@ impl Loader {
|
||||
if self.scripted(target)
|
||||
&& let (Some(scripts), Some(dir)) = (&self.scripts, &target.local)
|
||||
{
|
||||
// Bun is looked for only now, for the first TypeScript plugin (O-166); without it the plugin is skipped.
|
||||
// Bun is looked for only now, for the first TypeScript plugin; without it the plugin is skipped.
|
||||
if !scripts.runtime() {
|
||||
return skip(crate::SKIPPED_NO_BUN);
|
||||
}
|
||||
@@ -689,7 +657,7 @@ impl Loader {
|
||||
}
|
||||
let Some(file) = target.library() else {
|
||||
self.held.borrow_mut().remove(name);
|
||||
// What ran from a project's plugin whose build went stops now, not at the next reconcile (bigboi-8).
|
||||
// What ran from a project's plugin whose build went stops now, not at the next reconcile.
|
||||
if target.project {
|
||||
registry.unload(host, name);
|
||||
self.seen.borrow_mut().remove(name);
|
||||
@@ -698,7 +666,7 @@ impl Loader {
|
||||
registry.set_unloaded(name, None);
|
||||
return false;
|
||||
}
|
||||
// Why, with the way to load it where there is one (FT-10).
|
||||
// Why, with the way to load it where there is one.
|
||||
return skip(&match (&target.local, self.js()) {
|
||||
(None, true) => npm::missing(name),
|
||||
(None, false) => SKIPPED_OFF.to_owned(),
|
||||
@@ -711,12 +679,11 @@ impl Loader {
|
||||
Err(changed) => return changed,
|
||||
};
|
||||
self.waiting.borrow_mut().remove(name);
|
||||
// Nothing the build names may come from the project, or leave its private copy (bigboi-3).
|
||||
// Nothing the build names may come from the project, or leave its private copy.
|
||||
let checked = deps::check(&bytes, target.project);
|
||||
// Opening the library runs its code: the record names the build while it does, before its ID is known.
|
||||
let slot = registry.monitor().slot(&crate::contain::Artifact::external("", name, &format!("{digest:016x}")));
|
||||
// A crash in a build the record cannot name would restart into the same build: it does not run at all (final
|
||||
// review big-boi 11).
|
||||
// Do not run an unrecordable build: a crash would restart the same plugin.
|
||||
let checked = checked.and_then(|()| match registry.monitor().attributed(slot) {
|
||||
true => Ok(()),
|
||||
false => Err(format!(
|
||||
@@ -799,14 +766,14 @@ impl Loader {
|
||||
) -> bool {
|
||||
let name = target.target.as_str();
|
||||
// A project's TypeScript plugin runs only once the user approved its files, as a native build does: until then
|
||||
// nothing of it reaches the JS host, which does not start for it. What the JS host imports is a copy of exactly
|
||||
// the approved files (bigboi P8-1); a save since the approval holds the plugin back for a decision on it.
|
||||
// Its files are hashed and copied off the UI thread (FT-2): until the first walk, or the copy of an approved
|
||||
// tree, ended it is starting. A copy that does not stage, as the files changed under a stamp the walk could not
|
||||
// tell from the approved one, is held back with why, and its tree is hashed whole again off the UI thread: the
|
||||
// new build is asked about once that walk ends. A package from the npm cache a server part names (O-162) is
|
||||
// approved by its files and its install's `package.json` and lockfile ([`Artifact::tree`]), and runs where it is:
|
||||
// its dependencies sit beside it, not in it, so a copy of it could not import them.
|
||||
// nothing of it reaches the JS host, which does not start for it. What the JS host imports is a copy of
|
||||
// exactly the approved files; a save since the approval holds the plugin back for a decision on it. Its files
|
||||
// are hashed and copied off the UI thread: until the first walk, or the copy of an approved tree, ended it is
|
||||
// starting. A copy that does not stage, as the files changed under a stamp the walk could not tell from the
|
||||
// approved one, is held back with why, and its tree is hashed whole again off the UI thread: the new build is
|
||||
// asked about once that walk ends. A package from the npm cache a server part names is approved by its files
|
||||
// and its install's `package.json` and lockfile ([`Artifact::tree`]), and runs where it is: its dependencies
|
||||
// sit beside it, not in it, so a copy of it could not import them.
|
||||
let package = self.packages.borrow().values().any(|known| known.directory == dir);
|
||||
let staged = match target.project {
|
||||
true => {
|
||||
@@ -833,8 +800,8 @@ impl Loader {
|
||||
false => None,
|
||||
};
|
||||
let dir = staged.as_deref().unwrap_or(dir);
|
||||
// Safe mode holds it as it holds a library (review carbon-1). A crash or a client no parent guards does not:
|
||||
// nothing of it runs in this process.
|
||||
// Safe mode holds it as it holds a library. A crash or a client no parent guards does not: nothing of it runs
|
||||
// in this process.
|
||||
let was_held = registry.held(name);
|
||||
if !registry.admit_script(name) {
|
||||
scripts.forget(name);
|
||||
@@ -846,7 +813,7 @@ impl Loader {
|
||||
}
|
||||
match scripts.step(name, dir, target.options.as_deref(), staged.is_some()) {
|
||||
Step::Same => false,
|
||||
// Its setup runs only when it starts enabled (review carbon-8).
|
||||
// Its setup runs only when it starts enabled.
|
||||
Step::Described(id) => {
|
||||
match registry.starts_enabled(name, &id) {
|
||||
true => scripts.set_up(name),
|
||||
@@ -873,7 +840,6 @@ impl Loader {
|
||||
}
|
||||
Step::Failed(_, digest) if self.seen.borrow().get(name).is_some_and(|seen| seen.digest == digest) => false,
|
||||
Step::Failed(error, digest) => {
|
||||
// Named by its package, as a skipped one is, not by its path (CT-6, FT-15).
|
||||
if let Some(package) = package_name(dir) {
|
||||
registry.set_label(name, package);
|
||||
}
|
||||
@@ -881,7 +847,7 @@ impl Loader {
|
||||
}
|
||||
Step::Ready(definition, error, digest) => {
|
||||
if registry.id_taken(&definition.id, name) {
|
||||
// What the JS host set up of it goes (review carbon-2).
|
||||
// What the JS host set up of it goes.
|
||||
scripts.forget(name);
|
||||
let error = format!("plugin ID {} is already registered", definition.id);
|
||||
return self.fail(&**host, registry, listed, name, digest, error);
|
||||
@@ -997,8 +963,7 @@ impl Loader {
|
||||
};
|
||||
// The registry asks the running build whether it panicked, without the last reload's failure.
|
||||
reload.take();
|
||||
// Told as listed, as TS compares the failures it lists: a failure that left the previous version running
|
||||
// is new after the same error without it.
|
||||
// The same error is a new notification if the previous build no longer runs.
|
||||
let error = match registry.failed_load(target, &error) {
|
||||
true => reload.borrow_mut().insert(format!("{error} (previous version still active)")).clone(),
|
||||
false => error,
|
||||
@@ -1007,11 +972,11 @@ impl Loader {
|
||||
true
|
||||
}
|
||||
|
||||
/// Records the user's `decision` on `artifact`, the build of `target` they were shown (bigboi-1, carbon-1), once
|
||||
/// `now`, what [`Loader::found`] identified on the disk after the answer, is that build. It is recorded only while
|
||||
/// that build is the one held back: `Ok(false)` records nothing when the build changed since, and the user is asked
|
||||
/// about the new one. An error when it cannot be saved; nothing changes then. The next [`Loader::reconcile`]
|
||||
/// applies it: an approved build loads, a declined one is not asked about again.
|
||||
/// Records the user's `decision` on `artifact`, the build of `target` they were shown, once `now`, what
|
||||
/// [`Loader::found`] identified on the disk after the answer, is that build. It is recorded only while that build
|
||||
/// is the one held back: `Ok(false)` records nothing when the build changed since, and the user is asked about the
|
||||
/// new one. An error when it cannot be saved; nothing changes then. The next [`Loader::reconcile`] applies it: an
|
||||
/// approved build loads, a declined one is not asked about again.
|
||||
pub fn decide(
|
||||
&self,
|
||||
target: &str,
|
||||
@@ -1022,16 +987,14 @@ impl Loader {
|
||||
if self.held.borrow().get(target) != Some(&Ok(artifact.clone())) {
|
||||
return Ok(false);
|
||||
}
|
||||
// A build that changed since the question opened, before the watcher told the loader, leaves no decision behind
|
||||
// for either build (final review big-boi 9). The load still hashes what it opens.
|
||||
// An approval applies only if the build on disk still matches the one shown in the prompt.
|
||||
if now.as_ref().is_none_or(|now| now.as_ref() != Ok(artifact)) {
|
||||
return Ok(false);
|
||||
}
|
||||
self.approvals.decide(artifact, decision).map(|()| true)
|
||||
}
|
||||
|
||||
/// Counts the user's answer on `target`, whose check of the disk may end after a later answer's (review jsnpm-5).
|
||||
/// The count goes to [`Loader::superseded`] once the check ended.
|
||||
/// Sequence answers because their disk checks can finish out of order.
|
||||
pub fn deciding(&self, target: &str) -> u64 {
|
||||
let mut answers = self.answers.borrow_mut();
|
||||
let answer = answers.entry(target.to_owned()).or_default();
|
||||
@@ -1076,7 +1039,7 @@ impl Loader {
|
||||
listed: &Option<Status>,
|
||||
) -> Result<Build, bool> {
|
||||
let name = target.target.as_str();
|
||||
// Setup runs with the options, so new options load the build again (TS `sameGeneration`).
|
||||
// Setup runs with the options, so new options load the build again.
|
||||
let digest = |build: &[u8]| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(build);
|
||||
@@ -1087,7 +1050,7 @@ impl Loader {
|
||||
let (digest, bytes, quarantine) = match target.project {
|
||||
// A project's build runs only once the user approved this artifact (3.9). Until then nothing of it is read
|
||||
// but its hash, nothing is opened, and it claims nothing. What is loaded is what was hashed. When it
|
||||
// cannot be identified, what ran from it stops (bigboi-8) and nothing is reported (carbon-5).
|
||||
// cannot be identified, what ran from it stops and nothing is reported.
|
||||
true => {
|
||||
let (artifact, mut handle) = match Artifact::open(target.local.as_deref().unwrap_or(file), file) {
|
||||
Ok((artifact, handle)) => (self.approved(host, registry, name, Ok(artifact))?, handle),
|
||||
@@ -1097,7 +1060,7 @@ impl Loader {
|
||||
if unchanged(digest) {
|
||||
return Err(false);
|
||||
}
|
||||
// The quarantine of the file that was hashed, read through its descriptor (big-boi 3).
|
||||
// The quarantine of the file that was hashed, read through its descriptor.
|
||||
let read = artifact.bytes(&mut handle).and_then(|bytes| {
|
||||
let quarantine = quarantine::read(&handle).map_err(|error| format!("{}: {error}", file.display()));
|
||||
Ok((bytes, quarantine?))
|
||||
@@ -1142,7 +1105,7 @@ impl Loader {
|
||||
}
|
||||
};
|
||||
let build = format!("{digest:016x}");
|
||||
// A held build is not opened at all: no initializer, no `describe`, nothing of it runs (synthesis 4.5).
|
||||
// A held build is not opened at all: no initializer, no `describe`, nothing of it runs.
|
||||
let was_held = registry.held(name);
|
||||
if !registry.admit(name, &build) {
|
||||
if self.seen.borrow_mut().remove(name).is_some() {
|
||||
@@ -1154,9 +1117,8 @@ impl Loader {
|
||||
Ok((digest, bytes, quarantine))
|
||||
}
|
||||
|
||||
/// The one place that decides whether a project's plugin `target` may run: `artifact` (or why it cannot be read),
|
||||
/// when the user approved exactly it; otherwise it is held back, and the error says whether the manager's list
|
||||
/// changed. A native build and a TypeScript plugin go through it alike (3.9, P7).
|
||||
/// Returns the approved artifact or holds the target pending. The error indicates whether the manager list
|
||||
/// changed.
|
||||
fn approved(
|
||||
&self,
|
||||
host: &Rc<dyn Host>,
|
||||
@@ -1273,9 +1235,8 @@ fn identity(file: &Path) -> Option<(u64, u64)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a native build is among the targets: the discovered directories and the `configured` entries, enabled or
|
||||
/// not. The client starts under a parent only then (synthesis 4.5, decision 5). It reads directories and no library. With
|
||||
/// Luau on, a Luau plugin's directory counts as a native build.
|
||||
/// Checks targets for native builds without opening a library. Disabled targets count because they can be enabled
|
||||
/// later.
|
||||
pub fn has_native_build(config_dir: &Path, cwd: &Path, configured: &[&str]) -> bool {
|
||||
let discovered = discover(&plugin_directories(config_dir, cwd)).into_iter().map(Some);
|
||||
let configured = configured.iter().map(|target| local_source(target, config_dir));
|
||||
@@ -1293,9 +1254,9 @@ pub fn has_native_build(config_dir: &Path, cwd: &Path, configured: &[&str]) -> b
|
||||
})
|
||||
}
|
||||
|
||||
/// The `plugins` directories to search (TS `localPluginDirectories`): the global config directory's, then each
|
||||
/// `.opencode` directory from the project root ([`project_root`]) down to `cwd`. Directories other than the global
|
||||
/// one and the project's that do not exist are left out.
|
||||
/// The `plugins` directories to search: the global config directory's, then each `.opencode` directory from the
|
||||
/// project root ([`project_root`]) down to `cwd`. Directories other than the global one and the project's that do not
|
||||
/// exist are left out.
|
||||
pub fn plugin_directories(config_dir: &Path, cwd: &Path) -> Vec<PathBuf> {
|
||||
let ancestors: Vec<PathBuf> = {
|
||||
let mut ancestors: Vec<PathBuf> = cwd.ancestors().map(Path::to_path_buf).collect();
|
||||
@@ -1322,8 +1283,7 @@ pub fn plugin_directories(config_dir: &Path, cwd: &Path) -> Vec<PathBuf> {
|
||||
unique.into_iter().map(|dir| dir.join("plugins")).collect()
|
||||
}
|
||||
|
||||
/// The plugin directories inside `directories` (TS `discoverPluginTargets`): every subdirectory, or symlink to
|
||||
/// one, by name in each.
|
||||
/// The plugin directories inside `directories`: every subdirectory, or symlink to one, by name in each.
|
||||
pub fn discover(directories: &[PathBuf]) -> Vec<PathBuf> {
|
||||
directories
|
||||
.iter()
|
||||
@@ -1345,10 +1305,10 @@ pub fn discover(directories: &[PathBuf]) -> Vec<PathBuf> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The local path a `plugins` target names (TS `localSource`): a `file://` URL, or a `./`, `../`, or absolute
|
||||
/// path resolved against `directory`. A package name is not local. A URL decodes as TS `fileURLToPath` does; one
|
||||
/// that names no local file (a remote host) is not local. Absolute is `path.isAbsolute`: on Windows a rooted path
|
||||
/// without a drive (`/abs/x`) is absolute too and takes `directory`'s drive.
|
||||
/// The local path a `plugins` target names: a `file://` URL, or a `./`, `../`, or absolute path resolved against
|
||||
/// `directory`. A package name is not local. A URL decodes as TS `fileURLToPath` does; one that names no local file (a
|
||||
/// remote host) is not local. Absolute is `path.isAbsolute`: on Windows a rooted path without a drive (`/abs/x`) is
|
||||
/// absolute too and takes `directory`'s drive.
|
||||
pub fn local_source(target: &str, directory: &Path) -> Option<PathBuf> {
|
||||
let path = if target.starts_with("file://") {
|
||||
opencode_api_types::js::parse_url(target).ok()?.to_file_path().ok()?
|
||||
|
||||
@@ -1,38 +1,7 @@
|
||||
//! The native backend (decision O-42): plugins are shared libraries on the C ABI of `opencode-plugin-abi`,
|
||||
//! loaded with `opencode_util::dl`. There is no sandbox; it is the user's machine. The host only keeps a plugin's
|
||||
//! panics out of the TUI:
|
||||
//!
|
||||
//! - the plugin's shims catch its panics, and the host's callbacks catch the host's, so no panic unwinds across
|
||||
//! the boundary (a crash such as a segfault still takes the process down);
|
||||
//! - a panic fails the plugin: it is not called again, its fences fall back to the code view, its slots and routes
|
||||
//! draw empty, the plugin manager lists it as `failed` with the message, and a toast says so. Enabling it again
|
||||
//! in the plugin manager starts a fresh instance. Nothing the call that panicked asked for happens, and the storage
|
||||
//! it wrote gets back what it held, as for a built-in;
|
||||
//! - host effects (toasts, attention, routes, dispatches, storage notifications) wait until the plugin returns, on the
|
||||
//! effect queue in-process plugins share, so it never reenters itself through the host.
|
||||
//!
|
||||
//! An instance lives while its plugin is active: deactivation, unload and reload destroy it at once, whatever still
|
||||
//! holds a claim, route or fence of it, which then draw nothing.
|
||||
//!
|
||||
//! Every call into a plugin runs on the UI thread. A plugin that works on its own thread calls `wake`, which posts
|
||||
//! through the app's proxy; the host then asks that plugin's mounted claims to render again. A wake that finds the
|
||||
//! proxy's queue full is delivered once it has room, so the last one is never lost. Its threads `send` messages to its
|
||||
//! mailbox ([`crate::mailbox`]), which the UI thread hands to the plugin one call each.
|
||||
//!
|
||||
//! Versions follow the ABI's rules. The host serves ABI 2.0 to a library that exports [`abi::ENTRY`]. A major the host
|
||||
//! does not serve (also ABI 1.x, whose libraries export `opencode_plugin_v1`, decision O-169), a table shorter than
|
||||
//! 2.0's, a plugin that requires a newer host minor version, or one that requires a feature the host lacks is refused.
|
||||
//! Entries a later minor appends past the plugin's table size are absent.
|
||||
//!
|
||||
//! What the host takes from a plugin is decoded before anything of the call is applied: a buffer it cannot decode,
|
||||
//! or one that breaks the contract, fails the plugin and leaves no effect, as a panic does (4.14, `no-effects`).
|
||||
//!
|
||||
//! Every crossing of the C ABI on the UI thread is told to the conformance tap ([`crate::conformance`]), which records
|
||||
//! golden transcripts and checks the C ABI's protocol in the tests; it costs one thread-local read when nobody listens.
|
||||
//!
|
||||
//! Each build is copied to a file of its own before it is opened, because the platform loader returns the
|
||||
//! library already open at a path, and a rebuilt library is often written over the old one. Libraries are never
|
||||
//! unloaded: a running plugin's code must outlive every pointer into it, and a reload leaks one library.
|
||||
//! Loads native plugins through the C ABI. Native code runs in process; the panic boundary does not isolate a
|
||||
//! crash. Plugin effects commit when a call returns. If it panics, discard the effects, restore storage and stop
|
||||
//! calling the plugin until reactivation. Worker threads communicate through the mailbox and wake the UI thread for
|
||||
//! rendering. Deactivation destroys the instance even if a widget still holds one of its registrations.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
@@ -70,8 +39,8 @@ use crate::{Definition, ErrorFn, Host, Setup, Undo, defer, fail, next_request, r
|
||||
/// The host's minor version of the current major: it serves every entry and request up to it.
|
||||
pub const HOST_MINOR: u32 = ABI_MINOR;
|
||||
|
||||
/// The entry of ABI 1.x, which no host serves any more (O-169): a library that exports it alone is refused by its
|
||||
/// major, with a reason, not as no plugin.
|
||||
/// The entry of ABI 1.x, which no host serves any more: a library that exports it alone is refused by its major, with
|
||||
/// a reason, not as no plugin.
|
||||
const ENTRY_V1: &str = "opencode_plugin_v1";
|
||||
|
||||
/// What crossed the C ABI on this thread, counted outside any plugin and any mount (4.14, `work`).
|
||||
@@ -167,9 +136,9 @@ fn define(library: Library, options: Option<&str>) -> Result<(Definition, ErrorF
|
||||
}
|
||||
let options = options.map(str::to_owned);
|
||||
// Setup runs on each activation only, so a disabled plugin starts nothing: loading a library runs its native
|
||||
// initializers, never its setup. A library names its ID in `describe`, before any `create` (big-boi 6).
|
||||
// The failure of the running instance, a panic, in a cell of each activation's own: a new activation leaves an old
|
||||
// one's failure as it was.
|
||||
// initializers, never its setup. A library names its ID in `describe`, before any `create`. The failure of the
|
||||
// running instance, a panic, in a cell of each activation's own: a new activation leaves an old one's failure as
|
||||
// it was.
|
||||
let current: Rc<RefCell<Rc<RefCell<Option<String>>>>> = Rc::default();
|
||||
let definition = Definition::fallible(id, {
|
||||
let current = current.clone();
|
||||
@@ -263,9 +232,8 @@ impl Library {
|
||||
}
|
||||
|
||||
/// Opens a library, `bytes` read from the file `source` with its raw quarantine, through a copy, so a new build
|
||||
/// can replace the file, through [`abi::ENTRY`]. On macOS the copy carries the quarantine the bytes were read with,
|
||||
/// so the system checks it as it would the file (review carbon-6, final review big-boi 3); a copy that cannot carry
|
||||
/// it is not opened.
|
||||
/// can replace the file, through [`abi::ENTRY`]. On macOS the copy carries the quarantine the bytes were read
|
||||
/// with, so the system checks it as it would the file; a copy that cannot carry it is not opened.
|
||||
fn open(bytes: &[u8], source: Option<(&Path, Option<&[u8]>)>) -> Result<Self, String> {
|
||||
let dir = staging()?;
|
||||
let file = dir.path().join(format!("plugin.{}", std::env::consts::DLL_EXTENSION));
|
||||
@@ -384,7 +352,7 @@ impl Library {
|
||||
|
||||
/// The directory a library's copy is opened from: one this process makes, owner-only, so nobody else can place or swap
|
||||
/// the file in it. Windows cannot remove a mapped library, so there the copies go under `opencode-plugins` in the temp
|
||||
/// directory, and each open removes the directories there that no process maps any more (review carbon-6).
|
||||
/// directory, and each open removes the directories there that no process maps any more.
|
||||
fn staging() -> Result<opencode_util::temp::TempDir, String> {
|
||||
let temp = std::env::temp_dir();
|
||||
let base = if cfg!(windows) { temp.join("opencode-plugins") } else { temp };
|
||||
@@ -411,10 +379,7 @@ fn sweep(base: &Path, age: Duration) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the system refused to open a library, in words a user can act on (4.5, reviews F12, bigboi-13, carbon-6), on
|
||||
/// macOS or elsewhere. On macOS a client signed with library validation refuses a library another team signed;
|
||||
/// `dyld` refuses one whose signature is missing or invalid, and one that carries the quarantine of a download
|
||||
/// (`quarantined`: the host put it on the copy, from the file `source`), with the same words.
|
||||
/// Explains a platform loader refusal, including macOS quarantine and library validation.
|
||||
pub fn explain_refusal(error: &str, macos: bool, quarantined: bool, source: Option<&Path>) -> String {
|
||||
let message = format!("cannot load the library: {error}");
|
||||
let lower = error.to_lowercase();
|
||||
@@ -466,7 +431,7 @@ pub(crate) struct Ctx {
|
||||
quiet: bool,
|
||||
/// A render or a view runs: it may read, and ask for nothing.
|
||||
pub(crate) read_only: bool,
|
||||
/// What the calls hold of the input (P2), from the end of setup: setup itself has no mount and no owner.
|
||||
/// What the calls hold of the input, from the end of setup: setup itself has no mount and no owner.
|
||||
pub(crate) owners: Option<Rc<crate::Owners>>,
|
||||
}
|
||||
|
||||
@@ -547,11 +512,11 @@ pub(crate) enum Effect {
|
||||
Title(String),
|
||||
Theme(String),
|
||||
InstallTheme(String, serde_json::Value),
|
||||
// 2.0 (P6c)
|
||||
|
||||
Setting(String, serde_json::Value),
|
||||
// 2.0 (P3): a scroll verb, bound to the mount it names when the plugin asked.
|
||||
// a scroll verb, bound to the mount it names when the plugin asked.
|
||||
Scroll(Box<dyn FnOnce()>),
|
||||
/// An input verb of P2, its owner taken as it was asked for.
|
||||
/// Capture the owner when the input verb is requested.
|
||||
Input(crate::Effect),
|
||||
}
|
||||
|
||||
@@ -593,11 +558,8 @@ thread_local! {
|
||||
static OVER_LIST: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
/// [`received`] for what a draw answered with `status`. The rules of every buffer come first: a descriptor
|
||||
/// [`received`] refuses is refused unread, whatever the status (re-review bigboi). An error or a panic is text, taken
|
||||
/// whole as any call's is. Only a list, an OK answer, is admitted by its length before a byte of it is copied (review
|
||||
/// bigboi 7): one past [`abi::canvas::MAX_BYTES`] is over its limit, which [`OVER_LIST`] tells and the canvas shows as
|
||||
/// its placeholder, if it starts as a list does; else it is malformed, as [`abi::canvas::check`] reads it.
|
||||
/// Validate the buffer descriptor before inspecting status or reading bytes. Only successful draw results are
|
||||
/// subject to display-list limits.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`received`].
|
||||
@@ -690,8 +652,7 @@ impl Instance {
|
||||
context.undo();
|
||||
return Err(format!("setup panicked: {}", text(bytes)));
|
||||
}
|
||||
// An error the host cannot read is refused before its status is: nothing of it happens, as for a call
|
||||
// (big-boi 8).
|
||||
// An error the host cannot read is refused before its status is: nothing of it happens, as for a call.
|
||||
if let Err(error) = bytes {
|
||||
context.undo();
|
||||
return Err(format!("setup returned a bad result: {error}"));
|
||||
@@ -951,7 +912,7 @@ unsafe extern "C" fn host_free(owned: Owned) {
|
||||
}
|
||||
|
||||
pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::Value, String> {
|
||||
// The host's names of a declared key, which no other plugin's key shares (review carbon-6).
|
||||
// The host's names of a declared key, which no other plugin's key shares.
|
||||
let key = |ctx: &Ctx, key: &str| {
|
||||
if ctx.id.is_empty() {
|
||||
return Err("the plugin ID is not known during setup".to_owned());
|
||||
@@ -1035,7 +996,7 @@ pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::
|
||||
HostRequest::Plugins => return read(ctx, &mut |read| serde_json::to_value(read.plugins())),
|
||||
HostRequest::Setting { name } => return read(ctx, &mut |read| serde_json::to_value(read.setting(&name))),
|
||||
HostRequest::ImageSize { bytes } => {
|
||||
// Bytes past what the host decodes show nothing, which their length says before they are decoded (PL-9).
|
||||
// Bytes past what the host decodes show nothing, which their length says before they are decoded.
|
||||
if (bytes.len() / 4 * 3) as u64 > crate::limits::get().image_bytes + 2 {
|
||||
return Ok(serde_json::Value::Null);
|
||||
}
|
||||
@@ -1043,7 +1004,7 @@ pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::
|
||||
return read(ctx, &mut |read| serde_json::to_value(read.image_size(&bytes)));
|
||||
}
|
||||
HostRequest::UtcOffset { at } => return read(ctx, &mut |read| serde_json::to_value(read.utc_offset(at))),
|
||||
// Past one node's text it is not measured (review bigboi 2): a plugin measures what it would draw.
|
||||
// Past one node's text it is not measured: a plugin measures what it would draw.
|
||||
HostRequest::Measure { text } if text.len() as u64 > crate::limits::get().text => {
|
||||
return Err(format!("a text of {} bytes to measure, more than a node holds", text.len()));
|
||||
}
|
||||
@@ -1069,7 +1030,7 @@ pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::
|
||||
HostRequest::Attention(attention) => ctx.effects.push(Effect::Attention(attention)),
|
||||
HostRequest::Navigate { route } => ctx.effects.push(Effect::Navigate(route)),
|
||||
HostRequest::Fetch(fetch) => {
|
||||
// An ID is a promise of a reply: none is given unless the fetch's effect has room (bigboi's final pass).
|
||||
// An ID is a promise of a reply: none is given unless the fetch's effect has room.
|
||||
if !crate::has_room(ctx.effects.len()) {
|
||||
return Err(crate::REFUSED.to_owned());
|
||||
}
|
||||
@@ -1167,9 +1128,9 @@ pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::
|
||||
ctx.effects.push(Effect::InstallTheme(name, theme));
|
||||
}
|
||||
}
|
||||
// 2.0 (P3): the verbs and reads of the mount whose handler runs, else of the plugin's newest live mount of a
|
||||
// surface, as for a built-in's command, which a library's command is bound to no mount like. A transcript verb
|
||||
// answers the user's input only.
|
||||
// the verbs and reads of the mount whose handler runs, else of the plugin's newest live mount of a surface, as
|
||||
// for a built-in's command, which a library's command is bound to no mount like. A transcript verb answers the
|
||||
// user's input only.
|
||||
HostRequest::Scroll { target, verb } => {
|
||||
if target == v2::Target::Transcript && !behave::in_handler() {
|
||||
return Err("a transcript verb outside a handler of the user's input is dropped".to_owned());
|
||||
@@ -1222,10 +1183,10 @@ pub(crate) fn handle(ctx: &mut Ctx, request: HostRequest) -> Result<serde_json::
|
||||
Ok(serde_json::Value::Null)
|
||||
}
|
||||
|
||||
/// The mount whose handler or view runs, which P3's verbs and reads name; `None` for a command, which is bound to no
|
||||
/// mount: then the plugin's newest live mount of the surface.
|
||||
/// Scroll commands use the current call's mount, or the newest live mount of the named surface if called outside a
|
||||
/// mount.
|
||||
fn called_mount(ctx: &Ctx) -> Option<std::rc::Weak<()>> {
|
||||
// The mount the call is of, also a route command's, which holds no input (carbon own-1).
|
||||
// The mount the call is of, also a route command's, which holds no input.
|
||||
ctx.owners.as_ref().and_then(|owners| owners.owning())
|
||||
}
|
||||
|
||||
@@ -1376,7 +1337,7 @@ struct Guest {
|
||||
revoked: RefCell<Vec<Disposer>>,
|
||||
/// The mounted slot claims and routes, which a wake draws again.
|
||||
activation: Rc<Activation>,
|
||||
/// What its calls hold of the input (P2).
|
||||
/// What its calls hold of the input.
|
||||
owners: Rc<crate::Owners>,
|
||||
monitor: Rc<crate::contain::Monitor>,
|
||||
slot: crate::contain::Slot,
|
||||
@@ -1408,12 +1369,9 @@ impl Guest {
|
||||
self.checked(export, request, |_: &T| Ok(()))
|
||||
}
|
||||
|
||||
/// [`Guest::request`] whose result `check` must accept. A result the host cannot decode, or that `check` refuses,
|
||||
/// fails the plugin as a panic does: what the call asked for is dropped, and the storage it wrote put back. An
|
||||
/// error the plugin returns is an answer: what the call asked for happens, and the plugin then fails (4.14). A
|
||||
/// render or a view may ask for nothing ([`renders`]). A call that returned late (an overrun, synthesis 4.4) did
|
||||
/// return: what it asked for happens, then it fails, which revokes it; a cause of the call's own (a refusal, or an
|
||||
/// error) names the failure before the overrun.
|
||||
/// Checks the result before committing the call's effects. Malformed or refused results roll back storage. An
|
||||
/// error returned by the plugin or an overrun after a valid result commits effects, then fails the plugin. The
|
||||
/// call's own error takes precedence over an overrun.
|
||||
fn checked<T: DeserializeOwned>(
|
||||
self: &Rc<Self>,
|
||||
export: &'static str,
|
||||
@@ -1504,7 +1462,7 @@ impl Guest {
|
||||
let guest = Rc::downgrade(self);
|
||||
Rc::new(move |_: &dyn Host, owner: &Rc<crate::interact::Owner>, event: &abi::interact::Event| {
|
||||
let Some(guest) = guest.upgrade() else { return abi::interact::Handled::Pass };
|
||||
// A surface's handler hears which of its mounts the event is for (big-boi 4).
|
||||
// A surface's handler hears which of its mounts the event is for.
|
||||
let to = match to {
|
||||
To::Surface(surface) => abi::InputTo::Surface { surface, mount: owner.id().cloned() },
|
||||
To::Layer(layer) => abi::InputTo::Layer { layer },
|
||||
@@ -1525,14 +1483,14 @@ impl Guest {
|
||||
|
||||
/// Sends a request to a handler, then, if it ran, invalidates the claims, whose state it may have changed.
|
||||
fn handle(self: &Rc<Self>, export: &'static str, request: &Request) {
|
||||
// A handler answers `null` (O-135): anything else is a contract break.
|
||||
// A handler answers `null`: anything else is a contract break.
|
||||
if self.request::<()>(export, request).is_some() {
|
||||
self.activation.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a command, which answers `"pass"` to decline the key that ran it (contract ergonomics 2.5) and `null` to
|
||||
/// take it. A call that failed took its key.
|
||||
/// Runs a command, which answers `"pass"` to decline the key that ran it and `null` to take it. A call that
|
||||
/// failed took its key.
|
||||
fn command(self: &Rc<Self>, request: &Request) -> abi::interact::Handled {
|
||||
let answer = self.checked("run-command", request, |answer: &Option<String>| match answer.as_deref() {
|
||||
None | Some("pass") => Ok(()),
|
||||
@@ -1634,7 +1592,7 @@ pub(crate) fn reply_to(
|
||||
if mount.upgrade().is_none() {
|
||||
return running.cancel(request);
|
||||
}
|
||||
// Past the cap the request is not sent, and its reply is that refusal (carbon ac-1).
|
||||
// Past the cap the request is not sent, and its reply is that refusal.
|
||||
if !wait(mount, guest, request) {
|
||||
let error = format!("more than {MOUNT_REQUESTS} requests of the plugin's mounts wait");
|
||||
return running.answer(Request::Reply { id: request, result: Err(error) });
|
||||
@@ -1662,7 +1620,7 @@ pub(crate) fn reply_to(
|
||||
pub(crate) const MOUNT_REQUESTS: usize = 1024;
|
||||
|
||||
/// The requests of mounts that wait for their reply ([`reply_to`]), by request and by mount, so that a reply and a
|
||||
/// mount's close each touch only their own (bigboi's ownership pass), and how many each instance has.
|
||||
/// mount's close each touch only their own, and how many each instance has.
|
||||
#[derive(Default)]
|
||||
struct Inflight {
|
||||
/// Each request: its mount's key, and the instance that asked.
|
||||
@@ -1738,9 +1696,9 @@ fn take_inflight(request: abi::RequestId) -> bool {
|
||||
}
|
||||
|
||||
/// Cancels at once the waiting requests of the mount whose key is `key`, which closed, rather than once their replies
|
||||
/// come: the JS host's fetch of a mount that closed settles while the server still holds it (bigboi's freeze pass). A
|
||||
/// surface's mount calls it as it ends. Each cancel an instance hears is an effect of its own, so many spread over
|
||||
/// frames as replies do (carbon ac-1). How many requests it cancelled: no other mount's are looked at.
|
||||
/// come: the JS host's fetch of a mount that closed settles while the server still holds it. A surface's mount calls
|
||||
/// it as it ends. Each cancel an instance hears is an effect of its own, so many spread over frames as replies do. How
|
||||
/// many requests it cancelled: no other mount's are looked at.
|
||||
pub(crate) fn cancel_closed(key: usize) -> usize {
|
||||
let cancelled: Vec<_> = INFLIGHT.with_borrow_mut(|inflight| {
|
||||
let Some((_, waiting)) = inflight.mounts.remove(&key) else { return Vec::new() };
|
||||
@@ -1777,9 +1735,9 @@ fn owning(ctx: &Ctx) -> Option<Weak<()>> {
|
||||
ctx.owners.as_ref().and_then(|owners| owners.owning())
|
||||
}
|
||||
|
||||
/// Queues `effects` of plugin `id` on the effect queue, as the host would for a built-in; a fetch replies to `guest`, and
|
||||
/// a dialog belongs to activation `generation`. Each effect is an entry of its own, as on the linked carrier, so each
|
||||
/// counts against the frame's bound and the dispatch depth (review carbon new-1).
|
||||
/// Queues `effects` of plugin `id` on the effect queue, as the host would for a built-in; a fetch replies to `guest`,
|
||||
/// and a dialog belongs to activation `generation`. Each effect is an entry of its own, as on the linked carrier, so
|
||||
/// each counts against the frame's bound and the dispatch depth.
|
||||
pub(crate) fn apply(
|
||||
host: &Weak<dyn Host>,
|
||||
id: String,
|
||||
@@ -1828,7 +1786,7 @@ fn run(host: &dyn Host, effect: Effect, id: &str, guest: &Weak<dyn Answers>, gen
|
||||
Effect::ClearSelection => host.clear_selection(),
|
||||
Effect::Foreground(request, program, mount) => {
|
||||
// The program starts later, once the turn is done: only if the instance is still live then, and the mount
|
||||
// that owns it is still open (bigboi's freeze pass).
|
||||
// that owns it is still open.
|
||||
let (owner, owning) = (guest.clone(), mount.clone());
|
||||
let alive = Box::new(move || {
|
||||
let open = owning.as_ref().is_none_or(|mount| mount.upgrade().is_some());
|
||||
@@ -1974,7 +1932,7 @@ fn register(setup: &mut Setup<'_>, guest: &Rc<Guest>, manifest: &Manifest) {
|
||||
});
|
||||
setup.view_route(name, render, route::commands(&scoped, name), mount, &activation);
|
||||
}
|
||||
// P2: the searches, and the layers of setup, each with its own handler, the activation's.
|
||||
// the searches, and the layers of setup, each with its own handler, the activation's.
|
||||
for name in &manifest.searches {
|
||||
let (guest, searched) = (guest.clone(), name.clone());
|
||||
let call: crate::SearchCall = Rc::new(move |_: &dyn Host, query: &str, options: &[abi::SelectOption]| {
|
||||
@@ -1988,7 +1946,7 @@ fn register(setup: &mut Setup<'_>, guest: &Rc<Guest>, manifest: &Manifest) {
|
||||
let deliver = guest.deliver(To::Layer(index));
|
||||
guest.owners.input.register(&**setup.host(), std::slice::from_ref(layer), &deliver);
|
||||
}
|
||||
// 2.0: the surfaces, whose views run through `View`.
|
||||
// the surfaces, whose views run through `View`.
|
||||
for (index, claim) in manifest.surfaces.iter().enumerate() {
|
||||
let at: v2::Place = (&claim.place).into();
|
||||
// A route's commands are bound to the mount they run for, as in process: what they ask for is that mount's.
|
||||
@@ -2019,7 +1977,7 @@ fn register(setup: &mut Setup<'_>, guest: &Rc<Guest>, manifest: &Manifest) {
|
||||
guest.fail(error);
|
||||
}
|
||||
});
|
||||
// P3: `layout` and the scroll handler run as calls of the library, as its view does.
|
||||
// `layout` and the scroll handler run as calls of the library, as its view does.
|
||||
let place =
|
||||
surface::Place { name: claim.name.clone(), at, palette: claim.palette, notify: claim.notify.clone() };
|
||||
let calls = behave::Calls {
|
||||
@@ -2049,11 +2007,11 @@ fn register(setup: &mut Setup<'_>, guest: &Rc<Guest>, manifest: &Manifest) {
|
||||
let remote = Rc::new(Remote { guest: guest.clone(), index, draw: claim.draw });
|
||||
setup.surface(place, remote, commands, fail, calls, &guest.owners, input);
|
||||
}
|
||||
// 2.0: the renderer claims, whose views run through `Claim`.
|
||||
// the renderer claims, whose views run through `Claim`.
|
||||
for (index, entry) in manifest.claims.iter().enumerate() {
|
||||
setup.renderer_claim(entry.clone(), Rc::new(RemoteClaim { guest: guest.clone(), index }), &guest.owners);
|
||||
}
|
||||
// 2.0: what the plugin's threads send runs `Message`, one call each, when its manifest says it takes messages; a
|
||||
// what the plugin's threads send runs `Message`, one call each, when its manifest says it takes messages; a
|
||||
// thread's panic fails the plugin, once.
|
||||
if !manifest.messages {
|
||||
guest.activation.mailbox.refuse_messages();
|
||||
@@ -2078,7 +2036,6 @@ fn register(setup: &mut Setup<'_>, guest: &Rc<Guest>, manifest: &Manifest) {
|
||||
pub(crate) fn keyed(node: &v2::Node, kept: &dyn Fn(&str) -> usize) -> usize {
|
||||
let inside: usize = match node {
|
||||
v2::Node::Keep { key } => return kept(key).max(1),
|
||||
// A list's items are nodes of the tree too (P6c: a memo a list item).
|
||||
v2::Node::List { items, .. } => items.iter().map(|item| keyed(&item.node, kept)).sum(),
|
||||
_ => node.children().iter().map(|child| keyed(child, kept)).sum(),
|
||||
};
|
||||
|
||||
@@ -977,8 +977,7 @@ fn verbed(host: &Rc<TestHost>, registry: &Registry) -> Verbed {
|
||||
host.app.advance(Duration::from_millis(1));
|
||||
host.app().root().clear();
|
||||
host.app().root().add(parent);
|
||||
// One frame: the claim shows what it renders for its size in the frame that lays it out (reviews bigboi-3,
|
||||
// carbon-2).
|
||||
// One frame: the claim shows what it renders for its size in the frame that lays it out.
|
||||
let text = host.app.render().text();
|
||||
text.lines().find(|line| line.contains("sample reads:")).unwrap_or_default().trim().to_owned()
|
||||
};
|
||||
@@ -2018,7 +2017,7 @@ unsafe extern "C" fn raw_call(_: *mut c_void, request: Bytes, out: *mut Owned) -
|
||||
r#"{"type":"toast","variant":"info","message":"from a render"}"#,
|
||||
r#"{"type":"dialog","dialog":{"type":"alert","title":"T","message":"M"}}"#,
|
||||
r#"{"type":"storage-set","key":"k","value":"{\"a\":1}"}"#,
|
||||
// The small verbs (review bigboi-13).
|
||||
// The small verbs.
|
||||
r#"{"type":"set-variant","variant":"high"}"#,
|
||||
r#"{"type":"set-model","provider":"p","model":"m"}"#,
|
||||
r#"{"type":"tab","edit":{"type":"focus","session":"ses_1"}}"#,
|
||||
@@ -2027,7 +2026,7 @@ unsafe extern "C" fn raw_call(_: *mut c_void, request: Bytes, out: *mut Owned) -
|
||||
r#"{"type":"title","title":"t"}"#,
|
||||
r#"{"type":"set-theme","name":"nord"}"#,
|
||||
r#"{"type":"install-theme","name":"x","theme":{"theme":{}}}"#,
|
||||
// 2.0 (P3).
|
||||
// .
|
||||
r#"{"type":"scroll","target":{"type":"node","surface":"s","id":"l"},"verb":{"type":"by","rows":1}}"#,
|
||||
];
|
||||
let statuses = asks.iter().map(|ask| table.call(ask).0);
|
||||
@@ -2620,7 +2619,7 @@ fn a_library_macos_refuses_says_why() {
|
||||
);
|
||||
}
|
||||
assert_eq!(explain_refusal(missing, true, false, Some(source)), format!("cannot load the library: {missing}"));
|
||||
// Each of the words alone is enough (review carbon-7).
|
||||
// Each of the words alone is enough.
|
||||
let alone = [
|
||||
("mapping process and mapped file have different Team IDs", "library validation"),
|
||||
("'x' is a platform binary", "library validation"),
|
||||
|
||||
@@ -1,26 +1,6 @@
|
||||
//! Where a plugin named by npm package lies in the package cache TS installs into, found as TS's `Npm.resolve` finds
|
||||
//! it (`packages/util/src/npm.ts:358-366`), which the TS client asks for a server plugin's TUI part, and after its
|
||||
//! install for a `cli.json` entry (`packages/cli/src/commands/handlers/default.ts:143`). Nothing is installed or
|
||||
//! fetched here: a package the cache does not hold is not found.
|
||||
//!
|
||||
//! The cache is `<cache>/npm/<key>` (`npm.ts:148`), `<cache>` the global cache directory (`~/.cache/opencode`). The
|
||||
//! key is the spec as written, not a version it resolves to (`npm.ts:92-97`):
|
||||
//!
|
||||
//! - a registry spec (a version, a range or a tag of a named package, as `npm-package-arg` parses it) is
|
||||
//! `<name>@<spec>`, the spec being `latest` for a bare name (`foo@latest`; `foo@^1` is `foo@^1`, `foo@` is `foo@*`);
|
||||
//! - a git spec (a git URL, an SCP `user@host:path`, or a spec on a known host, as `hosted-git-info` reads it: GitHub's
|
||||
//! `user/repo`, a `github:`, `gitlab:`, `bitbucket:`, `gist:` or `sourcehut:` shortcut, or an HTTPS or SSH URL of
|
||||
//! those hosts) is `git-<slug>-<the first 12 hex digits of the spec's SHA-256>`;
|
||||
//! - anything else (an alias, a directory, a tarball, a URL, a spec `npm-package-arg` refuses) is the spec itself.
|
||||
//!
|
||||
//! [`cache_key`] gives that key for every spec, as `Npm.cacheKey` does. [`resolve`] looks up only the first two: the
|
||||
//! others name no package TS's `parse` classifies, and keyed by their text they can lead out of the cache (carbon
|
||||
//! jsnpm-4).
|
||||
//!
|
||||
//! On Windows the characters a file name cannot hold become `_` (`sanitize`). Each install is a generation, a
|
||||
//! numbered directory; the newest, the largest number, is the one used (`npm.ts:149-162`), else the key's directory
|
||||
//! itself. The package is that directory's `node_modules/<name>`: the spec's name, else the first dependency of the
|
||||
//! generation's `package.json`, else the spec (`installedName`, `npm.ts:173-183`).
|
||||
//! Resolves installed plugins without fetching anything. The package cache keys a registry spec by its requested
|
||||
//! version or tag, and a git spec by its slug and a hash of the literal spec. Use the highest numbered generation.
|
||||
//! Unclassified specs can have cache keys but must never be joined to the cache path.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -39,10 +19,8 @@ pub fn missing(spec: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The package `spec` names in the cache under `cache`, if the cache holds it. Only a spec TS's `parse` classifies (a
|
||||
/// version, range or tag of a named package, or a git spec) is looked up, by its key, and only a package name `name`
|
||||
/// or `@scope/name` is joined to the path; the package found must lie under `<cache>/npm` once links are followed
|
||||
/// (carbon jsnpm-4). It is returned by its real path.
|
||||
/// Resolves a registry or git spec to a package inside the cache. Only valid package names may be joined to the
|
||||
/// generation directory.
|
||||
pub fn resolve(spec: &str, cache: &Path) -> Option<Package> {
|
||||
let target = parse(spec)?;
|
||||
let root = cache.join("npm");
|
||||
@@ -52,7 +30,7 @@ pub fn resolve(spec: &str, cache: &Path) -> Option<Package> {
|
||||
if !valid_name(&name) {
|
||||
return None;
|
||||
}
|
||||
// Real paths, without Windows' verbatim prefix: the JS host is handed this one (carbon recheck-3).
|
||||
// Real paths, without Windows' verbatim prefix: the JS host is handed this one.
|
||||
let directory = super::real(&base.join("node_modules").join(&name))?;
|
||||
let inside = super::real(&root).is_some_and(|root| directory.starts_with(root));
|
||||
(inside && directory.is_dir()).then_some(Package { directory, name })
|
||||
@@ -79,12 +57,12 @@ enum Kind {
|
||||
Git,
|
||||
}
|
||||
|
||||
/// The directory under `<cache>/npm` that holds the installs of `spec` (TS `Npm.cacheKey`).
|
||||
/// The directory under `<cache>/npm` that holds the installs of `spec`.
|
||||
pub fn cache_key(spec: &str) -> String {
|
||||
key(spec, parse(spec).as_ref())
|
||||
}
|
||||
|
||||
/// The cache key of `spec` (`key`, `npm.ts:92-97`).
|
||||
/// Computes the key used by the shared npm cache.
|
||||
fn key(spec: &str, target: Option<&Target>) -> String {
|
||||
match target {
|
||||
Some(Target { kind: Kind::Registry(range), name: Some(name) }) => sanitize(&format!("{name}@{range}")),
|
||||
@@ -97,8 +75,7 @@ fn key(spec: &str, target: Option<&Target>) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// `parse` (`npm.ts:68-90`): a registry target for a version, range or tag of a named package, a git target, or none
|
||||
/// for any other spec and for one `npm-package-arg` refuses.
|
||||
/// Classifies installable registry and git specs.
|
||||
fn parse(spec: &str) -> Option<Target> {
|
||||
match npa(spec).ok()? {
|
||||
Npa::Git(name) => Some(Target { kind: Kind::Git, name }),
|
||||
@@ -531,7 +508,6 @@ fn correct_url(mut giturl: String) -> String {
|
||||
giturl
|
||||
}
|
||||
|
||||
/// `gitSlug` (`npm.ts:99-115`).
|
||||
fn git_slug(spec: &str) -> String {
|
||||
let target = spec.split('#').next().unwrap_or_default();
|
||||
let target = percent_decode(target).unwrap_or_else(|| target.to_owned());
|
||||
@@ -585,7 +561,7 @@ fn percent_decode(text: &str) -> Option<String> {
|
||||
String::from_utf8(out).ok()
|
||||
}
|
||||
|
||||
/// `sanitize` (`npm.ts:45-50`): on Windows, `<>:"|?*` and control characters become `_`.
|
||||
/// Windows filenames cannot contain control characters or `<>:"|?*`.
|
||||
fn sanitize(key: &str) -> String {
|
||||
match cfg!(windows) {
|
||||
true => {
|
||||
@@ -621,8 +597,6 @@ fn first_dependency(base: &Path) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Expected (TS `Npm.resolve`): the newest generation's `node_modules/<name>`; a scoped name nests; a git spec's
|
||||
// name is the generation's first dependency; nothing in the cache, or only a key without the package, is not found.
|
||||
#[test]
|
||||
fn a_package_resolves_in_the_newest_generation() {
|
||||
let temp = opencode_util::temp::tempdir().unwrap();
|
||||
@@ -652,10 +626,6 @@ mod tests {
|
||||
assert_eq!(resolve("baz", &cache), None);
|
||||
}
|
||||
|
||||
// Expected (carbon jsnpm-4): nothing outside `<cache>/npm` is found. A spec TS's `parse` does not classify (one
|
||||
// that climbs with `..`, a tarball, a URL) is not looked up, even where its key's directory holds a package; a
|
||||
// `dependencies` key that is not a package name (absolute, `..`) is not joined; a package that is a link out of the
|
||||
// cache is refused. A registry spec and a git spec still are found, by their real paths.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn nothing_outside_the_cache_is_found() {
|
||||
@@ -679,7 +649,6 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(resolve(spec, &cache), None, "{key}");
|
||||
}
|
||||
// Keyed by the spec itself, as TS keys it, and holding a package: still not looked up.
|
||||
let tarball = generation("plugin.tgz");
|
||||
std::fs::create_dir_all(tarball.join("node_modules").join("plugin.tgz")).unwrap();
|
||||
assert_eq!(resolve("plugin.tgz", &cache), None);
|
||||
@@ -697,7 +666,6 @@ mod tests {
|
||||
assert_eq!(resolve("github:u/r", &cache).map(|package| package.name), Some("@s/real".to_owned()));
|
||||
}
|
||||
|
||||
// Expected (`validate-npm-package-name` 7, `validForOldPackages`): the names npm-package-arg takes.
|
||||
#[test]
|
||||
fn a_package_name_is_validated_as_npm_does() {
|
||||
for name in ["foo", "Foo", "fs", "foo.bar", "foo~", "@s/foo", "@s/Foo", "@../x", "a!"] {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
//! The quarantine macOS gives a download (`com.apple.quarantine`), which the private copy of a library carries so the
|
||||
//! system checks the copy as it would the file (review carbon-6). It is read through the descriptor the library's
|
||||
//! bytes were read through, as its raw bytes, so the copy carries the attribute of the very file that was hashed and
|
||||
//! loaded, not of whatever the name leads to later (final review big-boi 3). An attribute that is not there is told
|
||||
//! from one that cannot be read, which refuses the library. Elsewhere there is no quarantine.
|
||||
//! Preserves macOS quarantine on the private copy the loader opens. Read the raw attribute from the same file
|
||||
//! descriptor as the library bytes. A missing attribute is allowed; an unreadable one is an error.
|
||||
|
||||
use std::fs::File;
|
||||
|
||||
@@ -26,8 +23,7 @@ thread_local! {
|
||||
static FAIL: std::cell::Cell<Option<std::io::Error>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Makes the next [`read`] on this thread fail with `error`, as an attribute the system cannot read does on macOS:
|
||||
/// what the loader does then runs on every platform (final re-review big-boi 3).
|
||||
/// Forces the next quarantine read on this thread to fail.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn fail_next_read(error: std::io::Error) {
|
||||
FAIL.set(Some(error));
|
||||
@@ -110,9 +106,6 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
// Expected (final review big-boi 3; runs on macOS only): the quarantine is read through the descriptor as its raw
|
||||
// bytes, absent is `None`, and once the name leads to another file the descriptor still reads the file that was
|
||||
// opened; a copy given the value carries the same bytes.
|
||||
#[test]
|
||||
fn the_quarantine_is_read_through_the_descriptor() {
|
||||
let dir = opencode_util::temp::TempDir::new().unwrap();
|
||||
@@ -134,8 +127,6 @@ mod tests {
|
||||
assert_eq!(read(©), Ok(Some(value)));
|
||||
}
|
||||
|
||||
// Expected (final re-review big-boi 3; macOS only): an attribute that is not there, or a file system that holds
|
||||
// none, is no quarantine; every other error is one the library is refused for.
|
||||
#[test]
|
||||
fn only_absence_is_no_quarantine() {
|
||||
for (errno, absent) in [(libc::ENOATTR, true), (libc::ENOTSUP, true), (libc::EACCES, false), (libc::EIO, false)]
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(crate) struct TestHost {
|
||||
pub deltas: Rc<RefCell<Vec<crate::Deltas>>>,
|
||||
/// The replies of the programs run in the foreground, which [`TestHost::exit`] delivers.
|
||||
pub programs: RefCell<Vec<(Alive, Reply)>>,
|
||||
/// The plugins' input (P2): their layers, listeners, pointer capture and pastes.
|
||||
/// The plugins' input: their layers, listeners, pointer capture and pastes.
|
||||
pub router: crate::interact::Router,
|
||||
}
|
||||
|
||||
@@ -502,7 +502,6 @@ fn local_source_resolves_paths_and_urls_but_not_packages() {
|
||||
assert_eq!(local_source("@acme/opencode-tui", dir), None);
|
||||
// `\` is no separator here: `..\x` names a package, which the cache refuses.
|
||||
assert_eq!(local_source(r"..\x", dir), None);
|
||||
// Expected (r2 review, bigboi-ui-8 and carbon-ui-8): a file URL means what `fileURLToPath(new URL(spec))` says.
|
||||
assert_eq!(local_source("file:///a/My%20Plugin", dir), Some("/a/My Plugin".into()));
|
||||
assert_eq!(local_source("file://localhost/a/b", dir), Some("/a/b".into()));
|
||||
assert_eq!(local_source("file:///a/b/../c", dir), Some("/a/c".into()));
|
||||
@@ -516,7 +515,7 @@ fn local_source_resolves_paths_and_urls_but_not_packages() {
|
||||
let dir = Path::new(r"C:\Users\me\.config\opencode");
|
||||
assert_eq!(local_source("./plugins/x", dir), Some(r"C:\Users\me\.config\opencode\plugins\x".into()));
|
||||
assert_eq!(local_source("../x.wasm", dir), Some(r"C:\Users\me\.config\x.wasm".into()));
|
||||
// Windows' own relative forms (carbon jsnpm-4), which climb no further than a `/` form does.
|
||||
// Windows' own relative forms, which climb no further than a `/` form does.
|
||||
assert_eq!(local_source(r".\plugins\x", dir), Some(r"C:\Users\me\.config\opencode\plugins\x".into()));
|
||||
assert_eq!(local_source(r"..\..\..\x", dir), Some(r"C:\Users\x".into()));
|
||||
assert_eq!(local_source("/abs/x", dir), Some(r"C:\abs\x".into()));
|
||||
@@ -570,7 +569,6 @@ fn reconcile_loads_reloads_keeps_and_unloads() {
|
||||
assert_eq!(entry(&entries, &lib_target).source, Source::External);
|
||||
assert_eq!(entry(&entries, &lib_target).status, Status::Active);
|
||||
assert_eq!(entry(&entries, &file_target).id, "extra");
|
||||
// Skipped with why and how to load it, and named by its package rather than its path (FT-10, FT-15).
|
||||
assert_eq!(entry(&entries, &ts_target).status, Status::Skipped(SKIPPED_OFF.to_owned()));
|
||||
assert_eq!(entry(&entries, &ts_target).id, "@acme/typescript-tui");
|
||||
assert_eq!(entry(&entries, "@acme/tui").status, Status::Skipped(SKIPPED_OFF.to_owned()));
|
||||
@@ -1843,7 +1841,7 @@ fn a_typescript_plugins_artifact_is_its_files() {
|
||||
assert_eq!(artifact.path, std::fs::canonicalize(&dir).unwrap());
|
||||
std::fs::write(dir.join("tui.ts"), "export default {}\n").unwrap();
|
||||
assert_eq!(hash(), first, "a save that changed nothing changed the hash");
|
||||
// A hidden file is a module the plugin may import (review carbon-1).
|
||||
// A hidden file is a module the plugin may import.
|
||||
std::fs::write(dir.join(".payload.ts"), "export const a = 1\n").unwrap();
|
||||
assert_ne!(hash(), first, "a hidden file kept the hash");
|
||||
std::fs::remove_file(dir.join(".payload.ts")).unwrap();
|
||||
@@ -2121,7 +2119,6 @@ fn a_removal_in_the_users_configuration_withdraws_its_vouch() {
|
||||
"byglob@1.0.0",
|
||||
"again@1.0.0",
|
||||
"enabled@1.0.0",
|
||||
// carbon's probe: the spec, removed by the spec.
|
||||
"-revoked@1.0.0",
|
||||
"-acme.byid",
|
||||
"-acme.*",
|
||||
@@ -2283,8 +2280,6 @@ fn a_build_without_ts_says_it_has_no_typescript_plugin_support() {
|
||||
assert_eq!(entry(®istry.entries(), &native).status, Status::Pending);
|
||||
}
|
||||
|
||||
// Expected (win-x64-link): a build without Luau, by feature or on x86_64 Windows MSVC, lists a Luau plugin directory as
|
||||
// skipped, saying it has no Luau support, not a TypeScript reason; a native build beside it loads.
|
||||
#[cfg(not(luau))]
|
||||
#[test]
|
||||
fn a_build_without_luau_says_it_has_no_luau_plugin_support() {
|
||||
|
||||
Reference in New Issue
Block a user