Skip to content

Console

Console provides native command registration, parsing, output, and testing. Typer parses arguments. Rich renders terminal output. Foundation owns each application-aware command lifecycle.

Use Annotated metadata for values supplied on the command line. Other typed parameters resolve from the active application Container.

from typing import Annotated
from titanspan.console import Argument, Console
from titanspan.contracts import ConsoleOutput
console = Console()
@console.command("greet")
def greet(
name: Annotated[str, Argument()],
output: ConsoleOutput,
) -> None:
"""Print a greeting for one name.
Args:
name: Person who receives the greeting.
output: Application-owned terminal output service.
"""
output.write(f"Hello, {name}.")

Console.command() preserves the handler object. Use Console.register_command() when a component already has a handler object. Both operations use the shared CommandRegistrar contract.

Use Python defaults for optional command-line values:

from typing import Annotated
from titanspan.console import Console, Option
from titanspan.contracts import ConsoleOutput
console = Console()
@console.command("inspect")
def inspect(
limit: Annotated[int, Option("--limit", "-l")] = 10,
*,
output: ConsoleOutput,
) -> None:
"""Show up to the selected number of records.
Args:
limit: Maximum number of records to show.
"""
output.write(f"Limit: {limit}")

Create nested command groups with add_group():

from titanspan.console import Console
console = Console()
admin = console.add_group("admin")
def rebuild_index() -> None:
"""Rebuild the application search index.
This function represents one application-owned command handler.
"""
admin.register_command("rebuild", rebuild_index)

Group state belongs to one Console. Names cannot conflict with another command or group at the same path.

Use list[T] annotations for repeated command-line inputs. Positional values are collected in order, and repeated options such as --channel email and --channel sms become a Python list. Typer validates declared types and required arguments before Console starts the Application.

Set hidden=True to keep a command executable while leaving it out of help. Aliases invoke the same handler and are hidden from help automatically:

from titanspan.console import Console
from titanspan.contracts import ConsoleOutput
console = Console()
@console.command("cache:clear", aliases=("cache:purge",))
def clear_cache(output: ConsoleOutput) -> None:
"""Clear the active application's cache.
Both command names dispatch to this handler.
"""
output.write("Cache cleared.")
@console.command("maintenance:refresh", hidden=True)
def refresh_maintenance(output: ConsoleOutput) -> None:
"""Run an explicit maintenance operation.
Callers can invoke this command even though help omits it.
"""
output.write("Maintenance refreshed.")

command_names includes hidden commands and aliases because it reports every registered path.

Mark a command isolatable to add an opt-in --isolated flag. The command uses the active application’s configured Cache lock and skips its handler when another run holds the same key:

from typing import Annotated
from titanspan.console import Argument, Console
from titanspan.contracts import ConsoleOutput
console = Console()
@console.command(
"reports:build",
isolatable=True,
isolation_key=lambda values: str(values["tenant"]),
)
async def build_report(
tenant: Annotated[str, Argument()],
output: ConsoleOutput,
) -> None:
"""Build a report while its tenant key is exclusively held.
Args:
tenant: Tenant whose report is being built.
"""
output.write(f"Built report for {tenant}.")

The default key uses the command path. Aliases share the primary command’s lock. An isolation_key callback can scope the lock to parsed command inputs; its result must be a non-empty string no longer than 1024 characters. Titanspan hashes the key before storing it. The lock lease defaults to 3600 seconds and can be changed with isolation_ttl. CLI users can set the busy status with --isolation-exit-code; Python callers can pass isolated=True and isolation_exit_code to execute_async() or execute_sync(). A contended invocation returns status zero by default.

The Cache backend owns lock acquisition, release, and expiry. The memory backend coordinates only within its process. Use a shared lock-capable Cache backend, such as Redis, when separate application processes must coordinate.

Functions and command classes use the application Container. Command classes define a handle() method. The Container constructs a new command object for each invocation.

from titanspan.contracts import ConfigRepository, ConsoleOutput
from titanspan.console import Console
class StatusCommand:
"""Display the configured application name.
The command receives its settings through the native Container.
"""
def __init__(self, config: ConfigRepository) -> None:
"""Retain the shared configuration repository.
Args:
config: Application configuration contract.
"""
self._config = config
def handle(self, output: ConsoleOutput) -> None:
"""Write the configured application name.
Args:
output: Application-owned terminal output service.
"""
output.write(self._config.get("app.name", "Titanspan"))
console = Console()
console.register_command("status", StatusCommand)

The default command factory uses bootstrap/app.py:create_application when that conventional file exists. The synchronous function receives the ConsoleServiceProvider and must return a native Application. Its own Foundation builder settings, trusted providers, logging, and middleware then apply to Console execution. Relative imports within bootstrap/ remain isolated by application root. Without that file, Console builds an Application from the current directory and discovers trusted titanspan.providers entry points. Pass application_factory to a Console when one instance needs explicit composition. A Console with a custom factory retains the framework and component commands from the installed catalog.

Call discover_commands() to load trusted installed entry points from the titanspan.commands group. Discovery order uses entry-point name and value. Applications can keep command handlers in routes/console.py and expose them through that group. This operation imports installed Python code. Install only trusted packages.

Use with_application=False only for bootstrap commands that need no Container services. The built-in configuration commands use this mode because they must work before application configuration is constructed.

Inject the shared ConsoleOutput contract or construct TerminalOutput directly. Output strings are rendered as plain text.

from titanspan.console import TerminalOutput
output = TerminalOutput()
output.table(["Name", "State"], [["worker", "ready"]])
with output.progress(total=2, description="Indexing") as progress:
progress.advance()
progress.complete()

ConsoleExitError selects a process status from 0 through 255. Other command exceptions are reported and return status 1. Foundation shuts down the application before the CLI returns its status. The default terminal message shows the command and exception class. Set Console(show_exception_details=True) to print bounded chained exception details and a traceback. Those details may contain secrets.

Use ConsoleTester to invoke the real parser and capture text output:

from titanspan.console.testing import ConsoleTester
result = ConsoleTester(console).invoke(["greet", "Ada"])
assert result.exit_code == 0

Call execute_async() when an application already owns an async runtime:

status = await console.execute_async(
"cache clear",
{"force": True},
)

The method accepts typed Python values and skips command-line parsing. It reuses the active Application. Otherwise, it starts and shuts down one through the configured application factory. It returns the command’s process status.

The installed command provides about, configuration, route, and event inspection commands. route:list displays the active catalog used for matching and URL generation. route:cache writes a validated metadata snapshot. route:clear removes it. Event cache commands require a configured events.manifest_path. Route snapshots do not skip route discovery at startup.

Use the native generators to create typed starter files under the selected application root:

Terminal window
titanspan make:controller reports.ReportController
titanspan make:middleware RequestId
titanspan make:provider Metrics
titanspan make:command Reindex
titanspan make:event DocumentReady
titanspan make:listener SendNotice --event app.events.DocumentReadyEvent
titanspan make:test documents

Names may use dotted application module paths. Generators create parent directories, reject paths outside the root, and never replace existing files. The listener generator requires a trusted event class path. Review generated files before registering providers, middleware, listeners, or commands.

Console does not generate a complete application scaffold. Other components can add commands through the shared CommandRegistrar contract.

Synchronous run() and invoke() cannot start inside an active async task. Use execute_async() from async application code. It skips the parser and requires typed input values. Synchronous handlers run in AnyIO worker threads and must use thread-safe services. Use an async handler with thread-affine resources.