Skip to content
Edit this page

Application foundation

The retained framework foundation composes application paths, configuration, providers, and lifecycle. The separate HTTP kernel owns the FastAPI host. The application owns the container lifecycle and the resolver owns finalization.

Create an application

from titancore import Application
from titancore.foundation.http import Kernel

application = Application(base_path=".")
kernel = Kernel(application)
app = kernel.asgi

base_path is expanded and resolved at construction. When omitted, the current working directory is used. application.path("storage", "logs") joins trusted path segments beneath that base; it does not validate external input.

Register services

Declare application services through the Titancore container package:

from titancore import Application
from titancore.container import Provider, Scope, provide
from titancore.foundation.http import Kernel


class GreetingService:
    def message(self) -> str:
        return "Hello"


class AppServiceProvider(Provider):
    @provide(scope=Scope.APP)
    def provide_greeting(self) -> GreetingService:
        return GreetingService()


application = Application()
application.register(AppServiceProvider())
kernel = Kernel(application)

The application registers providers before the kernel adds its FastAPI integration. The kernel bootstraps the application and pairs its container lifecycle with ASGI startup and shutdown. Request injection uses the supported FastAPI integration:

from titancore.facades import Route
from titancore.foundation.http import inject


@inject
async def welcome(service: GreetingService) -> dict[str, str]:
    return {"message": service.message()}


Route.get("/greeting", welcome)

FastAPI and Starlette own route matching, request parsing, response handling, and ASGI protocol behavior. Titancore adds only route declaration metadata and grouping. In routes/api.py, use the facade for conventional declarations:

from welcome_controller import WelcomeController

from titancore.facades import Route

Route.get("/welcome", (WelcomeController, "show"))

The HTTP kernel discovers that file, resolves the controller through the application container, and compiles the declaration into FastAPI. The hello-world guide shows the controller and its plain constructor injection.

Lifecycle

The HTTP kernel pairs FastAPI's lifespan with the application container. For a direct application context, call bootstrap_with(...) before async with application. Access application.services only after startup. The delegated resolver finalizes resources declared by providers when the application shuts down. Facades use the active application during an HTTP request or an async with application block. A nested block restores its enclosing owner on exit.

The HTTP kernel supplies the default environment and configuration sequence. Applications can replace it before the kernel is accessed:

from titancore import Application
from titancore.foundation.bootstrap import LoadConfiguration

application = Application()
application.bootstrap_with((LoadConfiguration,))

Each bootstrapper creates and binds the repositories it owns through the application's public container API. Access them with application["env"] and application["config"].

Register framework-shaped lifecycle callbacks with booting, booted, and terminating:

application.booting(lambda app: app.register(AppServiceProvider()))
application.booted(lambda app: app["config"].set("app.ready", True))
application.terminating(lambda app: app["config"].set("app.closed", True))

Logging and exceptions

The default bootstrap sequence creates an application-owned LogManager from config/logging.yaml. The configuration follows framework's compact channel shape:

default: stack
channels:
  stack:
    driver: stack
    channels: [single, console]
  single:
    driver: single
    path: storage/logs/application.log
  console:
    driver: console

Application code can use the facade or resolve the same manager through array access:

from titancore.facades import Log

Log.info("job started", {"job": "example"})
application["log"].channel("single").info("written to disk")

The other retained facades follow the same small proxy pattern: App exposes container registration and resolution, Config and Env expose the bootstrap repositories, and DB opens an explicit async database unit of work. They do not create a second registry or hide transaction ownership.

The HTTP kernel reports unexpected errors through the shared exception handler and sends a generic error response. FastAPI handles expected HTTP errors and validation errors. Exception reporting follows the manager's current default channel. The logger resolved from application["logger"] identifies the channel selected during bootstrap. Context added through the manager or a logger stays local to the current execution context.

The current foundation does not include application discovery, a custom service registry, or component auto-registration. App tracks the current application only as a facade owner; all registrations remain in the application container.

Console applications

The separate Console kernel uses the same application bootstrap, container, exception handler and shutdown behavior. It loads routes/console.py; HTTP loads only routes/api.py. The application contract extends the container contract, so every application supports the same registration and resolution boundary without repeated interface declarations.

Explicit garbage collection

Application shutdown requests one full native collection after owned service finalizers and facade cleanup. Repeated shutdown does not collect again. Requests, job dispatch and streaming chunks do not force collection.

Developers may call collect_garbage(generation=2) from titancore.support after releasing a large batch. The helper delegates to Python's collector, returns its object count and skips overlapping calls through the helper. Automatic GC and thresholds remain unchanged. Call outside collector callbacks. It does not close resources, free reachable objects, or promise lower resident memory. Profile a workload before adding explicit collections to its hot path.