Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move serviceworker to workbox and fix SSE interference (#11538) #11547

Merged
merged 2 commits into from
May 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ rules:
no-cond-assign: [2, except-parens]
no-console: [1, {allow: [info, warn, error]}]
no-continue: [0]
no-empty: [2, {allowEmptyCatch: true}]
no-eq-null: [2]
no-mixed-operators: [0]
no-multi-assign: [0]
Expand Down
12 changes: 0 additions & 12 deletions modules/templates/dynamic.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,6 @@ func JSONRenderer() macaron.Handler {
})
}

// JSRenderer implements the macaron handler for serving JS templates.
func JSRenderer() macaron.Handler {
return macaron.Renderer(macaron.RenderOptions{
Funcs: NewFuncMap(),
Directory: path.Join(setting.StaticRootPath, "templates"),
AppendDirectories: []string{
path.Join(setting.CustomPath, "templates"),
},
HTMLContentType: "application/javascript",
})
}

// Mailer provides the templates required for sending notification mails.
func Mailer() (*texttmpl.Template, *template.Template) {
for _, funcs := range NewTextFuncMap() {
Expand Down
9 changes: 0 additions & 9 deletions modules/templates/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,6 @@ func JSONRenderer() macaron.Handler {
})
}

// JSRenderer implements the macaron handler for serving JS templates.
func JSRenderer() macaron.Handler {
return macaron.Renderer(macaron.RenderOptions{
Funcs: NewFuncMap(),
TemplateFileSystem: NewTemplateFileSystem(),
HTMLContentType: "application/javascript",
})
}

// Mailer provides the templates required for sending notification mails.
func Mailer() (*texttmpl.Template, *template.Template) {
for _, funcs := range NewTextFuncMap() {
Expand Down
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
"webpack": "4.43.0",
"webpack-cli": "3.3.11",
"webpack-fix-style-only-entries": "0.4.0",
"workbox-routing": "5.1.3",
"workbox-strategies": "5.1.3",
"worker-loader": "2.0.0"
},
"devDependencies": {
Expand Down
4 changes: 0 additions & 4 deletions routers/routes/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -1048,10 +1048,6 @@ func RegisterRoutes(m *macaron.Macaron) {
ctx.HTML(200, "pwa/manifest_json")
})

m.Get("/serviceworker.js", templates.JSRenderer(), func(ctx *context.Context) {
ctx.HTML(200, "pwa/serviceworker_js")
})

// prometheus metrics endpoint
if setting.Metrics.Enabled {
c := metrics.NewCollector()
Expand Down
26 changes: 2 additions & 24 deletions templates/base/head.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,6 @@
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>{{if .Title}}{{.Title | RenderEmojiPlain}} - {{end}} {{if .Repository.Name}}{{.Repository.Name}} - {{end}}{{AppName}} </title>
<link rel="manifest" href="{{AppSubUrl}}/manifest.json" crossorigin="use-credentials">
{{if UseServiceWorker}}
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('{{AppSubUrl}}/serviceworker.js').then(function(registration) {
// Registration was successful
console.info('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.info('ServiceWorker registration failed: ', err);
});
}
</script>
{{else}}
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.forEach(function(registration) {
registration.unregister();
console.info('ServiceWorker unregistered');
});
});
}
</script>
{{end}}
<meta name="theme-color" content="{{ThemeColorMetaTag}}">
<meta name="author" content="{{if .Repository}}{{.Owner.Name}}{{else}}{{MetaAuthor}}{{end}}" />
<meta name="description" content="{{if .Repository}}{{.Repository.Name}}{{if .Repository.Description}} - {{.Repository.Description}}{{end}}{{else}}{{MetaDescription}}{{end}}" />
Expand Down Expand Up @@ -84,8 +60,10 @@
</script>
<script>
window.config = {
AppVer: '{{AppVer}}',
AppSubUrl: '{{AppSubUrl}}',
StaticUrlPrefix: '{{StaticUrlPrefix}}',
UseServiceWorker: {{UseServiceWorker}},
csrf: '{{.CsrfToken}}',
HighlightJS: {{if .RequireHighlightJS}}true{{else}}false{{end}},
Minicolors: {{if .RequireMinicolors}}true{{else}}false{{end}},
Expand Down
83 changes: 0 additions & 83 deletions templates/pwa/serviceworker_js.tmpl

This file was deleted.

43 changes: 43 additions & 0 deletions web_src/js/features/serviceworker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const {UseServiceWorker, AppSubUrl, AppVer} = window.config;
const cacheName = 'static-cache-v2';

async function unregister() {
for (const registration of await navigator.serviceWorker.getRegistrations()) {
const serviceWorker = registration.active;
if (!serviceWorker) continue;
registration.unregister();
}
}

async function invalidateCache() {
await caches.delete(cacheName);
}

async function checkCacheValidity() {
const cacheKey = AppVer;
const storedCacheKey = localStorage.getItem('staticCacheKey');

// invalidate cache if it belongs to a different gitea version
if (cacheKey && storedCacheKey !== cacheKey) {
invalidateCache();
localStorage.setItem('staticCacheKey', cacheKey);
}
}

export default async function initServiceWorker() {
if (!('serviceWorker' in navigator)) return;

if (UseServiceWorker) {
await checkCacheValidity();
try {
await navigator.serviceWorker.register(`${AppSubUrl}/serviceworker.js`);
} catch (err) {
console.error(err);
await invalidateCache();
await unregister();
}
} else {
await invalidateCache();
await unregister();
}
}
2 changes: 2 additions & 0 deletions web_src/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import initGitGraph from './features/gitgraph.js';
import initClipboard from './features/clipboard.js';
import initUserHeatmap from './features/userheatmap.js';
import initDateTimePicker from './features/datetimepicker.js';
import initServiceWorker from './features/serviceworker.js';
import {initTribute, issuesTribute, emojiTribute} from './features/tribute.js';
import createDropzone from './features/dropzone.js';
import highlight from './features/highlight.js';
Expand Down Expand Up @@ -2477,6 +2478,7 @@ $(document).ready(async () => {
initGitGraph(),
initClipboard(),
initUserHeatmap(),
initServiceWorker(),
]);
});

Expand Down
16 changes: 16 additions & 0 deletions web_src/js/serviceworker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';

const cacheName = 'static-cache-v2';

const cachedDestinations = new Set([
'manifest',
'script',
'style',
'worker',
]);

registerRoute(
({request}) => cachedDestinations.has(request.destination),
new StaleWhileRevalidate({cacheName}),
);
9 changes: 8 additions & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,20 @@ module.exports = {
jquery: [
resolve(__dirname, 'web_src/js/jquery.js'),
],
serviceworker: [
resolve(__dirname, 'web_src/js/serviceworker.js'),
],
icons: glob('node_modules/@primer/octicons/build/svg/**/*.svg'),
...themes,
},
devtool: false,
output: {
path: resolve(__dirname, 'public'),
filename: 'js/[name].js',
filename: ({chunk}) => {
// serviceworker can only manage assets below it's script's directory so
// we have to put it in / instead of /js/
return chunk.id === 'serviceworker' ? '[name].js' : 'js/[name].js';
},
chunkFilename: 'js/[name].js',
},
optimization: {
Expand Down