Skip to content

Architecture

SourceLab is a Litestar monolith that runs as several kinds of process: see Components for those. This page explains how the code fits together. Five design choices explain most of the system:

  1. Git holds the code and SQL holds the metadata, with part of the metadata mirrored into git. Issues and pull requests live in the database and are also written as JSON files to dedicated git repositories. Pushing to those repositories updates the database, so the sync runs both ways.
  2. Writes go through a real git push. Merges and other server-side changes are made in a temporary clone and pushed back, so they pass through the same hooks as a user's push.
  3. Git hooks run the whole application. Each hook is a new Python process that imports SourceLab, opens a database session and runs plugins.
  4. Slow work runs in Myxo jobs, queued in the SQL database. A job is written in the transaction of the change that puts it, and the UI sends the user to a /wait/<ticket> page while it runs.
  5. Configuration is global and read at import time. It decides which routes exist.

Code map

Module Role
sourcelab/web/asgi.py The entry point: the Litestar app, behind the reverse proxy's headers
sourcelab/web/ui/, api/, internal/ Served by Litestar: the pages, with templates in sourcelab/web/templates/, the JSON API under /api/0, and the /pv endpoints
sourcelab/web/litestar/ The Litestar application and its request handling: the page's g, the context, the session, the CSRF tokens, the templates and the URLs
sourcelab/services/ Database and business logic, one module per domain (projects.py, issues.py, pull_requests.py, users.py...)
sourcelab/domain/model/ SQLAlchemy models, one module per domain, including serialization (to_json); the package exports every model
sourcelab/infra/git/ Git operations, one module per kind, and TemporaryClone (clone.py); merges are in sourcelab/services/merges.py, the JSON sync in sourcelab/services/git_sync.py
sourcelab/services/notifications.py Who to notify of a change and what to tell them; the delivery, by email or on the message buses, is in sourcelab/infra/messaging.py
sourcelab/workers/ The Myxo services that run the jobs, one module per service. The jobs are messages in sourcelab/domain/jobs.py, put through sourcelab/infra/queue.py
sourcelab/hooks/ The git hook runtime: hookrunner, and run_hook_file, which runs the hooks in the hook's own process. sourcelab/plugins/push.py runs them, for it and for /pv/hooks (run_hook, run_project_hooks)
sourcelab/plugins/ The plugins of the projects; their tables are in sourcelab/domain/model/plugins.py
sourcelab/services/access.py, web/forms/, web/pfmarkdown.py Access checks, WTForms, Markdown extensions

Each layer only imports the layers below it: web, hooks, cli and workers at the top, then plugins, services, infra and domain. An import-linter contract in the root pyproject.toml enforces this. The real graph has import cycles, resolved by importing whole modules and by imports inside functions. As a result, importing any service module loads nearly the whole backend, which is why a hook is slow to start. The figure below predates the split of the package into layers: query is now the services package. The other modules are in infra.

Views import query and git. Query and git both import model. Red two-headed arrows mark modules that import each other: query with git, notify, tasks and tasks_services; git with tasks and sourcelab.hooks. Hooks also import query. Dashed red arrows show sourcelab.utils importing sourcelab.web.api and query inside a function.

Web application

sourcelab.web.asgi:create_asgi_app() is the application: the Litestar app, behind the reverse-proxy middleware. It serves the API, /pv, git over HTTP, the pages, the static files and the 404 of unknown URLs. create_app() in litestar/app.py assembles it from the ROUTES of the handler modules, reading the global configuration: it refuses the settings of what SourceLab dropped, and sets up the logging and the redis of the live updates. The pages render the templates with their own Jinja environment (litestar/templates.py), and build URLs with a Werkzeug map of the routes under the endpoint names the Flask views had (litestar/urls.py). NeoZen keeps the login sessions, and sourcelab/web/login_sessions.py finds the user of a request's session cookie. The session of the pages (flashes, CSRF secret) is Litestar's.

