Skip to content

Commit

Permalink
chore: OPTIC-1061: Improve webpack bundle management so bundles can b…
Browse files Browse the repository at this point in the history
…e cached more effectively (#6797)
  • Loading branch information
bmartel authored Dec 17, 2024
1 parent 4dd9e7a commit dfa7932
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 4 deletions.
12 changes: 12 additions & 0 deletions label_studio/core/templatetags/filters.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""

import json
import re
from datetime import datetime

from core.utils.manifest_assets import get_manifest_asset
from django import template
from django.conf import settings
from django.utils.html import format_html

register = template.Library()


@register.simple_tag
def manifest_asset(path):
"""Maps a path to its hashed filename using manifest.json, or falls back to /react-app/ prefix
Usage in template:
{% manifest_asset 'main.js' %}
"""
return get_manifest_asset(path)


@register.filter
def initials(val, jn=''):
"""Given a string return its initials join by $jn"""
Expand Down
8 changes: 7 additions & 1 deletion label_studio/core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,13 @@
),
re_path(r'^dm/(?P<path>.*)$', serve, kwargs={'document_root': settings.DM_ROOT, 'show_indexes': True}),
re_path(
r'^react-app/(?P<path>.*)$', serve, kwargs={'document_root': settings.REACT_APP_ROOT, 'show_indexes': True}
r'^react-app/(?P<path>.*)$',
serve,
kwargs={
'document_root': settings.REACT_APP_ROOT,
'show_indexes': True,
'manifest_asset_prefix': 'react-app',
},
),
re_path(
r'^static/fonts/roboto/roboto.css$',
Expand Down
27 changes: 27 additions & 0 deletions label_studio/core/utils/manifest_assets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import json
from pathlib import Path

from django.conf import settings

# Load manifest.json once at module scope
_MANIFEST = {}
try:
if not settings.DEBUG:
manifest_path = Path(settings.STATIC_ROOT) / 'js/manifest.json'
if manifest_path.exists():
with open(manifest_path, 'r') as f:
_MANIFEST = json.load(f)
except Exception:
# If there's any error reading the manifest, we'll use the default mapping
pass


def get_manifest_asset(path: str) -> str:
"""Maps a path to its hashed filename using manifest.json, or falls back to /react-app/ prefix
Usage in template:
{% manifest_asset 'main.js' %}
"""
if path in _MANIFEST:
return f'{settings.FRONTEND_HOSTNAME}{_MANIFEST[path]}'
return f'{settings.FRONTEND_HOSTNAME}/react-app/{path}'
22 changes: 21 additions & 1 deletion label_studio/core/utils/static_serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""

import mimetypes
import posixpath
from pathlib import Path

from core.utils.manifest_assets import get_manifest_asset
from django.http import (
Http404,
HttpResponseNotModified,
Expand All @@ -17,7 +19,7 @@
from ranged_fileresponse import RangedFileResponse


def serve(request, path, document_root=None, show_indexes=False):
def serve(request, path, document_root=None, show_indexes=False, manifest_asset_prefix=None):
"""
Serve static files below a given point in the directory structure.
Expand All @@ -32,11 +34,29 @@ def serve(request, path, document_root=None, show_indexes=False):
of the directory. This index view will use the template hardcoded below,
but if you'd like to override it, you can create a template called
``static/directory_index.html``.
If manifest_asset_prefix is provided, we will try to serve the file from the manifest.json
if the file is not found in the document_root.
Example:
path = "main.js"
document_root = "/dist/apps/labelstudio/"
manifest_asset_prefix = "react-app"
manifest_json = {"main.js": "/react-app/main.123456.js"}
fullpath = Path(safe_join(document_root, "main.123456.js"))
"""
path = posixpath.normpath(path).lstrip('/')
fullpath = Path(safe_join(document_root, path))
if fullpath.is_dir():
raise Http404(_('Directory indexes are not allowed here.'))
if manifest_asset_prefix and not fullpath.exists():
possible_asset = get_manifest_asset(path)
manifest_asset_prefix = (
f'/{manifest_asset_prefix}' if not manifest_asset_prefix.startswith('/') else manifest_asset_prefix
)
if possible_asset.startswith(manifest_asset_prefix):
possible_asset = possible_asset[len(manifest_asset_prefix) :]
fullpath = Path(safe_join(document_root, possible_asset))
if not fullpath.exists():
raise Http404(_('“%(path)s” does not exist') % {'path': fullpath})
# Respect the If-Modified-Since header.
Expand Down
4 changes: 3 additions & 1 deletion label_studio/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
<!-- CSS -->
<link href="{{settings.HOSTNAME}}{% static 'css/uikit.css' %}" rel="stylesheet">
<link href="{{settings.HOSTNAME}}{% static 'css/main.css' %}" rel="stylesheet">
<link href="{{settings.FRONTEND_HOSTNAME}}/react-app/main.css?v={{ versions.backend.commit }}" rel="stylesheet">
{% block app-css %}
<link href="{{settings.FRONTEND_HOSTNAME}}/react-app/main.css?v={{ versions.backend.commit }}" rel="stylesheet">
{% endblock %}

{% block app-scripts %}
{% endblock %}
Expand Down
5 changes: 4 additions & 1 deletion label_studio/templates/simple.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
<meta name="apple-mobile-web-app-status-bar-style" content="#272727"> <!-- iOS Safari -->

<link href="{{settings.HOSTNAME}}{% static 'css/main.css' %}" rel="stylesheet"/>
<link href="{{settings.FRONTEND_HOSTNAME}}/react-app/main.css?v={{ versions.backend.commit }}" rel="stylesheet">
{% block app-css %}
<link href="{{settings.FRONTEND_HOSTNAME}}/react-app/main.css?v={{ versions.backend.commit }}" rel="stylesheet">
{% endblock %}


{% block page_labeling %}
<title>Label Studio</title>
Expand Down

0 comments on commit dfa7932

Please sign in to comment.