Skip to content

Commit

Permalink
🧹 dapp sunucusunu pageWorker yap
Browse files Browse the repository at this point in the history
  • Loading branch information
KimlikDAO-bot committed Dec 2, 2023
1 parent 3022be1 commit 0c41c45
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 157 deletions.
2 changes: 1 addition & 1 deletion lib
Submodule lib updated 2 files
+13 −0 cloudflare/pageWorker.d.js
+150 −0 cloudflare/pageWorker.js
6 changes: 5 additions & 1 deletion sunucu/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ $(PAGE_TARGETS): build/%.sayfa: $(call compressions,build/%-en.html build/%-tr.h
build: $(PAGE_TARGETS)

build/sunucu/prod.js: sunucu/prod.js sunucu/prod.d.js \
lib/cloudflare/moduleWorker.d.js lib/cloudflare/types.d.js
lib/cloudflare/moduleWorker.d.js lib/cloudflare/types.d.js \
lib/cloudflare/pageWorker.d.js lib/cloudflare/pageWorker.js
mkdir -p $(dir $@)
yarn google-closure-compiler -W VERBOSE -O ADVANCED --charset UTF-8 \
--jscomp_error=checkTypes \
Expand All @@ -22,7 +23,10 @@ build/sunucu/prod.js: sunucu/prod.js sunucu/prod.d.js \
--jscomp_error=reportUnknownTypes \
--emit_use_strict \
--language_in ECMASCRIPT_NEXT \
--module_resolution NODE \
--assume_function_wrapper \
--dependency_mode PRUNE \
--entry_point $< \
--js $^ \
--js_output_file $@
yarn uglifyjs $@ -m -c toplevel,unsafe,drop_console -o $@
Expand Down
158 changes: 5 additions & 153 deletions sunucu/prod.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,7 @@
// Has to end with a slash
/** @define {string} */
const HOST_URL = "https://kimlikdao.org/";
/** @const {string} */
const PAGE_CACHE_CONTROL = "max-age=90,public";
/**
* @const {string}
* @noinline
*/
const STATIC_CACHE_CONTROL = "max-age=29030400,public,immutable";
/** @const {!Object<string, string>} */
const MIMES = {
"css": "text/css",
"js": "application/javascript;charset=utf-8",
"svg": "image/svg+xml",
"woff2": "font/woff2",
"ttf": "font/ttf",
"png": "image/png",
"txt": "text/plain",
};
/** @const {!Object<string, string>} */
const PAGES = {
import { create } from "/lib/cloudflare/pageWorker";

/** @const {!cloudflare.ModuleWorker} */
const ProdWorker = create("https://kimlikdao.org/", {
"?tr": "ana-tr.html",
"?en": "ana-en.html",
"al": "al-tr.html",
Expand All @@ -30,137 +12,7 @@ const PAGES = {
"vote": "oyla-en.html",
"iptal": "iptal-tr.html",
"revoke": "iptal-en.html"
};

/**
* @return {!Response}
*/
const err = () => new Response("NAPÄ°M?", {
status: 404,
headers: { "content-type": "text/plain;charset=utf-8" }
})

/**
* @implements {cloudflare.ModuleWorker}
*/
const ProdWorker = {
/**
* @override
*
* @param {!cloudflare.Request} req
* @param {!ProdEnvironment} env
* @param {!cloudflare.Context} ctx
* @return {!Promise<!Response>}
*/
fetch(req, env, ctx) {
/** @const {string} */
const url = req.url;
/** @const {string} */
const enc = req.cf.clientAcceptEncoding || "";
/** @const {string} */
const ext = (url.endsWith(".woff2") || url.endsWith(".png"))
? ""
: enc.includes("br") ? ".br" : enc.includes("gz") ? ".gz" : "";
/** @const {number} */
const idx = url.lastIndexOf(".");

/** @type {?string} */
let kvKey = url.slice(HOST_URL.length);
/** @type {?string} */
let cacheKey;
if (kvKey && idx != HOST_URL.lastIndexOf("."))
cacheKey = url;
else {
/** @const {number} */
const qmark = kvKey.lastIndexOf("?");
if (qmark != -1 && kvKey.length > 3)
kvKey = kvKey.slice(0, qmark);
if (kvKey) kvKey = PAGES[kvKey];
else {
/** @const {?string} */
const cookie = req.headers.get("cookie");
kvKey = (cookie ? cookie.includes("l=tr")
: req.headers.get("accept-language")?.includes("tr"))
? "ana-tr.html" : "ana-en.html";
}
cacheKey = HOST_URL + kvKey
}
kvKey += ext;
cacheKey += ext;

/** @type {boolean} */
let inCache = false;
/**
* We search the CF cache for the asset.
*
* @const {!Promise<!Response>}
*/
const fromCache = caches.default.match(cacheKey).then((response) => {
if (!response) return Promise.reject();
inCache = true;
return response;
});

/**
* @param {!ArrayBuffer} body
* @return {!Response}
*/
const makeResponse = (body) => {
/** @const {string} */
const suffix = url.slice(idx + 1);
/** @type {!Object<string, string>} */
let headers = {
"cache-control": idx == HOST_URL.lastIndexOf(".")
? PAGE_CACHE_CONTROL
: STATIC_CACHE_CONTROL,
"content-encoding": ext === ".br" ? "br" : ext === ".gz" ? "gzip" : "",
"content-length": body.byteLength,
"content-type": idx == HOST_URL.lastIndexOf(".")
? "text/html;charset=utf-8"
: MIMES[suffix],
"expires": "Sun, 01 Jan 2034 00:00:00 GMT",
"vary": "accept-encoding",
}
if (idx == HOST_URL.lastIndexOf("."))
headers["cdn-cache-control"] = STATIC_CACHE_CONTROL;
else if (suffix == "woff2" || suffix == "ttf")
headers["access-control-allow-origin"] = "*";
return new Response(body, {
headers,
"encodeBody": "manual"
});
}

/**
* In parallel, we also query the CF KV. Under normal circumstances, if
* the asset is present in the CF cache, `fromCache` promise should always
* win the race.
* If the asset has been evicted from CF cache, this promise will get it
* from KV and write it to CF cache (after a small header modification).
* If the asset is present in CF cache and the cache returns in a timely
* manner, this promise will not re-write to CF cache, as the `fromCache`
* promise will set the `inCache` flag, which prevents this promise from
* recaching the response.
* In all other cases (either the response is not present in CF cache or
* CF cache is taking unusually long), the response will be served from the
* KV.
*
* @const {!Promise<!Response>}
*/
const fromKV = env.KV.get(kvKey, "arrayBuffer").then((body) => {
if (!body) return Promise.reject();
// Remember to cache the response, but only after we finish serving the
// request.
ctx.waitUntil(new Promise((/** function(?):void */ resolve) =>
resolve(inCache ? null : caches.default.put(/** @type {string} */(cacheKey),
makeResponse(/** @type {!ArrayBuffer} */(body))))
));
return makeResponse(body);
})

return Promise.any([fromCache, fromKV]).catch(err);
}
}
});

globalThis["ProdWorker"] = ProdWorker;
export default ProdWorker;
1 change: 1 addition & 0 deletions sunucu/test/Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
build/sunucu/test/prod.compiled-test.js: sunucu/test/prod.compiled-test.js \
sunucu/prod.js sunucu/prod.d.js \
lib/cloudflare/types.d.js lib/cloudflare/moduleWorker.d.js \
lib/cloudflare/pageWorker.d.js lib/cloudflare/pageWorker.js \
lib/testing/assert.js lib/testing/nodejs.d.js
mkdir -p $(dir $@)
yarn google-closure-compiler -W VERBOSE -O ADVANCED --charset UTF-8 \
Expand Down
5 changes: 3 additions & 2 deletions sunucu/test/prod.compiled-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,9 @@ const createRequest = (url, encoding, cookie) => /** @type {!cloudflare.Request}
}
});

const testKvName = (url, acceptEncoding, cookie, kvName) => ProdWorker.fetch(
createRequest(url, acceptEncoding, cookie), env, ctx)
const testKvName = (url, acceptEncoding, cookie, kvName) => /** @type {!Promise<Response>} */(
ProdWorker.fetch(
createRequest(url, acceptEncoding, cookie), env, ctx))
.then((res) => res.text())
.then((res) => assertEq(res, kvName));

Expand Down

0 comments on commit 0c41c45

Please sign in to comment.