create_asgi_app, which handles the reverse proxy's headers, calls create_app, which reads the global sourcelab_config. create_app checks the settings, sets up the logging and redis, and builds the routes: the 90 endpoints of /api/0, the 5 of /pv that programs call, the 144 of the pages at / and of their JavaScript at /pv, the static files at /static, and url_map, the Werkzeug rules that url_for() builds with.

Project pages live at the URL root, so a top-level word like api or login can only be reserved through the BLACKLISTED_PROJECTS configuration list. A new root-level route needs a matching entry there. Most project routes exist in four forms: <repo>, <namespace>/<repo>, fork/<username>/<repo> and fork/<username>/<namespace>/<repo>.

A client request reaches provide_page, which opens the database session and builds the user, the forms and the CSP nonce. A request with a repo in its URL also loads the project, opens the repository, lists all branches and computes role flags. The handler gets g, reads or changes data through the services and git, and for a slow operation tracks a job in the database and redirects to /wait. templates.render() returns the page with its CSP header, and the database session closes.

Views are usually thin, and call the services and infra.git. In the service modules, functions take session as their first argument. Most of them flush and leave the commit to their caller, but some commit themselves, so check the function you're calling.

Internal endpoints (/pv)

/pv is the forge's internal HTTP API: endpoints that SourceLab's own code calls. Unlike /api/0, it has no documentation page and no stability promise, and other clients shouldn't use it. Its callers are of two kinds, served and authenticated differently.

Programs running next to the web application. Litestar serves these, from sourcelab/web/internal/. They act on behalf of other users, so the browser session never counts. A request with an Authorization header needs a token holding the internal_access ACL. A request without one must come from an address listed in IP_ALLOWED_INTERNAL.

Endpoint Caller Purpose
POST /pv/ssh/lookupkey/ files/keyhelper.py, sshd's AuthorizedKeysCommand Find the user or deploy key of the SSH key a client presents
POST /pv/ssh/checkaccess/ files/aclchecker.py, the forced command of that key Decide whether that user may read the requested repository, and where it is on disk
PUT /pv/ticket/comment/ The email milter (sourcelab-milters) Add an email reply as a comment on an issue, in the name of the sender's address
PUT /pv/pull-request/comment/ The email milter The same, on a pull request

The SSH helpers send SSH_ADMIN_TOKEN when it is set, and otherwise rely on their address. The milter sends no token, so it must reach the application from an allowed address. Behind a reverse proxy, the address is the one the application server reports: see IP_ALLOWED_INTERNAL.

The JavaScript of the web pages. Litestar serves these too, from sourcelab/web/internal/, beside the pages. They use the browser session like the pages that call them, and each POST checks the page's CSRF token.

Endpoint Used by
POST /pv/branches/commit/, POST /pv/branches/heads/ The commit and commit-list pages: the branches holding a commit
POST /pv/pull-request/merge The pull request page: whether it merges cleanly, fast-forwards or conflicts
POST /pv/pull-request/ready The repository and branches pages: the branches ready for a pull request
POST /pv/<repo>/issue/template The new-issue page: the content of an issue template
POST /pv/<repo>/family The new-pull-request page: the forks to choose from
POST /pv/stats/commits/authors, POST /pv/stats/commits/trend The statistics page
GET /pv/task/<id> Pages waiting for the value of a job

The project-scoped ones also exist in the namespaced and fork forms of project routes.

Data

There are two stores, and a single user action often touches both: the SQL database, which also holds the job queue, and the git repositories. Redis, if live updates are enabled, carries their messages.

Crow's feet mark the many side. User and Project each have many tokens, SSH keys and ProjectUser rows. SourceLabGroup and Project meet in ProjectGroup. Project has many issues, pull requests and boards. Issues have comments, pull requests have comments and flags, and PrToIssue links the two. Boards have statuses, and BoardIssues links statuses to issues.

Each project can have four bare repositories under GIT_FOLDER:

Type Contents
main The code
docs Published documentation, if ENABLE_DOCS is set
tickets One JSON file per issue, if ENABLE_TICKETS is set
requests One JSON file per pull request

The web application, the workers and the hooks must all see the same filesystem, which ties horizontal scaling to shared storage.

