Skip to main content

Elements

Common

Common defines the abstract architectural contracts for the entire Rust backend: the ActionEffect system, async service traits, DTOs, and the universal CommonError type.

Common: Abstract Core Library 🧑🏻‍🏭

Common is the architectural foundation of Land’s native Rust backend. Common is a pure abstract library that defines:

  • Every application capability as async traits
  • The ActionEffect declarative system
  • Data Transfer Objects (DTOs)
  • A universal error type

It contains no concrete implementations.


Table of Contents

  1. Overview
  2. Architecture Principles
  3. Trait Architecture
  4. ActionEffect System
  5. Environment and Dependency Injection
  6. Data Transfer Objects
  7. CommonError
  8. Transport Layer
  9. Telemetry Module
  10. Service Domain Map
  11. Related Documentation

graph TB
    subgraph Common["Common Abstract Core"]
        TRAITS["Async Traits<br/>FileSystem / Terminal /<br/>Configuration / Workspace<br/>+ 20 more"]
        AE["ActionEffect<br/>System<br/>description / execution<br/>separation"]
        ENV["Environment / Requires<br/>compile-time DI"]
        DTO["Data Transfer Objects<br/>FileStat / InitData /<br/>TerminalOptions"]
        ERR["CommonError<br/>unified error enum"]
        TRANS["Transport Layer<br/>TransportStrategy + Config"]
        TEL["Telemetry<br/>PostHog + OTLP"]

        TRAITS --> AE
        AE --> ENV
        ENV -->|"capability resolution"| TRAITS
        DTO --> TRAITS
        DTO --> AE
        ERR --> TRAITS
        ERR --> AE
        TRANS --> ENV
        TEL -.->|"emit events"| TRAITS
    end

    AE -->|"execute via"| RUNTIME["ApplicationRunTime<br/>(Echo-backed)"]

Overview 📋

Common defines the architectural language of the entire native platform:

  • Every service interface, data contract, and communication pattern originates here
  • Mountain, Air, Echo, Mist, Rest, SideCar, and Grove all depend on Common’s definitions
AttributeValue
LanguageRust (edition 2024)
Crate typeLibrary (no binary)
Dependenciestauri, async-trait, serde, thiserror, url, prometheus, posthog-rs
ConsumersMountain, Air, Echo, Mist, Rest, SideCar, Grove

Architecture Principles 📐

PrincipleDescriptionKey Components
Pure AbstractionEvery application capability is an abstract async trait with no concrete implementationAll *Provider.rs and *Manager.rs files
Declarative EffectsOperations are ActionEffect values separating description from executionEffect/ module
Trait-Based DICompile-time dependency injection via Environment and Requires traitsEnvironment/ module
Universal Error HandlingSingle CommonError enum covering all failure scenariosError/CommonError.rs
Contract-First DesignDTOs and errors defined before implementationsDTO/, Error/ modules
Minimal DependenciesIndependent from Tauri, gRPC, or any specific application logicCargo.toml

Trait Architecture 📋

Every application capability is defined as an async trait:

#[async_trait]
pub trait FileSystem: Send + Sync {
    async fn read_file(&self, path: &Path) -> Result<Vec<u8>, CommonError>;
    async fn write_file(&self, path: &Path, content: &[u8]) -> Result<(), CommonError>;
    async fn stat(&self, path: &Path) -> Result<FileStat, CommonError>;
    async fn read_dir(&self, path: &Path) -> Result<Vec<DirEntry>, CommonError>;
    async fn create_dir(&self, path: &Path) -> Result<(), CommonError>;
    async fn remove_file(&self, path: &Path) -> Result<(), CommonError>;
    async fn rename(&self, from: &Path, to: &Path) -> Result<(), CommonError>;
    async fn copy(&self, from: &Path, to: &Path) -> Result<(), CommonError>;
    async fn watch(&self, path: &Path) -> Result<FileWatcher, CommonError>;
}

Defined Service Traits 📋

