optimise www redirect check

minor init.js optimisation
avoid gzip for empty obj in alerts endpoint
This commit is contained in:
Azareal 2020-03-06 13:07:28 +10:00
parent 8f21d34964
commit d2828471cd
4 changed files with 58 additions and 48 deletions

View File

@ -840,6 +840,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
// Redirect www. and local IP requests to the right place // Redirect www. and local IP requests to the right place
if strings.HasPrefix(shost, "www.") || c.Site.LocalHost {
if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) { if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) {
// TODO: Abstract the redirect logic? // TODO: Abstract the redirect logic?
w.Header().Set("Connection", "close") w.Header().Set("Connection", "close")
@ -858,6 +859,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, dest, http.StatusMovedPermanently) http.Redirect(w, req, dest, http.StatusMovedPermanently)
return return
} }
}
// Deflect malformed requests // Deflect malformed requests
if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) { if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) {

View File

@ -1,15 +1,15 @@
'use strict'; 'use strict';
var me = {}; var me={};
var phraseBox = {}; var phraseBox={};
if(tmplInits===undefined) var tmplInits = {}; if(tmplInits===undefined) var tmplInits={};
var tmplPhrases = []; // [key] array of phrases indexed by order of use var tmplPhrases=[]; // [key] array of phrases indexed by order of use
var hooks = { // Shorten this list by binding the hooks just in time? var hooks={ // Shorten this list by binding the hooks just in time?
"pre_iffe": [], "pre_iffe":[],
"pre_init": [], "pre_init":[],
"start_init": [], "start_init":[],
"almost_end_init": [], "almost_end_init":[],
"end_init": [], "end_init":[],
"after_phrases":[], "after_phrases":[],
"after_add_alert":[], "after_add_alert":[],
"after_update_alert_list":[], "after_update_alert_list":[],
@ -18,7 +18,7 @@ var hooks = { // Shorten this list by binding the hooks just in time?
"edit_item_pre_bind":[], "edit_item_pre_bind":[],
"analytics_loaded":[], "analytics_loaded":[],
}; };
var ranInitHooks = {} var ranInitHooks={}
function runHook(name, ...args) { function runHook(name, ...args) {
if(!(name in hooks)) { if(!(name in hooks)) {
@ -33,9 +33,9 @@ function runHook(name, ...args) {
return ret; return ret;
} }
function addHook(name, callback) { function addHook(name, h) {
if(hooks[name]===undefined) hooks[name] = []; if(hooks[name]===undefined) hooks[name] = [];
hooks[name].push(callback); hooks[name].push(h);
} }
// InitHooks are slightly special, as if they are run, then any adds after the initial run will run immediately, this is to deal with the async nature of script loads // InitHooks are slightly special, as if they are run, then any adds after the initial run will run immediately, this is to deal with the async nature of script loads
@ -45,22 +45,22 @@ function runInitHook(name, ...args) {
return ret; return ret;
} }
function addInitHook(name, callback) { function addInitHook(name, h) {
addHook(name, callback); addHook(name, h);
if(name in ranInitHooks) callback(); if(name in ranInitHooks) h();
} }
// Temporary hack for templates // Temporary hack for templates
function len(item) { function len(it) {
return item.length; return item.length;
} }
function asyncGetScript(source) { function asyncGetScript(src) {
return new Promise((resolve, reject) => { return new Promise((resolve,reject) => {
let script = document.createElement('script'); let script = document.createElement('script');
script.async = true; script.async = true;
const onloadHandler = (e, isAbort) => { const onloadHandler = (e,isAbort) => {
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
script.onload = null; script.onload = null;
script.onreadystatechange = null; script.onreadystatechange = null;
@ -75,17 +75,17 @@ function asyncGetScript(source) {
}; };
script.onload = onloadHandler; script.onload = onloadHandler;
script.onreadystatechange = onloadHandler; script.onreadystatechange = onloadHandler;
script.src = source; script.src = src;
const prior = document.getElementsByTagName('script')[0]; const prior = document.getElementsByTagName('script')[0];
prior.parentNode.insertBefore(script, prior); prior.parentNode.insertBefore(script, prior);
}); });
} }
function notifyOnScript(source) { function notifyOnScript(src) {
source = "/s/"+source; src = "/s/"+src;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let ss = source.replace("/s/",""); let ss = src.replace("/s/","");
try { try {
let ssp = ss.charAt(0).toUpperCase() + ss.slice(1) let ssp = ss.charAt(0).toUpperCase() + ss.slice(1)
console.log("ssp:",ssp) console.log("ssp:",ssp)
@ -95,8 +95,8 @@ function notifyOnScript(source) {
} }
} catch(e) {} } catch(e) {}
console.log("source:",source) console.log("src:",src)
let script = document.querySelectorAll('[src^="'+source+'"]')[0]; let script = document.querySelectorAll('[src^="'+src+'"]')[0];
console.log("script:",script); console.log("script:",script);
if(script===undefined) { if(script===undefined) {
reject("no script found"); reject("no script found");
@ -117,7 +117,7 @@ function notifyOnScript(source) {
}); });
} }
function notifyOnScriptW(name, complete, success) { function notifyOnScriptW(name,complete,success) {
notifyOnScript(name) notifyOnScript(name)
.then(() => { .then(() => {
console.log("Loaded " +name+".js"); console.log("Loaded " +name+".js");
@ -132,7 +132,7 @@ function notifyOnScriptW(name, complete, success) {
} }
// TODO: Send data at load time so we don't have to rely on a fallback template here // TODO: Send data at load time so we don't have to rely on a fallback template here
function loadScript(name, callback,fail) { function loadScript(name,callback,fail) {
let fname = name; let fname = name;
let value = "; " + document.cookie; let value = "; " + document.cookie;
let parts = value.split("; current_theme="); let parts = value.split("; current_theme=");
@ -142,18 +142,18 @@ function loadScript(name, callback,fail) {
let iurl = "/s/"+name+".js" let iurl = "/s/"+name+".js"
asyncGetScript(url) asyncGetScript(url)
.then(callback) .then(callback)
.catch((e) => { .catch(e => {
console.log("Unable to get script '"+url+"'"); console.log("Unable to get script '"+url+"'");
if(fname!=name) { if(fname!=name) {
asyncGetScript(iurl) asyncGetScript(iurl)
.then(callback) .then(callback)
.catch((e) => { .catch((e) => {
console.log("Unable to get script '"+iurl+"'"); console.log("Unable to get script '"+iurl+"'");
console.log("e: ", e); console.log("e:", e);
console.trace(); console.trace();
}); });
} }
console.log("e: ", e); console.log("e:", e);
console.trace(); console.trace();
fail(e); fail(e);
}); });
@ -166,8 +166,8 @@ function loadTmpl(name,callback) {
} }
*/ */
function DoNothingButPassBack(item) { function DoNothingButPassBack(it) {
return item; return it;
} }
function RelativeTime(date) { function RelativeTime(date) {
@ -243,8 +243,8 @@ function fetchPhrases(plist) {
if(loggedIn) { if(loggedIn) {
fetch("/api/me/") fetch("/api/me/")
.then((resp) => resp.json()) .then(resp => resp.json())
.then((data) => { .then(data => {
console.log("loaded me endpoint data"); console.log("loaded me endpoint data");
console.log("data:",data); console.log("data:",data);
me = data; me = data;
@ -254,4 +254,4 @@ function fetchPhrases(plist) {
me = {User:{ID:0,S:""},Site:{"MaxRequestSize":0}}; me = {User:{ID:0,S:""},Site:{"MaxRequestSize":0}};
runInitHook("pre_init"); runInitHook("pre_init");
} }
})(); })()

View File

@ -84,7 +84,7 @@ func main() {
vcpy := route.Vars vcpy := route.Vars
route.Vars = []string{"h"} route.Vars = []string{"h"}
route.Vars = append(route.Vars, vcpy...) route.Vars = append(route.Vars, vcpy...)
}/* else if route.Name != "common.RouteWebsockets" { } /* else if route.Name != "common.RouteWebsockets" {
//out += "\n\t\t\tsa := time.Now()" //out += "\n\t\t\tsa := time.Now()"
//out += "\n\t\t\tcn := uutils.Nanotime()" //out += "\n\t\t\tcn := uutils.Nanotime()"
}*/ }*/
@ -167,8 +167,8 @@ func main() {
/*if !route.Action && !route.NoHead && !group.NoHead { /*if !route.Action && !route.NoHead && !group.NoHead {
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[route.Name]) + ", h.StartedAt)" out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[route.Name]) + ", h.StartedAt)"
} else {*/ } else {*/
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[route.Name]) + ")" //out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[route.Name]) + ")"
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[route.Name]) + ", cn)" out += "\n\t\t\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[route.Name]) + ", cn)"
//} //}
} }
@ -193,8 +193,8 @@ func main() {
/*if !defaultRoute.Action && !defaultRoute.NoHead && !group.NoHead { /*if !defaultRoute.Action && !defaultRoute.NoHead && !group.NoHead {
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", h.StartedAt)" out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", h.StartedAt)"
} else {*/ } else {*/
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ")" //out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ")"
out += "\n\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", cn)" out += "\n\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", cn)"
//} //}
} }
out += ` out += `
@ -559,6 +559,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
} }
// Redirect www. and local IP requests to the right place // Redirect www. and local IP requests to the right place
if strings.HasPrefix(shost, "www.") || c.Site.LocalHost {
if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) { if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) {
// TODO: Abstract the redirect logic? // TODO: Abstract the redirect logic?
w.Header().Set("Connection", "close") w.Header().Set("Connection", "close")
@ -577,6 +578,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, dest, http.StatusMovedPermanently) http.Redirect(w, req, dest, http.StatusMovedPermanently)
return return
} }
}
// Deflect malformed requests // Deflect malformed requests
if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) { if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) {

View File

@ -131,12 +131,23 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
topCreatedAt = uCreatedAt topCreatedAt = uCreatedAt
} }
} }
err = rows.Err() if err = rows.Err(); err != nil {
if err != nil {
return c.InternalErrorJS(err, w, r) return c.InternalErrorJS(err, w, r)
} }
} }
if count == 0 || len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
gzw, ok := w.(c.GzipResponseWriter)
if ok {
w = gzw.ResponseWriter
h := w.Header()
h.Del("Content-Type")
h.Del("Content-Encoding")
}
_, _ = io.WriteString(w, `{}`)
return nil
}
// Might not want to error here, if the account was deleted properly, we might want to figure out how we should handle deletions in general // Might not want to error here, if the account was deleted properly, we might want to figure out how we should handle deletions in general
list, err := c.Users.BulkGetMap(actors) list, err := c.Users.BulkGetMap(actors)
if err != nil { if err != nil {
@ -144,11 +155,6 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
return c.InternalErrorJS(err, w, r) return c.InternalErrorJS(err, w, r)
} }
if count == 0 || len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
_, _ = io.WriteString(w, `{}`)
return nil
}
var ok bool var ok bool
var sb strings.Builder var sb strings.Builder
sb.Grow(c.AlertsGrowHint + (len(alerts) * c.AlertsGrowHint2)) sb.Grow(c.AlertsGrowHint + (len(alerts) * c.AlertsGrowHint2))