Repository navigation
Conversation
This is a first step. It's not fully tested. It doesn't keep the full API space of the previous parent's internals but it does keep the features we know are used in the wild. Needs testing.
(cherry picked from commit 0379c61)
…d expand minimally with some much needed compilers (cherry picked from commit 5fba2e5)
(cherry picked from commit 3063183)
(cherry picked from commit da5fa38)
(cherry picked from commit 6882a65)
…st context (cherry picked from commit 8f3622e)
… parts of the helper function, so we don't need to be backward compatible with them (cherry picked from commit 81c7dbb)
…port for providing scope, wait_for_triplestore no longer does a sudo query to not break non-sudo services (cherry picked from commit 8533639)
(cherry picked from commit 726317f)
…th an example implementation services could use while waiting for the real deal (cherry picked from commit d02fbb6)
Raising a BaseHTTPException results in a JSONAPI error response. It is available without import and takes the same arguments as in the FastAPI based semantic-ai/mu-python-template. A sudo query without permission raises it with status 403. Co-authored-by: Joachim van der Herten <joachim@ml2grow.com>
Services may configure helpers.sparqlQuery and helpers.sparqlUpdate (e.g. a timeout or custom headers such as mu-auth-sudo), which earlier versions of the template applied to every query. Copying those per query keeps that working while staying thread-safe. As every query starts from a copy, the sudo and scope headers no longer need to be cleared.
- validate_resource_type compared strings by identity, rejecting valid resource types - validate_json_api_content_type crashed on requests without Content-Type - update_modified used the time the service started as default date
The Uvicorn worker sizes its WSGI thread pool with gunicorn's threads setting (default 1, e.g. GUNICORN_CMD_ARGS="--threads 4"), so a worker handles one request at a time like with meinheld. It also stops when gunicorn's reloader requests so, which Uvicorn didn't check. The uvicorn-worker package replaces the deprecated uvicorn.workers module. DEV_SERVER=gunicorn runs the production server with live-reloading in development mode. app.before_first_request, removed in Flask 2.3, is emulated with a deprecation warning.
Co-authored-by: Joachim van der Herten <joachim@ml2grow.com> Co-authored-by: karel kremer <karel.kremer@redpencil.io>
|
I will also remove the logs being written to a file, since that's not in-line with other templates. If you want to keep logs this can be done through docker. |
Other templates only write to stdout and logs are available through stdout. Removing this for consistency. Log files require management and it's easiest if this is done in one place (through docker logs)
to keep .git and CI config out of the image
In line with the js template. Allowed groups resolved by mu-authorization are stored per request and forwarded to the client.
uv is a fast, pip-compatible installer. The pip-style interface is used with --system: no virtual environments (the container provides the isolation)
| from uvicorn_worker import UvicornWorker | ||
|
|
||
|
|
||
| class UvicornWSGIWorker(UvicornWorker): |
There was a problem hiding this comment.
As a general comment, why the choice to run Uvicorn which is an ASGI webserver as worker for Gunicorn, a WSGI webserver? Flask is a WSGI framework hence inside the ASGI worker it needs to be wrapped again in the WSGI middleware.
start.sh can then simply run:
gunicorn --reload -k gthread -c /gunicorn_conf.py web:app and this entire file can be deleted.
There was a problem hiding this comment.
based on a chat conversation: do note that Flask is always sync. Even if you start using async handlers in Flask, in the end they run in an eventloop which is then run synchronously. The webapp therefor always runs on top of a WSGI webserver framework, if you bring an ASGI webserver you need the middleware to convert it (basically running the webapp in a threadpool so it becomes async again).
| @@ -24,6 +25,8 @@ | |||
| """ | |||
|
|
|||
| MU_APPLICATION_GRAPH = os.environ.get('MU_APPLICATION_GRAPH') | |||
There was a problem hiding this comment.
In general: these global dependencies on the environment with no defaults make testing harder.
There was a problem hiding this comment.
a fair remark,but can perhaps be deferred to a separate PR?
| builtins.app = app | ||
| builtins.helpers = helpers | ||
| builtins.sparql_escape = sparql_escape | ||
| builtins.BaseHTTPException = BaseHTTPException |
There was a problem hiding this comment.
these things are there for backward compatibility but should be removed, regardless if it breaks anything or not and definitely not be expanded.
-
Every module in the worker, including third-party libraries, sees
app,helpers,sparql_escape,BaseHTTPExceptionas builtins. A dependency that happens to use any of these names as a variable now has different behavior inside this container than anywhere else. That's a debugging nightmare that will be attributed to anything but the template. -
any tooling such as mypy, ruff, pyright, pylint,... which are usually included for validation in CI are left broken because of this.
-
Any local variable named
apporhelpersin a service function shadows the builtin in that scope only. The service works until a refactor moves a line out of the function, then breaks withNameError/AttributeErrorfar from the cause. And becausehelpersis both a real importable module and a builtin,import helpersvs. ambienthelperscan even resolve to different objects in edge cases with reloads. -
it makes automated testing reliant on executing web.py's side effects.
-
for developers its super confusing.
There was a problem hiding this comment.
Thanks for bringing this to my attention, we had a similar thing in the ruby template so I took a similar approach here:
- BaseHTTPException is no longer a builtin, since it's new. it has to be imported from helpers.
- Using helpers or sparql_escape without an import still works, but logs a deprecation warning (once per helper, can be turned off with PRINT_DEPRECATION_WARNINGS). Services that import explicitly shadow the builtin and don't get a warning. The README now recommends explicit imports.
- The idea is to remove them in the next major version.
avoids an extra line in traceback
previously an invalid configuration for log level would cause an unclear error, we raise a clear error that cannot be ignored. An empty or unset log level now defaults to info.
BaseHTTPException is no longer added as a builtin, services import it from helpers. Using helpers or sparql_escape without an import still works for backwards compatibility, but logs a deprecation warning once per helper. PRINT_DEPRECATION_WARNINGS (default true) disables these warnings, similar to the ruby template. The before_first_request warning now uses the same mechanism: Python hides a DeprecationWarning raised outside of __main__, so it was never shown. The README recommends explicit imports.
it had not been working for a long time (likely since beta.1)
this is a configuration error of the service, not a client error, so a 403 was misleading. A plain exception also works outside of a request context and matches the javascript template.
the validators returned None on success, so callers had to check the result before returning it. They now raise a BaseHTTPException, similar to the ruby template where they halt the request. Services returning the result keep working, as the error response is the same. A missing type in validate_resource_type now results in a 409 instead of a KeyError.
aligns with sparqlEscapeDecimal in the javascript template. Values are written in fixed-point notation, as xsd:decimal does not allow an exponent.
Modernizes the template for the 2.0.0 release: a supported Python and server, thread-safe helpers, mu-authorization support and pinned dependencies.
Server & base image
tiangolo/meinheld-gunicorn:python3.8base image withpython:3.13-slim, running gunicorn with threaded (gthread) workers. Behaviour is unchanged: 1 worker (WEB_CONCURRENCY) handling one request at a time. Other gunicorn settings can be passed throughGUNICORN_CMD_ARGS, e.g.--threads 4.DEV_SERVER=gunicornfor development mode: the production server with live reload, e.g. to test behaviour with multiple workers or threads. The Flask development server (with debugger) stays the default.on-build.shhook, in line with the other templates: services can install system packages before their Python requirements are installed. gcc and g++ are included for packages without wheels..dockerignore.latestand feature branches./logsis no longer used.MODULE_NAME,APP_MODULE,GUNICORN_CONF,WORKERS_PER_CORE, …) are no longer supported (as far as we know they weren't used). UseWEB_CONCURRENCY,HOST,PORT,BINDandGUNICORN_CMD_ARGSinstead.Helpers
query()andupdate()execute on a copy of the sharedSPARQLWrapperinstances. Configuration set on the shared instances (timeouts, custom headers) still applies to every query.mu-auth-allowed-groupsandmu-auth-used-groupsheaders returned by mu-authorization are forwarded to the client, and the resolved groups are reused for later queries within the same request.update()returns the SPARQLWrapperQueryResult.BaseHTTPException: raise it anywhere in a handler to return a JSON:API error response. Breaking:validate_json_api_content_typeandvalidate_resource_typeraise it instead of returning an error response. Returning their result from a route keeps working.sparql_escape_decimal.sparql_escapenow escapesTrue/Falseasxsd:booleaninstead ofxsd:integer.LOG_LEVELraises an error at startup.update_modifiedhelper was removed.Deprecations
Logged once per feature, can be turned off with
PRINT_DEPRECATION_WARNINGS=false.helpersandsparql_escapewithout importing them.app.before_first_request: brought back for services written against older Flask versions, but deprecated in favour of startup code at the top level ofweb.py.Compatibility
Python 3.13, Flask 3.1, SPARQLWrapper 2.0, rdflib 7.6, gunicorn 26.2. Pinned dependencies of services might need an update.
Tested
ONBUILDinstalls the child's requirements.mu-auth-allowed-groupsis forwarded to the client.ModuleNotFoundError.DEV_SERVER=flaskandDEV_SERVER=gunicorn.Closes #12, closes #14, closes #18, closes #19, closes #28, closes #33, closes #34, closes #36, closes #37