API Reference
High-Level Client
- class v2root.V2RootClient(http_port=2300, socks_port=2301, *, core_path=None, core_manager=None, auto_install=True, geosite_path=None, native_factory=<class 'v2root.native.NativeCore'>)[source]
Bases:
objectPrimary SDK facade.
Construction resolves or installs a compatible core. Configuration methods accept either share URIs, raw JSON, or configuration file paths supported by V2Root Core. Lifecycle operations are serialized per client.
- configure_logging(level=None, output=None)[source]
Configure native log level and destination.
- Parameters:
level (str | None) – Native level such as
warningordebug.output (str | os.PathLike[str] | None) – Writable native log path.
- Returns:
Native process-global logging settings are updated in place.
- Return type:
None
- connect(config_input, *, validate=True)[source]
Select a configuration and start the runtime in one operation.
- Parameters:
- Returns:
This client for fluent usage.
- Return type:
- Raises:
ConfigurationError – If parsing or validation fails.
NativeCallError – If startup fails.
- parse(uri, **options)[source]
Convert a share URI into normalized Xray-compatible JSON.
- Parameters:
uri (str) – VLESS, VMess, Trojan, or Shadowsocks share URI.
**options – Additional parser options documented by V2Root Core.
- Returns:
Complete normalized JSON configuration.
- Return type:
- Raises:
ValueError – If
uriis empty or not a string.ConfigurationError – If the native parser returns an empty result.
- property running: bool
Return whether the embedded runtime currently reports
RUNNING.- Returns:
Trueonly forRuntimeStatus.RUNNING.- Return type:
- property runtime_status: RuntimeStatus
Return the lifecycle status as a typed enumeration.
- Returns:
Typed representation of the native status string.
- Return type:
- Raises:
ValueError – If a future core returns an unknown status value.
- set_config(config_input, parse_uri=True)[source]
Normalize, validate, and retain a runtime configuration.
- Parameters:
- Returns:
Normalized configuration retained by this client.
- Return type:
- Raises:
ValueError – If
config_inputis empty or not a string.ConfigurationError – If parsing or validation fails.
- property speed
Return upload and download rates calculated by the native core.
- Returns:
Upload and download rates in bytes per second.
- Return type:
- Raises:
NativeCallError – If the runtime is stopped or native JSON is invalid.
- start(config_input=None, validate=True)[source]
Start the process-global embedded runtime.
- Parameters:
- Returns:
Runtime status after startup is accepted.
- Return type:
- Raises:
ValueError – If no configuration is available.
ConfigurationError – If pre-start validation fails.
NativeCallError – If the core rejects startup.
- property status
Return the raw lifecycle status reported by V2Root Core.
- Returns:
One of
STOPPED,STARTING,RUNNING, orSTOPPING.- Return type:
- test_latency(configs, test_url='', timeout=10)[source]
Measure latency for one or more configurations.
- Parameters:
- Returns:
Ordered numeric latencies and native error strings.
- Return type:
- Raises:
ValueError – If the normalized configuration collection is empty.
NativeCallError – If the native batch operation itself fails.
- test_latency_detailed(configs, test_url='', timeout=10)[source]
Measure latency and return structured per-configuration results.
- Parameters:
- Returns:
Ordered results containing config, latency, and error.
- Return type:
- Raises:
ValueError – If no configurations are supplied.
NativeCallError – If the native batch operation fails.
- test_subscription(manager, subscription_id=None, timeout=10)[source]
Test subscription configs and persist their results.
- Parameters:
manager (SubscriptionManager) – Manager owning configs and persistence.
subscription_id (str | None) – Restrict testing to one source.
timeout (int) – Per-test timeout in seconds.
- Returns:
Ordered structured measurements.
- Return type:
- Raises:
ValueError – If the selected source has no configurations.
NativeCallError – If the native latency operation fails.
PersistenceError – If results cannot be saved.
Convert a JSON configuration to a supported share URI.
- property traffic
Return cumulative non-API outbound traffic counters.
- Returns:
Uploaded and downloaded byte counts.
- Return type:
- Raises:
NativeCallError – If the runtime is stopped or native JSON is invalid.
- update_core()[source]
Update the managed core while the runtime is stopped.
- Returns:
Previous/current installations and change status.
- Return type:
UpdateResult
- Raises:
NativeCallError – If the runtime is not stopped.
CoreError – If release discovery, download, or installation fails.
- update_geo_assets(asset_path='')[source]
Download geosite and geoip assets through the native core.
- validate(config_input=None)[source]
Validate a configuration without starting a persistent runtime.
- Parameters:
config_input (str | None) – Configuration to validate.
Noneuses the configuration previously selected byset_config().- Returns:
- Native validation response, normally
{"result": "valid"}.
- Return type:
- Raises:
ValueError – If no configuration is available.
ConfigurationError – If native validation reports an error.
- property version_info
Return typed build metadata for the loaded native core.
- Returns:
Core code version, upstream version, and build date.
- Return type:
- Raises:
NativeCallError – If native metadata is missing or invalid JSON.
Compatibility Facade
- class v2root.V2ROOT(http_port=2300, socks_port=2301, v2ray_path=None, lib_path=None, geosite_path=None, auto_install=True, core_manager=None)[source]
Bases:
V2RootClientExpose familiar method names while executing the V2Root 2.0 implementation.
New applications should prefer
V2RootClient. This class exists to ease source migration; it does not load the retired C wrapper or launch an external V2Ray executable.- get_status()[source]
Return the current runtime status.
- Returns:
Native lifecycle state.
- Return type:
- reset_network_proxy()[source]
Stop the runtime without changing operating-system proxy settings.
- Returns:
Runtime status after shutdown.
- Return type:
Notes
V2Root 2.0 intentionally does not mutate system proxy configuration.
- set_log_level(level)[source]
Configure the native log level.
- Parameters:
level (str) – Native level such as
warningordebug.- Returns:
Process-global native logging is updated.
- Return type:
None
- set_log_output(path)[source]
Configure the native log destination.
- Parameters:
path (str | os.PathLike[str]) – Writable log file path.
- Returns:
Process-global native logging is updated.
- Return type:
None
- test_configs(configs, timeout=10, test_url='')[source]
Measure multiple configurations using the legacy batch method.
Core Management
- class v2root.CoreManager(cache_dir=None, repository='v2RayRoot/V2Root-Core', transport=None, target=None)[source]
Discover, install, update, activate, and roll back V2Root Core.
- property api_base
Return the configured GitHub REST API base.
- Returns:
Repository releases API prefix.
- Return type:
- current()[source]
Resolve the currently activated core.
- Returns:
Active valid installation, otherwise
None.- Return type:
InstalledCore | None
- property current_file
Return the active-release marker path.
- Returns:
currentfile inside the managed cache.- Return type:
- ensure(auto_install=True)[source]
Ensure that a usable active core exists.
- Parameters:
auto_install (bool) – Install the latest compatible release when absent.
- Returns:
Existing or newly installed active core.
- Return type:
InstalledCore
- Raises:
CoreNotInstalledError – If absent and automatic installation is disabled.
CoreError – If automatic installation fails.
- get_release(tag)[source]
Fetch metadata for an explicitly tagged release.
- Parameters:
tag (str) – Exact GitHub release tag.
- Returns:
Normalized release metadata.
- Return type:
CoreRelease
- Raises:
CoreDownloadError – If the tag is unavailable or malformed.
- install(tag=None, force=False)[source]
Download, verify, atomically install, and activate a release.
- Parameters:
- Returns:
Verified active installation.
- Return type:
InstalledCore
- Raises:
CoreDownloadError – If metadata or the target asset is unavailable.
CoreIntegrityError – If archive layout or checksums are invalid.
OSError – If local atomic installation operations fail.
- installed()[source]
Discover valid cached core installations.
- Returns:
Installations ordered by timestamp descending.
- Return type:
list[InstalledCore]
Notes
Corrupt unrelated manifests are skipped so one bad historical release does not prevent use of healthy installations.
- latest_release()[source]
Fetch metadata for the latest published core release.
- Returns:
Normalized release tag, publication date, and assets.
- Return type:
CoreRelease
- Raises:
CoreDownloadError – If metadata cannot be fetched or normalized.
Runtime Models
- class v2root.RuntimeStatus(*values)[source]
Enumerate lifecycle states exposed by the process-global native runtime.
- class v2root.VersionInfo(code_version, version, release_date)[source]
Expose build metadata reported by the loaded V2Root Core binary.
- class v2root.Traffic(uplink, downlink)[source]
Contain cumulative uploaded and downloaded byte counters.
- class v2root.RealtimeSpeed(uplink, downlink)[source]
Contain current upload and download rates measured in bytes per second.
Subscriptions
- class v2root.SubscriptionManager(storage_dir=None, *, repository=None, parser=None, transport=None)[source]
Coordinate subscription transport, parsing, persistence, and scheduling.
The manager is the application-service boundary for subscriptions. Its dependencies are injectable, allowing deterministic tests and alternative transports or repositories without changing domain models.
- add_subscription(url, name=None, auto_update=False, update_interval=86400, enabled=True, priority=0, tags=None, fetch_now=True)[source]
Register, optionally fetch, persist, and schedule a subscription.
- Parameters:
url (str) – Absolute HTTP(S) subscription URL.
name (str | None) – Optional display name.
auto_update (bool) – Start a periodic scheduler after registration.
update_interval (int) – Scheduler interval in seconds.
enabled (bool) – Include this source in aggregate queries.
priority (int) – Application-defined priority value.
tags (Iterable[str] | None) – Source classification labels.
fetch_now (bool) – Fetch and parse the source before returning.
- Returns:
The registered and possibly populated model.
- Return type:
- Raises:
ValueError – If the URL is duplicated or model values are invalid.
FetchError – If immediate fetching fails.
ParseError – If immediate parsing finds no valid configurations.
PersistenceError – If state cannot be saved.
- best_config(**filters)[source]
Select the lowest-latency tested configuration after filtering.
- Parameters:
**filters – Filters accepted by
filter_configs().- Returns:
Best tested candidate, or
None.- Return type:
ConfigMetadata | None
- close()[source]
Stop all active schedulers and persist their disabled state.
- Returns:
All known schedulers are synchronously requested to stop.
- Return type:
None
- filter_configs(subscription_tags=None, **filters)[source]
Filter enabled subscriptions and their configurations.
- Parameters:
subscription_tags (Iterable[str] | None) – Require at least one matching source tag.
**filters – Keyword filters accepted by
Subscription.filter_configs().
- Returns:
Metadata satisfying source and config filters.
- Return type:
- Raises:
ValueError – If a delegated configuration filter is invalid.
- get_config_metadata(enabled_only=True)[source]
Flatten metadata objects from all selected subscriptions.
- Parameters:
enabled_only (bool) – Exclude disabled subscriptions when true.
- Returns:
References to managed metadata objects.
- Return type:
- get_configs_from_subscription(subscription_id)[source]
Return share URIs for one source when it exists.
- get_subscription(subscription_id)[source]
Look up one subscription without raising when it is absent.
- Parameters:
subscription_id (str) – Stable source identifier.
- Returns:
Registered model or
None.- Return type:
Subscription | None
- record_latency(config_string, latency, success=True)[source]
Record and persist a test result for the matching share URI.
- Parameters:
- Returns:
Truewhen a matching config was updated.- Return type:
- Raises:
PersistenceError – If the owning subscription cannot be saved.
- remove_subscription(subscription_id)[source]
Stop scheduling and remove one subscription from memory and storage.
- require(subscription_id)[source]
Look up one subscription and require that it exists.
- update_subscription(subscription_id, timeout=30)[source]
Fetch, parse, merge, and persist one subscription.
- Parameters:
- Returns:
Newly parsed configuration metadata.
- Return type:
- Raises:
KeyError – If
subscription_idis unknown.FetchError – If the source cannot be downloaded.
ParseError – If downloaded content is invalid.
PersistenceError – If success or failure state cannot be persisted.
- class v2root.Subscription(url, name=None, auto_update=False, update_interval=86400, enabled=True, priority=0, tags=<factory>, configs=<factory>, last_update_time=0, last_fetch_success=False, last_error_message='', total_updates=0, successful_updates=0, failed_updates=0)[source]
Represent one remote subscription and its persistent application state.
The model validates URL and scheduling invariants at construction time. It does not perform network I/O itself; fetching, parsing, and persistence are coordinated by
SubscriptionManager.- Parameters:
- configs
Parsed configurations from the source.
- Type:
- filter_configs(protocols=None, min_success_rate=None, max_latency=None, tags=None, name_contains=None)[source]
Select configuration metadata matching all supplied constraints.
- Parameters:
protocols (Iterable[str] | None) – Allowed protocol schemes.
min_success_rate (float | None) – Inclusive success-rate threshold between
0.0and1.0.max_latency (int | float | None) – Inclusive maximum successful latency in milliseconds. Untested configs are excluded.
tags (Iterable[str] | None) – At least one tag must match.
name_contains (str | None) – Case-insensitive regular expression applied to the human-readable config name.
- Returns:
Matching objects in their original order.
- Return type:
- Raises:
ValueError – If
min_success_rateis outside0..1or the regular expression is invalid.
- classmethod from_dict(value)[source]
Restore a subscription from repository data.
- Parameters:
value (dict[str, object]) – JSON-decoded subscription document.
- Returns:
A validated source with restored runtime statistics.
- Return type:
- Raises:
KeyError – If the required
urlfield is absent.ValueError – If persisted URL or interval values are invalid.
TypeError – If persisted fields have incompatible types.
- get_statistics()[source]
Calculate an immutable statistical snapshot of current state.
- Returns:
- Counts, protocol distribution, update
totals, and average latency for successfully tested configs.
- Return type:
SubscriptionStatistics
- sort_configs(by='latency', reverse=False)[source]
Return configurations ordered by a supported metadata field.
- Parameters:
- Returns:
A new sorted list; the model is not mutated.
- Return type:
- Raises:
ValueError – If
byis not a supported field.
- class v2root.ConfigMetadata(config_string, protocol='unknown', name='Unnamed Config', address='unknown', port=0, last_test_time=0, last_latency=-1, success_count=0, failure_count=0, tags=<factory>)[source]
Store parsed identity and historical health data for one share URI.
- Parameters:
- config_string
Original share URI. It may contain credentials and must not be written to logs without redaction.
- Type:
- classmethod from_dict(value)[source]
Restore metadata from a persisted dictionary.
- get_success_rate()[source]
Calculate the ratio of successful tests to all recorded tests.
- Returns:
A value from
0.0through1.0. Untested configs return0.0rather than raising a division error.- Return type:
- property tested: bool
Report whether at least one test result has been recorded.
- Returns:
Truewhenlast_test_timeis greater than zero.- Return type:
Errors
- v2root.explain_error(error)[source]
Explain one V2Root 2.0 exception using the default catalog.
- Parameters:
error (BaseException) – Failure to classify.
- Returns:
Presentation-neutral diagnosis.
- Return type:
Logging
- class v2root.logger.V2RootLogger(name='v2root')[source]
Manage handlers and convenience methods for the shared package logger.
- Parameters:
name (str) – Base logger name. Child loggers inherit its handlers.
Notes
The wrapper does not create files during construction. Applications must call
configure()orconfigure_logger()explicitly.- configure(*, log_level=20, log_to_file=False, log_to_console=True, log_dir=None, max_file_size=5242880, backup_count=3)[source]
Replace package handlers with explicit console and file outputs.
- Parameters:
log_level (int) – Standard logging threshold such as
logging.INFO.log_to_file (bool) – Create a rotating UTF-8 log file when true.
log_to_console (bool) – Emit formatted records to stderr when true.
log_dir (str | os.PathLike[str] | None) – File logging directory. Platform-specific user storage is used when omitted.
max_file_size (int) – Rotation threshold in bytes.
backup_count (int) – Number of rotated files to retain.
- Returns:
This configured wrapper for fluent setup.
- Return type:
- Raises:
ValueError – If size or backup values are negative.
OSError – If the log directory or file cannot be created.
- critical(msg, *args, **kwargs)[source]
Emit a CRITICAL record.
- Parameters:
msg (object) – Message or formatting template.
*args – Values interpolated by Python logging.
**kwargs – Standard
logging.Logger.criticaloptions.
- Returns:
The record is delegated to the shared logger.
- Return type:
None
- debug(msg, *args, **kwargs)[source]
Emit a DEBUG record.
- Parameters:
msg (object) – Message or formatting template.
*args – Values interpolated by Python logging.
**kwargs – Standard
logging.Logger.debugoptions.
- Returns:
The record is delegated to the shared logger.
- Return type:
None
- error(msg, *args, **kwargs)[source]
Emit an ERROR record.
- Parameters:
msg (object) – Message or formatting template.
*args – Values interpolated by Python logging.
**kwargs – Standard
logging.Logger.erroroptions.
- Returns:
The record is delegated to the shared logger.
- Return type:
None
- exception(msg, *args, **kwargs)[source]
Emit an ERROR record with the active traceback.
- Parameters:
msg (object) – Message or formatting template.
*args – Values interpolated by Python logging.
**kwargs – Standard
logging.Logger.exceptionoptions.
- Returns:
The record is delegated to the shared logger.
- Return type:
None
- get_logger(name=None)[source]
Return the package logger or one of its named descendants.
- Parameters:
name (str | None) – Optional suffix such as
core.manager.- Returns:
Shared root logger or
v2root.<name>child.- Return type:
- info(msg, *args, **kwargs)[source]
Emit an INFO record.
- Parameters:
msg (object) – Message or formatting template.
*args – Values interpolated by Python logging.
**kwargs – Standard
logging.Logger.infooptions.
- Returns:
The record is delegated to the shared logger.
- Return type:
None
- log_function_call(func=None, *, log_args=False, log_result=False, level=10)[source]
Create a decorator that records function entry, exit, and failures.
- Parameters:
- Returns:
Decorated function, or a decorator when
funcis absent.- Return type:
Callable
Notes
Representations are truncated to reduce accidental credential exposure. Sensitive APIs should still avoid
log_args=True.
- v2root.configure_logger(**kwargs)[source]
Configure the process-wide V2Root logger.
- Parameters:
**kwargs – Keyword arguments accepted by
V2RootLogger.configure().- Returns:
Configured shared logger wrapper.
- Return type:
- Raises:
TypeError – If an unsupported configuration keyword is supplied.
ValueError – If rotation settings are invalid.
OSError – If requested file logging cannot be initialized.