Redis only delivers the live page updates, through pub/sub.

Git as a data store

Any field in to_json has two consumers, the export and the importer in git.py, so both must change together.

The update_git task copies data from the SQL database to the tickets or requests repo through a temporary clone, writes JSON and pushes as "sourcelab". When a person pushes to that repo, the post-receive hook queues load_json_commits_to_db, which updates the database. The hook skips pushes made by "SourceLab", so the sync does not loop.

Git operations

Reads mostly use pygit2 in-process, and sometimes the git command line. Writes use TemporaryClone. It clones to a temporary directory, makes the changes, then runs git push with environment variables that the hooks read.

Variable Effect
GL_USER The acting user
internal=yes Marks a push made by SourceLab itself
pull_request_uid Tells hooks and ACL checks which pull request is being merged
internal_no_hooks=yes hookrunner exits before importing SourceLab, used when populating forks
SOURCELAB_HOOK_URL, SOURCELAB_HOOK_TOKEN The hooks ask the web application to run them (/pv/hooks), set when HOOK_SECRET is

This gives one consistent enforcement point, at the cost of a clone per operation.

A view queues the merge task and the browser waits on /wait. The task takes the WORKER lock in SQL, enters TemporaryClone, which clones the bare repo to a temp directory, fetches the fork and merges, then pushes with GL_USER and the pull request uid. The bare repo runs pre-receive and update hooks, gets the ACL verdict and runs post-receive. The task then closes the PR and releases the lock.

merge_pull_request both merges (domerge=True) and computes whether a pull request can be merged (domerge=False, which stores the result in merge_status).

merge_pull_request merges in a temporary clone and inspects the result. Already up to date: a check records NO_CHANGE, and a merge closes the PR and raises an already merged error. Fast-forward possible: a check records FFORWARD, and a merge moves the branch, pushes and closes the PR. No conflict: a check records MERGE, and a merge creates a merge commit, pushes and closes the PR. Conflicts: a check records CONFLICTS, and a merge raises an error.

Git transport and hooks

Over SSH, the two checks are separate: /pv/ssh decides read access; the hooks decide write access. Over HTTP, sourcelab/web/ui/clone.py proxies to git http-backend, and pushing needs ALLOW_HTTP_PUSH.

The git client connects to sshd. sshd runs keyhelper.py, which posts lookupkey to /pv/ssh and returns the key with a forced command. sshd then runs aclchecker.py, which posts checkaccess, for read access only, and executes receive-pack with GL_USER. receive-pack runs pre-receive and update in hookrunner, where write access is decided and refused refs are removed, then post-receive, and returns the push result.

A push runs hookrunner at least three times: pre-receive, one update per ref and post-receive. Loading SourceLab takes about a second each time, before any plugin does useful work.

When its environment has SOURCELAB_HOOK_URL and SOURCELAB_HOOK_TOKEN, which the pushes SourceLab starts set once HOOK_SECRET is configured (sourcelab.utils.hook_environ: in TemporaryClone.push, the mirrors, web/ui/clone.py and files/aclchecker.py), hookrunner imports nothing of SourceLab: it posts the changes and its git variables to /pv/hooks/<type>, where the web application, which has SourceLab loaded, runs sourcelab.plugins.push.run_hook and answers the hook's output and exit code. The variables include git's quarantine (GIT_QUARANTINE_PATH, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES): until git accepts the push, its objects are only there, so the plugins that read the pushed commits run git with them. If the request can't reach the application, the hook runs the hooks itself. If it reaches the application but no answer comes, the push fails, rather than running the hooks twice.

git runs a hook. If internal_no_hooks is set, it exits 0 with nothing imported. Otherwise it imports SourceLab, opens a session and finds the project. Pushes by SourceLab itself, static auth backends and post-receive skip the ACL check. Others run check_acl for each ref and remove refused refs, and if none remain the push is rejected with exit 1. It then runs enabled plugins and legacy hook scripts.