ModuleTraitDomainMethods
FileSystem/FileSystemReader + FileSystemWriterFile operationsread, write, stat, readdir, mkdir, remove, rename, copy, watch
Configuration/ConfigurationProviderSettingsget, set, has, inspect, onDidChange, keys
Terminal/TerminalProviderPTYcreate, write, resize, onData, onExit, list
UserInterface/UserInterfaceProviderDialogsopen, save, message, input, quickPick
Document/DocumentProviderText documentsopen, save, saveAs, applyChanges
ExtensionManagement/ExtensionManagementServiceExtensionsscan, install, uninstall, list, getManifest
Search/SearchProviderSearchsearch, findInFile, replace
Secret/SecretProviderKeychainget, set, delete, onDidChange
Storage/StorageProviderKV storageget, set, delete, list, clear
Workspace/WorkspaceProviderWorkspacegetWorkspaceFolder, findFiles, applyEdit
LanguageFeature/LanguageFeatureProviderRegistryLanguagehover, completion, definition, references, codeAction, formatting
Command/CommandExecutorCommandsexecute, register, unregister, getAll
Debug/DebugServiceDebuggingstart, stop, step, breakpoints
Testing/TestControllerTestingrun, discover, results
SourceControlManagement/SourceControlManagementProviderSCMstatus, commit, push, pull, diff
Synchronization/SynchronizationProviderSyncpush, pull, merge, resolve
IPC/IPCProviderCommunicationsend, receive, proxy
Webview/WebviewProviderWebviewscreate, sendMessage, dispose
TreeView/TreeViewProviderTree viewsgetChildren, getParent, resolveItem
StatusBar/StatusBarProviderStatus barsetItem, updateItem, removeItem
Diagnostic/DiagnosticManagerDiagnosticsset, clear, getAll
Keybinding/KeybindingProviderKeybindingsresolve, onDidChange

ActionEffect System ⚡

The ActionEffect system treats operations as data structures rather than direct function calls. This declarative approach enables:

  • Composition — Combine effects sequentially or in parallel
  • Testing — Effects are data, easy to mock and assert
  • Controlled execution — Effects are executed by a runtime

Type Signature 📝

pub struct ActionEffect<TCapability, TError, TOutput> {
    pub Function: Arc<
        dyn Fn(TCapability)
            -> Pin<Box<dyn Future<Output = Result<TOutput, TError>> + Send>>
            + Send
            + Sync,
    >,
}
  • TCapability: The environment/capability type required for execution
  • TError: The error type that may result
  • TOutput: The successful result type

Effect Composition 🔄

// Sequential composition
let sequential = effect1.and_then(|result1| effect2(result1));

// Parallel composition
let parallel = effect1.zip(effect2);

// Error recovery
let resilient = effect.fallback(backup_effect);

// Mapping
let mapped = effect.map(|result| transform(result));

Execution ▶️

// Effects are executed by ApplicationRunTime
let runtime = ApplicationRunTime::new(environment);
let result: Result<Vec<u8>, CommonError> = runtime
    .execute_effect(ActionEffect::ReadFile { path: "/tmp/test.txt" })
    .await;

Environment and Dependency Injection 🧩

Common implements compile-time dependency injection through the Environment and Requires traits:

// A component declares what capabilities it requires
pub trait Requires<C> {
    type Error;
    async fn run(self, env: &C) -> Result<Self::Output, Self::Error>;
}

// An environment provides concrete implementations
pub trait Environment {
    type FileSystem: FileSystem;
    type Configuration: ConfigurationProvider;
    type Terminal: TerminalProvider;
    // ... one associated type per capability
}

Capability Resolution Flow 🗺️

ActionEffect<C, E, T>
    |
    v
ApplicationRunTime
    |
    v
Environment Provider
    |  - Resolves concrete capability C
    |  - Environment::FileSystem -> MountainFileSystem
    |  - Environment::Terminal -> MountainTerminal
    |
    v
