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:
- 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.
- 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. - Git hooks run the whole application. Each hook is a new Python process that imports SourceLab, opens a database session and runs plugins.
- 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. - 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.
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.
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>.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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 |