A plugin pairs a BaseHook (name, form, description) with a BaseRunner, and usually has its own table, in sourcelab/domain/model/plugins.py. Plugins are discovered by scanning sourcelab.plugins, so they must live in that package. Project admins enable them per project.

Background work

A job is a frozen msgspec message of sourcelab/domain/jobs.py, run by a method @job(Message) of a Myxo service in sourcelab/workers/. Code puts it with sourcelab.infra.queue.put(owner, message), and it is written when the session of owner commits, so a rolled-back change queues nothing. The job takes names and uids, and its function opens a session of its own (with_session) and reloads the ORM objects it needs.

The myxo_jobs table of the SQL database feeds the services. The process run by sourcelab_worker.service holds projects, repos, pull_requests and stats; keys, webhooks, commits, loadjson and mirror each have their own unit.

Events go the same way: sourcelab.infra.queue.publish(owner, event) writes an event of sourcelab/domain/events.py to Myxo's events table when the session commits, and Myxo delivers it to the services that @subscribe to it. The post-receive hook of a main repository publishes CommitsPushed (the refs, the pusher, the push options), but for an import (git push -o import), and commits it before running the project plugins, so that a failing plugin doesn't take it back.

Tests run a job right after its session commits, in the same thread, without serialization. Argument serialization bugs and concurrency bugs can't show up there.

A browser posts a form to a view, which tracks a job in the database, commits, and redirects to /wait/ticket. A worker takes the job. Until it is done, the browser keeps getting the waiting page. The worker then marks the job done or failed, and the /wait page redirects to the next URL, or to the previous page with the error.

Notifications

A mutation in a service module usually fans out by hand, with nothing to enforce it. So a new mutation must remember every channel: follow a neighbouring function.

A mutation in query.py calls up to four things by hand. update_git queues the update_git task, which writes the tickets or requests repo. notify.log publishes to fedmsg, fedora-messaging, STOMP, MQTT and blinker, and queues webhook_notification. REDIS.publish reaches the pages that follow the object, through the web app's live updates. notify functions send email over SMTP.

Authentication and authorization

SourceLab logs users in itself, with NeoZen, which keeps the passwords and the sessions; ctx.user, or g.fas_user in a page, is the user logged in. API tokens are rows with an expiry, an owner, an optional project and a set of ACLs.

Level Check Grants
Instance admin is_admin SOURCELAB_ADMIN_USERS or ADMIN_GROUP; passes the other checks
Project owner and admin is_repo_admin Settings, access management
commit is_repo_committer All branches
collaborator is_repo_collaborator Branches that match the granted patterns
ticket is_repo_user Issue triage, read access to private projects

Four mechanisms enforce these, and they don't share code: the checks of litestar/page.py (require_login, is_repo_admin...) and the role flags of g for the pages, sourcelab/web/litestar/identity.py and check_repo_permissions for the API and the programs' /pv endpoints, and the git auth backend for pushes. A change to the access rules usually has to reach several of them.

Configuration

The app's factory and the job topics read the configuration when the process starts, so changing those settings needs a new process.

default_config.py and the SOURCELAB_CONFIG file feed reload_config, which derives the folder settings and produces the global sourcelab.config.config at import. That global decides which routes exist, is checked by create_app, and configures hook processes.

Extension points

Mechanism Purpose
sourcelab.plugins entry point The forge's plugins: Plushy plugins, loaded at start by sourcelab/plugin.py, which add pages, APIs, templates, project tabs and sourcelab-admin commands (PLUGINS_DISABLED leaves some out). Their routes get the clients of their Myxo services from the web process's runtime. The builds (packages/sourcelab-builds/) are one
Myxo events CommitsPushed, for a plugin's services to @subscribe to
sourcelab.git_auth.helpers entry point Git authorization backends: Plushy plugins, subclasses of GitAuthHelper with a name, checked against the GitAuthBackend contract. GIT_AUTH_BACKEND names the one services/git_auth.py loads; the built-in ones are found even without installed entry points
BaseHook subclasses Project plugins, in the sourcelab.plugins package
blinker_publish A signal for in-process plugins