Concrete Capability (e.g., Mountain's FileSystem impl)
    |
    v
Effect executed with concrete implementation

Data Transfer Objects 📦

Common defines all DTOs shared across components:

DTOModuleFieldsUsed By
FileStatFileSystem/DTOpath, type, size, mtime, permissionsAll file ops
InitDataWorkspaceworkspace info, extensions, configMountain->Cocoon startup
TerminalOptionsTerminalname, shellPath, cwd, env, cols, rowsTerminal creation
ExtensionManifestExtensionManagementid, version, publisher, activationEventsExtension mgmt
ConfigurationTargetConfigurationGlobal, Workspace, WorkspaceFolderConfig ops
SearchOptionsSearchpattern, include, exclude, maxResultsSearch ops
WorkspaceEditDTODTO/edits, fileCreates, fileDeletesWorkspace edits
TransportConfigTransporttimeout, retry configTransport configuration

CommonError ⚠️

A single error type covering all failure modes across every service domain:

pub enum CommonError {
    NotFound(String),
    PermissionDenied(String),
    IoError(std::io::Error),
    ParseError(String),
    ProtocolError(String),
    Timeout(String),
    Unsupported(String),
    Internal(String),
    Cancelled,
}

Transport Layer 🔗

Common provides a transport-agnostic communication interface:

pub trait TransportStrategy: Send + Sync {
    type Error: std::error::Error + Send + Sync + 'static;
    async fn connect(&self) -> Result<(), Self::Error>;
    async fn send(&self, request: &[u8]) -> Result<Vec<u8>, Self::Error>;
    async fn close(&self) -> Result<(), Self::Error>;
    fn is_connected(&self) -> bool;
    fn transport_type(&self) -> TransportType;
}

Common defines the trait surface and TransportConfig; concrete transports (gRPCTransport, IPCTransport, WASMTransport, MistTransport) live in Grove.


Telemetry Module 📡

Common’s telemetry module provides a dual-pipe emit surface:

PipeCrateConfiguration
PostHogposthog-rsTELEMETRY_POSTHOG_KEY, TELEMETRY_DISABLE
OTLPopentelemetryTELEMETRY_OTLP_ENDPOINT, TELEMETRY_DISABLE
  • Honors the Disable=true build-time flag to completely remove telemetry from the binary

Service Domain Map 🗺️

Common/
+-- Command/            - Command execution and registration
+-- Configuration/      - Settings and configuration management
+-- CustomEditor/       - Custom (webview-based) editor support
+-- Debug/              - Debugging session management
+-- Diagnostic/         - Diagnostics and problem markers
+-- Document/           - Text document management
+-- DTO/                - Shared data transfer objects
+-- Effect/             - ActionEffect system
+-- Environment/        - DI traits (Environment, Requires)
+-- Error/              - CommonError enum
+-- ExtensionManagement/ - Extension lifecycle
+-- FileSystem/         - File and directory operations
+-- IPC/                - Inter-process communication
+-- Keybinding/         - Keyboard shortcut resolution
+-- LanguageFeature/    - Language intelligence (hover, completion, etc.)
+-- Output/             - Output channel management
+-- Search/             - File and text search
+-- Secret/             - OS keychain-backed secrets
+-- SourceControlManagement/ - Git and SCM integration
+-- StatusBar/          - Status bar item management
+-- Storage/            - Key-value storage
+-- Synchronization/    - User data synchronization
+-- Telemetry/          - PostHog + OTLP telemetry
+-- Terminal/           - PTY terminal management
+-- Testing/            - Test controller
+-- Transport/          - Agnostic communication layer
+-- TreeView/           - Tree data provider
+-- UserInterface/      - Dialogs, messages, quick pick
+-- Webview/            - Webview panel management
+-- Workspace/          - Workspace and folder management

Funding 💎

Common is developed as part of the CodeEditorLand project, funded through the NGI0 Commons Fund, a grant programme of the European Commission’s Next Generation Internet initiative.


Project Maintainers: Source Open (Source/[email protected]) | GitHub Repository | Report an Issue