add Cache-Control header

This commit is contained in:
Izalia Mae 2024-03-04 00:32:13 -05:00
parent 4639d8a78d
commit d7cfa12145
3 changed files with 19 additions and 22 deletions

View file

@ -28,7 +28,7 @@ from .views.frontend import handle_frontend_path
if typing.TYPE_CHECKING:
from tinysql import Database, Row
from .cache import Cache
from .misc import Message
from .misc import Message, Response
# pylint: disable=unsubscriptable-object
@ -36,11 +36,12 @@ if typing.TYPE_CHECKING:
class Application(web.Application):
DEFAULT: Application = None
def __init__(self, cfgpath: str | None):
def __init__(self, cfgpath: str | None, dev: bool = False):
web.Application.__init__(self,
middlewares = [
handle_api_path,
handle_frontend_path
handle_frontend_path,
handle_response_headers
]
)
@ -50,6 +51,7 @@ class Application(web.Application):
self['signer'] = None
self['start_time'] = None
self['cleanup_thread'] = None
self['dev'] = dev
self['config'] = Config(cfgpath, load = True)
self['database'] = get_database(self.config)
@ -255,25 +257,18 @@ class PushWorker(multiprocessing.Process):
await client.close()
@web.middleware
async def handle_response_headers(request: web.Request, handler: Coroutine) -> Response:
resp = await handler(request)
resp.headers['Server'] = 'ActivityRelay'
async def handle_access_log(request: web.Request, response: web.Response) -> None:
address = request.headers.get(
'X-Forwarded-For',
request.headers.get(
'X-Real-Ip',
request.remote
)
)
if request.app['dev'] and request.path.endswith(('.css', '.js')):
resp.headers['Cache-Control'] = 'public,max-age=2628000,immutable'
logging.info(
'%s "%s %s" %i %i "%s"',
address,
request.method,
request.path,
response.status,
response.content_length or 0,
request.headers.get('User-Agent', 'n/a')
)
else:
resp.headers['Cache-Control'] = 'no-store'
return resp
async def handle_cleanup(app: Application) -> None:

View file

@ -94,7 +94,7 @@ def cli_run():
class WatchHandler(PatternMatchingEventHandler):
patterns = ['*.py']
cmd = [sys.executable, '-m', 'relay', 'run']
cmd = [sys.executable, '-m', 'relay', 'run', '-d']
def __init__(self):

View file

@ -188,8 +188,9 @@ def cli_setup(ctx: click.Context) -> None:
@cli.command('run')
@click.option('--dev', '-d', is_flag=True, help='Enable developer mode')
@click.pass_context
def cli_run(ctx: click.Context) -> None:
def cli_run(ctx: click.Context, dev: bool = False) -> None:
'Run the relay'
if ctx.obj.config.domain.endswith('example.com') or not ctx.obj.signer:
@ -216,6 +217,7 @@ def cli_run(ctx: click.Context) -> None:
click.echo(pip_command)
return
ctx.obj['dev'] = True
ctx.obj.run()
# todo: figure out why the relay doesn't quit properly without this