Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 57e7254f8d | |||
| e379a86020 | |||
| e160701403 | |||
| cbfc496057 | |||
| ff257ae976 | |||
| e12466d5f2 | |||
| 4e48d6b40b | |||
| 1aed42598a | |||
| b55b0bd056 | |||
| 7815ae3c57 | |||
| 882a416831 | |||
| 4bd279798c | |||
| 138c8eaaeb | |||
| b3599633f9 | |||
| f3a107111f | |||
| 8b938fdd42 | |||
| 80945de92d |
@@ -0,0 +1,7 @@
|
||||
tsc:
|
||||
cd priv/static/js &&\
|
||||
tsc
|
||||
|
||||
watch:
|
||||
cd priv/static/js &&\
|
||||
tsc --watch
|
||||
@@ -1,3 +1,10 @@
|
||||
OPEN LOOPS - 2025-11-12
|
||||
- websockets
|
||||
- separate websocket handling from websocket parsing/sending
|
||||
- do renaming
|
||||
- make wfc not terrible
|
||||
|
||||
|
||||
VIDEO 1 - 2025-09-16
|
||||
TODONE
|
||||
- add qhl as dep
|
||||
|
||||
+7
-3
@@ -3,7 +3,11 @@
|
||||
{registered,[]},
|
||||
{included_applications,[]},
|
||||
{applications,[stdlib,kernel]},
|
||||
{vsn,"0.1.0"},
|
||||
{modules,[fd_client,fd_client_man,fd_client_sup,fd_clients,
|
||||
fd_sup,fewd]},
|
||||
{vsn,"0.2.0"},
|
||||
{modules,[fd_cache,fd_httpd,fd_httpd_client,fd_httpd_client_man,
|
||||
fd_httpd_client_sup,fd_httpd_clients,fd_httpd_sfc,
|
||||
fd_httpd_sfc_cache,fd_httpd_sfc_entry,fd_httpd_utils,
|
||||
fd_sup,fd_wsp,fewd,qhl,qhl_ws,wfc,wfc_bm,wfc_eval,
|
||||
wfc_eval_context,wfc_ltr,wfc_pp,wfc_read,wfc_sentence,
|
||||
wfc_sftt,wfc_ttfuns,wfc_utils,wfc_word,zj]},
|
||||
{mod,{fewd,[]}}]}.
|
||||
|
||||
@@ -23,3 +23,10 @@
|
||||
-type body() :: {partial, binary()} | {multipart, [body_part()]} | zj:value() | binary().
|
||||
-type body_part() :: {Field :: binary(), Data :: binary()}
|
||||
| {Field :: binary(), Name :: binary(), Data :: binary()}.
|
||||
|
||||
|
||||
-type request() :: #request{}.
|
||||
-type response() :: #response{}.
|
||||
-type tcp_error() :: closed
|
||||
| {timeout, RestData :: binary() | erlang:iovec()}
|
||||
| inet:posix().
|
||||
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Chat with Websockets</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1 class="content-title">Chat with websockets</h1>
|
||||
|
||||
<div class="content-body">
|
||||
<input autofocus label="Nick" id="nick"></input>
|
||||
<textarea hidden disabled id="wfc-output"></textarea>
|
||||
<input hidden id="wfc-input"></input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let nelt = document.getElementById('nick');
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let ws = new WebSocket("/ws/chat");
|
||||
let nick = '';
|
||||
|
||||
// when user hits any key while typing in nick
|
||||
function on_nick(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = nelt.value;
|
||||
let trimmed = contents.trim();
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = trimmed.length > 0;
|
||||
if (nonempty_contents) {
|
||||
nick = trimmed;
|
||||
let msg_obj = ['nick', nick];
|
||||
let msg_str = JSON.stringify(msg_obj);
|
||||
console.log('message to server:', contents.trim());
|
||||
// query backend for result
|
||||
ws.send(msg_str);
|
||||
|
||||
// delete element from dom
|
||||
nelt.remove();
|
||||
oelt.hidden = false;
|
||||
ielt.hidden = false;
|
||||
ielt.autofocus = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// when user hits any key while typing in ielt
|
||||
function on_input_key(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
let trimmed = contents.trim();
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = trimmed.length > 0;
|
||||
if (nonempty_contents) {
|
||||
let msg_obj = ['chat', trimmed];
|
||||
let msg_str = JSON.stringify(msg_obj);
|
||||
console.log('message to server:', contents.trim());
|
||||
// query backend for result
|
||||
ws.send(msg_str);
|
||||
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// add to output
|
||||
oelt.value += '> ';
|
||||
oelt.value += trimmed;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
nelt.addEventListener('keydown', on_nick);
|
||||
ielt.addEventListener('keydown', on_input_key);
|
||||
ws.onmessage =
|
||||
function (msg_evt) {
|
||||
console.log('message from server:', msg_evt);
|
||||
let msg_str = msg_evt.data;
|
||||
let msg_obj = JSON.parse(msg_str);
|
||||
|
||||
oelt.value += msg_obj.nick;
|
||||
oelt.value += '> ';
|
||||
oelt.value += msg_obj.msg;
|
||||
oelt.value += '\n';
|
||||
};
|
||||
}
|
||||
|
||||
main();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WF Compiler Demo</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1 class="content-title">WFC Demo</h1>
|
||||
|
||||
<ul>
|
||||
<li><a href="/chat.html">Websocket Chatroom</a></li>
|
||||
<li><a href="/ws-test-echo.html">Websocket Echo Test</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="content-body">
|
||||
<textarea disabled id="wfc-output"></textarea>
|
||||
<input autofocus id="wfc-input"></input>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<input type="checkbox" checked id="auto-resize-output">Auto-resize output</input> <br>
|
||||
<input type="checkbox" checked id="auto-scroll" >Auto-scroll output to bottom</input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let MAX_OELT_HEIGHT = 300;
|
||||
|
||||
function auto_resize_output() {
|
||||
// if the user has manually resized their output, we do nothing
|
||||
if (document.getElementById('auto-resize-output').checked) {
|
||||
// resize it automagically up to 500px
|
||||
if (oelt.scrollHeight < MAX_OELT_HEIGHT) {
|
||||
oelt.style.height = String(oelt.scrollHeight) + 'px';
|
||||
}
|
||||
else {
|
||||
oelt.style.height = String(MAX_OELT_HEIGHT) + 'px';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function auto_scroll_to_bottom() {
|
||||
if (document.getElementById('auto-scroll').checked) {
|
||||
// scroll to bottom
|
||||
oelt.scrollTop = oelt.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
async function on_server_return(response) {
|
||||
console.log('on_server_return:', response);
|
||||
if (response.ok) {
|
||||
let jsbs = await response.json();
|
||||
console.log('jsbs', jsbs);
|
||||
// jsbs: {ok: true, result: string} | {ok: false, error: string}
|
||||
if (jsbs.ok) {
|
||||
// this means got a result back from server
|
||||
// put it in
|
||||
oelt.value += jsbs.result;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
else {
|
||||
// this is an error at the WFC level
|
||||
oelt.value += jsbs.error;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
}
|
||||
// this means we sent an invalid request
|
||||
else {
|
||||
oelt.value += 'HTTP ERROR, SEE BROWSER CONSOLE\n'
|
||||
}
|
||||
}
|
||||
|
||||
function on_some_bullshit(x) {
|
||||
console.log('on_some_bullshit:', x);
|
||||
oelt.value += 'NETWORK ERROR, SEE BROWSER CONSOLE\n'
|
||||
}
|
||||
|
||||
function fetch_wfcin(user_line) {
|
||||
let req_body_obj = {wfcin: user_line};
|
||||
// let req_body_str = JSON.stringify(req_body_obj, undefined, 4);
|
||||
let req_body_str = JSON.stringify(req_body_obj);
|
||||
|
||||
let req_options = {method: 'POST',
|
||||
headers: {'content-type': 'application/json'},
|
||||
body: req_body_str};
|
||||
|
||||
let response_promise = fetch('/wfcin', req_options);
|
||||
|
||||
response_promise.then(on_server_return, on_some_bullshit);
|
||||
|
||||
// this is a promise for a response
|
||||
//console.log(response_promise);
|
||||
}
|
||||
|
||||
// when user hits any key
|
||||
function on_input_key(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = contents.trim().length > 0;
|
||||
if (nonempty_contents) {
|
||||
// put in output
|
||||
// // if it's nonempty add a newline
|
||||
// if (oelt.value.length > 0) {
|
||||
// oelt.value += '\n';
|
||||
// }
|
||||
oelt.value += '> ' + contents + '\n';
|
||||
oelt.hidden = false;
|
||||
|
||||
// query backend for result
|
||||
fetch_wfcin(contents.trim());
|
||||
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// auto-resize
|
||||
auto_resize_output();
|
||||
auto_scroll_to_bottom();
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
ielt.addEventListener('keydown', on_input_key);
|
||||
}
|
||||
|
||||
main();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,100 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Chat with Websockets</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1 class="content-title">Chat with websockets</h1>
|
||||
|
||||
<div class="content-body">
|
||||
<input autofocus label="Nick" id="nick"></input>
|
||||
<textarea hidden disabled id="wfc-output"></textarea>
|
||||
<input hidden id="wfc-input"></input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let nelt = document.getElementById('nick');
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let ws = new WebSocket("/ws/chat");
|
||||
let nick = '';
|
||||
|
||||
// when user hits any key while typing in nick
|
||||
function on_nick(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = nelt.value;
|
||||
let trimmed = contents.trim();
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = trimmed.length > 0;
|
||||
if (nonempty_contents) {
|
||||
nick = trimmed;
|
||||
let msg_obj = ['nick', nick];
|
||||
let msg_str = JSON.stringify(msg_obj);
|
||||
console.log('message to server:', contents.trim());
|
||||
// query backend for result
|
||||
ws.send(msg_str);
|
||||
|
||||
// delete element from dom
|
||||
nelt.remove();
|
||||
oelt.hidden = false;
|
||||
ielt.hidden = false;
|
||||
ielt.autofocus = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// when user hits any key while typing in ielt
|
||||
function on_input_key(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
let trimmed = contents.trim();
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = trimmed.length > 0;
|
||||
if (nonempty_contents) {
|
||||
let msg_obj = ['chat', trimmed];
|
||||
let msg_str = JSON.stringify(msg_obj);
|
||||
console.log('message to server:', contents.trim());
|
||||
// query backend for result
|
||||
ws.send(msg_str);
|
||||
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// add to output
|
||||
oelt.value += '> ';
|
||||
oelt.value += trimmed;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
nelt.addEventListener('keydown', on_nick);
|
||||
ielt.addEventListener('keydown', on_input_key);
|
||||
ws.onmessage =
|
||||
function (msg_evt) {
|
||||
console.log('message from server:', msg_evt);
|
||||
let msg_str = msg_evt.data;
|
||||
let msg_obj = JSON.parse(msg_str);
|
||||
|
||||
oelt.value += msg_obj.nick;
|
||||
oelt.value += '> ';
|
||||
oelt.value += msg_obj.msg;
|
||||
oelt.value += '\n';
|
||||
};
|
||||
}
|
||||
|
||||
main();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -25,6 +25,19 @@ body {
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* titlebar */
|
||||
#titlebar {
|
||||
background: var(--lgray2);
|
||||
height: 40px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
a.tb-home{
|
||||
font-size: 30px;
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
|
||||
.content {
|
||||
max-width: 800px;
|
||||
@@ -1,95 +0,0 @@
|
||||
/* color pallette */
|
||||
* {
|
||||
--white: #f7f8fb;
|
||||
--lgray0: #f5fbfd;
|
||||
--lgray1: #daddd6;
|
||||
--lgray2: #d3d8d5;
|
||||
--mgray1: #687864;
|
||||
--dgreen1: #21341e;
|
||||
--lgreen1: #e5eef2;
|
||||
--black: #003d27;
|
||||
|
||||
--sans: Helvetica, Liberation Sans, FreeSans, Roboto, sans-serif;
|
||||
--mono: Liberation Mono, FreeMono, Roboto Mono, monospace;
|
||||
--fsdef: 12pt;
|
||||
}
|
||||
|
||||
/* body */
|
||||
body {
|
||||
background: var(--white);
|
||||
color: var(--dgray1);
|
||||
font-size: var(--fsdef);
|
||||
font-family: var(--sans);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
|
||||
.content {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
/*
|
||||
background: #ff0;
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
/* add some top padding to content */
|
||||
|
||||
.content-title {
|
||||
text-align: center;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.content-body {
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
/*
|
||||
background: #f00;
|
||||
*/
|
||||
|
||||
|
||||
padding-left: 10px;
|
||||
padding-right: 10px;
|
||||
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* element-specific styling */
|
||||
|
||||
a {
|
||||
color: var(--mgray1);
|
||||
}
|
||||
|
||||
|
||||
#wfc-input {
|
||||
font-family: var(--mono);
|
||||
font-size: var(--fsdef);
|
||||
background: var(--lgreen1);
|
||||
|
||||
width: 100%;
|
||||
|
||||
box-sizing: border-box;
|
||||
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--lgray1);
|
||||
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#wfc-output {
|
||||
background: var(--lgray0);
|
||||
font-family: var(--mono);
|
||||
font-size: var(--fsdef);
|
||||
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
|
||||
box-sizing: border-box;
|
||||
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--lgray1);
|
||||
|
||||
padding: 5px;
|
||||
}
|
||||
@@ -3,9 +3,15 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Websockets echo test</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
<link rel="stylesheet" href="/css/default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="titlebar">
|
||||
<div class="content">
|
||||
<a href="/" class="tb-home">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1 class="content-title">Websockets echo test</h1>
|
||||
|
||||
+11
-125
@@ -3,136 +3,22 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WF Compiler Demo</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
<link rel="stylesheet" href="/css/default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1 class="content-title">WFC Demo</h1>
|
||||
|
||||
<ul>
|
||||
<li><a href="/chat.html">Websocket Chatroom</a></li>
|
||||
<li><a href="/ws-test-echo.html">Websocket Echo Test</a></li>
|
||||
</ul>
|
||||
|
||||
<div class="content-body">
|
||||
<textarea disabled id="wfc-output"></textarea>
|
||||
<input autofocus id="wfc-input"></input>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<input type="checkbox" checked id="auto-resize-output">Auto-resize output</input> <br>
|
||||
<input type="checkbox" checked id="auto-scroll" >Auto-scroll output to bottom</input>
|
||||
<div id="titlebar">
|
||||
<div class="content">
|
||||
<a href="/" class="tb-home">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let MAX_OELT_HEIGHT = 300;
|
||||
<div class="content">
|
||||
<h1 class="content-title">FEWD: index</h1>
|
||||
|
||||
function auto_resize_output() {
|
||||
// if the user has manually resized their output, we do nothing
|
||||
if (document.getElementById('auto-resize-output').checked) {
|
||||
// resize it automagically up to 500px
|
||||
if (oelt.scrollHeight < MAX_OELT_HEIGHT) {
|
||||
oelt.style.height = String(oelt.scrollHeight) + 'px';
|
||||
}
|
||||
else {
|
||||
oelt.style.height = String(MAX_OELT_HEIGHT) + 'px';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function auto_scroll_to_bottom() {
|
||||
if (document.getElementById('auto-scroll').checked) {
|
||||
// scroll to bottom
|
||||
oelt.scrollTop = oelt.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
async function on_server_return(response) {
|
||||
console.log('on_server_return:', response);
|
||||
if (response.ok) {
|
||||
let jsbs = await response.json();
|
||||
console.log('jsbs', jsbs);
|
||||
// jsbs: {ok: true, result: string} | {ok: false, error: string}
|
||||
if (jsbs.ok) {
|
||||
// this means got a result back from server
|
||||
// put it in
|
||||
oelt.value += jsbs.result;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
else {
|
||||
// this is an error at the WFC level
|
||||
oelt.value += jsbs.error;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
}
|
||||
// this means we sent an invalid request
|
||||
else {
|
||||
oelt.value += 'HTTP ERROR, SEE BROWSER CONSOLE\n'
|
||||
}
|
||||
}
|
||||
|
||||
function on_some_bullshit(x) {
|
||||
console.log('on_some_bullshit:', x);
|
||||
oelt.value += 'NETWORK ERROR, SEE BROWSER CONSOLE\n'
|
||||
}
|
||||
|
||||
function fetch_wfcin(user_line) {
|
||||
let req_body_obj = {wfcin: user_line};
|
||||
// let req_body_str = JSON.stringify(req_body_obj, undefined, 4);
|
||||
let req_body_str = JSON.stringify(req_body_obj);
|
||||
|
||||
let req_options = {method: 'POST',
|
||||
headers: {'content-type': 'application/json'},
|
||||
body: req_body_str};
|
||||
|
||||
let response_promise = fetch('/wfcin', req_options);
|
||||
|
||||
response_promise.then(on_server_return, on_some_bullshit);
|
||||
|
||||
// this is a promise for a response
|
||||
//console.log(response_promise);
|
||||
}
|
||||
|
||||
// when user hits any key
|
||||
function on_input_key(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = contents.trim().length > 0;
|
||||
if (nonempty_contents) {
|
||||
// put in output
|
||||
// // if it's nonempty add a newline
|
||||
// if (oelt.value.length > 0) {
|
||||
// oelt.value += '\n';
|
||||
// }
|
||||
oelt.value += '> ' + contents + '\n';
|
||||
oelt.hidden = false;
|
||||
|
||||
// query backend for result
|
||||
fetch_wfcin(contents.trim());
|
||||
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// auto-resize
|
||||
auto_resize_output();
|
||||
auto_scroll_to_bottom();
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
ielt.addEventListener('keydown', on_input_key);
|
||||
}
|
||||
|
||||
main();
|
||||
</script>
|
||||
<ul>
|
||||
<li><a href="/echo.html">Echo</a></li>
|
||||
<li><a href="/wfc.html">WFC</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* FEWD common js lib functions
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export { auto_resize, auto_scroll_to_bottom };
|
||||
declare function auto_resize(checkbox_element: HTMLInputElement, target_element: HTMLTextAreaElement, max_height: number): void;
|
||||
declare function auto_scroll_to_bottom(checkbox_element: HTMLInputElement, target_element: HTMLTextAreaElement): void;
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* FEWD common js lib functions
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export { auto_resize, auto_scroll_to_bottom };
|
||||
function auto_resize(checkbox_element, target_element, max_height) {
|
||||
// if the user has manually resized their output, we do nothing
|
||||
if (checkbox_element.checked) {
|
||||
let target_height = target_element.scrollHeight;
|
||||
// resize it automagically up to 500px
|
||||
if (target_height < max_height)
|
||||
target_element.style.height = String(target_height) + 'px';
|
||||
else
|
||||
target_element.style.height = String(max_height) + 'px';
|
||||
}
|
||||
}
|
||||
function auto_scroll_to_bottom(checkbox_element, target_element) {
|
||||
if (checkbox_element.checked) {
|
||||
// scroll to bottom
|
||||
target_element.scrollTop = target_element.scrollHeight;
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=libfewd.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"libfewd.js","sourceRoot":"","sources":["../ts/libfewd.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACH,WAAW,EACX,qBAAqB,EACxB,CAAC;AAGF,SACA,WAAW,CACN,gBAAmC,EACnC,cAAsC,EACtC,UAAyB;IAG1B,+DAA+D;IAC/D,IAAI,gBAAgB,CAAC,OAAO,EAAE,CAAC;QAC3B,IAAI,aAAa,GAAW,cAAc,CAAC,YAAY,CAAC;QACxD,sCAAsC;QACtC,IAAI,aAAa,GAAG,UAAU;YAC1B,cAAc,CAAC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC;;YAE3D,cAAc,CAAC,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;IAChE,CAAC;AACL,CAAC;AAGD,SACA,qBAAqB,CAChB,gBAAmC,EACnC,cAAsC;IAGvC,IAAI,gBAAgB,CAAC,OAAO,EAAE,CAAC;QAC3B,mBAAmB;QACnB,cAAc,CAAC,SAAS,GAAG,cAAc,CAAC,YAAY,CAAC;IAC3D,CAAC;AACL,CAAC"}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Tetris
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export {};
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Tetris
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
main();
|
||||
async function main() {
|
||||
let ws = new WebSocket("/ws/tetris");
|
||||
let elt_tetris_state = document.getElementById('tetris-state');
|
||||
ws.onmessage =
|
||||
(e) => {
|
||||
handle_evt(e, elt_tetris_state);
|
||||
};
|
||||
}
|
||||
//-----------------------------------------------------
|
||||
// Tetris
|
||||
//-----------------------------------------------------
|
||||
/**
|
||||
* take the entire tetris state, render the html elements
|
||||
*
|
||||
* then fish out the element in the document, and replace it
|
||||
*
|
||||
* blitting basically
|
||||
*/
|
||||
async function handle_evt(e, oelt) {
|
||||
let state_str = e.data;
|
||||
oelt.value = state_str;
|
||||
}
|
||||
export {};
|
||||
//# sourceMappingURL=tetris.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"tetris.js","sourceRoot":"","sources":["../ts/tetris.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH,IAAI,EAAE,CAAC;AAEP,KAAK,UACL,IAAI;IAIA,IAAI,EAAE,GAAuC,IAAI,SAAS,CAAC,YAAY,CAAC,CAAqC;IAC7G,IAAI,gBAAgB,GAAyB,QAAQ,CAAC,cAAc,CAAC,cAAc,CAAwB,CAAE;IAE7G,EAAE,CAAC,SAAS;QACR,CAAC,CAAe,EAAE,EAAE;YAChB,UAAU,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC;QACpC,CAAC,CAAA;AACT,CAAC;AAED,uDAAuD;AACvD,SAAS;AACT,uDAAuD;AAGvD;;;;;;GAMG;AACH,KAAK,UACL,UAAU,CACL,CAAmB,EACnB,IAA0B;IAG3B,IAAI,SAAS,GAAY,CAAC,CAAC,IAAc,CAAC;IAC1C,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;AAC3B,CAAC"}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Home page ts/js
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export {};
|
||||
Vendored
+79
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* Home page ts/js
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import * as libfewd from './libfewd.js';
|
||||
//------------------------------------------------------------------
|
||||
// page element stuff
|
||||
//------------------------------------------------------------------
|
||||
main();
|
||||
function main() {
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let cb_resize = document.getElementById('auto-resize-output');
|
||||
let cb_scroll = document.getElementById('auto-scroll');
|
||||
let MAX_OELT_HEIGHT = 300;
|
||||
ielt.addEventListener('keydown', function (e) {
|
||||
on_input_key(e, ielt, oelt, cb_resize, cb_scroll, MAX_OELT_HEIGHT);
|
||||
});
|
||||
}
|
||||
// when user hits any key
|
||||
async function on_input_key(evt, ielt, oelt, cb_resize, cb_scroll, max_height) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
let trimmed = contents.trim();
|
||||
let nonempty = trimmed.length > 0;
|
||||
// if contents are nonempty
|
||||
if (nonempty) {
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
// put in output
|
||||
oelt.value += '> ' + trimmed + '\n';
|
||||
oelt.hidden = false;
|
||||
// query backend for result
|
||||
let result = await fetch_wfcin(trimmed);
|
||||
if (result.ok)
|
||||
oelt.value += result.result;
|
||||
else
|
||||
oelt.value += result.error;
|
||||
oelt.value += '\n';
|
||||
// auto-resize
|
||||
libfewd.auto_resize(cb_resize, oelt, max_height);
|
||||
libfewd.auto_scroll_to_bottom(cb_scroll, oelt);
|
||||
}
|
||||
}
|
||||
}
|
||||
function assert(condition, fail_msg) {
|
||||
if (!condition)
|
||||
throw new Error(fail_msg);
|
||||
}
|
||||
async function fetch_wfcin(user_line) {
|
||||
let req_body_obj = { wfcin: user_line };
|
||||
let req_body_str = JSON.stringify(req_body_obj);
|
||||
let req_options = { method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: req_body_str };
|
||||
// default result = somehow neither branch of code below was run(?)
|
||||
// putting this here so ts doesn't chimp out
|
||||
let result = { ok: false,
|
||||
error: 'IT DO BE LIKE THAT MISTA STANCIL' };
|
||||
try {
|
||||
let response = await fetch('/wfcin', req_options);
|
||||
if (response.ok)
|
||||
result = await response.json();
|
||||
else {
|
||||
console.log('bad http response:', response);
|
||||
result = { ok: false, error: 'BAD HTTP RESPONSE' };
|
||||
}
|
||||
}
|
||||
catch (x) {
|
||||
console.log('network error:', x);
|
||||
result = { ok: false, error: 'NETWORK ERROR' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//# sourceMappingURL=wfc.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"wfc.js","sourceRoot":"","sources":["../ts/wfc.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,OAAO,MAAM,cAAc,CAAA;AAEvC,oEAAoE;AACpE,qBAAqB;AACrB,oEAAoE;AAEpE,IAAI,EAAE,CAAC;AAEP,SACA,IAAI;IAIA,IAAI,IAAI,GAAoC,QAAQ,CAAC,cAAc,CAAC,WAAW,CAA8B,CAAK;IAClH,IAAI,IAAI,GAAoC,QAAQ,CAAC,cAAc,CAAC,YAAY,CAAgC,CAAE;IAClH,IAAI,SAAS,GAA+B,QAAQ,CAAC,cAAc,CAAC,oBAAoB,CAAqB,CAAK;IAClH,IAAI,SAAS,GAA+B,QAAQ,CAAC,cAAc,CAAC,aAAa,CAA4B,CAAK;IAClH,IAAI,eAAe,GAAyB,GAAG,CAAC;IAGhD,IAAI,CAAC,gBAAgB,CAAC,SAAS,EAC3B,UAAS,CAAgB;QACrB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,eAAe,CAAC,CAAC;IACvE,CAAC,CACJ,CAAC;AACN,CAAC;AAGD,yBAAyB;AACzB,KAAK,UACL,YAAY,CACP,GAA0B,EAC1B,IAA6B,EAC7B,IAAgC,EAChC,SAA6B,EAC7B,SAA6B,EAC7B,UAAmB;IAGpB,IAAI,GAAG,CAAC,GAAG,KAAK,OAAO,EAAE,CAAC;QACtB,yBAAyB;QACzB,GAAG,CAAC,cAAc,EAAE,CAAC;QACrB,gBAAgB;QAChB,IAAI,QAAQ,GAAa,IAAI,CAAC,KAAK,CAAC;QACpC,IAAI,OAAO,GAAc,QAAQ,CAAC,IAAI,EAAE,CAAC;QACzC,IAAI,QAAQ,GAAa,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5C,2BAA2B;QAC3B,IAAI,QAAQ,EAAE,CAAC;YACX,cAAc;YACd,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;YAEhB,gBAAgB;YAChB,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG,OAAO,GAAG,IAAI,CAAC;YACpC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;YAEpB,2BAA2B;YAC3B,IAAI,MAAM,GAAY,MAAM,WAAW,CAAC,OAAO,CAAC,CAAC;YAEjD,IAAI,MAAM,CAAC,EAAE;gBACT,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC;;gBAE5B,IAAI,CAAC,KAAK,IAAI,MAAM,CAAC,KAAK,CAAC;YAC/B,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;YAEnB,cAAc;YACd,OAAO,CAAC,WAAW,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC;YACjD,OAAO,CAAC,qBAAqB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QACnD,CAAC;IACL,CAAC;AACL,CAAC;AAaD,SACA,MAAM,CACD,SAAmB,EACnB,QAAkB;IAGnB,IAAG,CAAC,SAAS;QACT,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC;AAClC,CAAC;AAGD,KAAK,UACL,WAAW,CACN,SAAkB;IAGnB,IAAI,YAAY,GAAG,EAAC,KAAK,EAAE,SAAS,EAAC,CAAC;IACtC,IAAI,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;IAEhD,IAAI,WAAW,GAAI,EAAC,MAAM,EAAG,MAAM;QACf,OAAO,EAAE,EAAC,cAAc,EAAE,kBAAkB,EAAC;QAC7C,IAAI,EAAK,YAAY,EAAC,CAAC;IAE3C,mEAAmE;IACnE,4CAA4C;IAC5C,IAAI,MAAM,GAAW,EAAC,EAAE,EAAM,KAAK;QACb,KAAK,EAAG,kCAAkC,EAAC,CAAC;IAElE,IAAI,CAAC;QACD,IAAI,QAAQ,GAAc,MAAM,KAAK,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;QAC7D,IAAI,QAAQ,CAAC,EAAE;YACX,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAY,CAAC;aACxC,CAAC;YACF,OAAO,CAAC,GAAG,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAAC;YAC5C,MAAM,GAAG,EAAC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,mBAAmB,EAAC,CAAC;QACrD,CAAC;IACL,CAAC;IACD,OAAO,CAAM,EAAE,CAAC;QACZ,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC,CAAC,CAAC;QACjC,MAAM,GAAG,EAAC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAC,CAAC;IACjD,CAAC;IAED,OAAO,MAAM,CAAC;AAClB,CAAC"}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* FEWD common js lib functions
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
export {
|
||||
auto_resize,
|
||||
auto_scroll_to_bottom
|
||||
};
|
||||
|
||||
|
||||
function
|
||||
auto_resize
|
||||
(checkbox_element : HTMLInputElement,
|
||||
target_element : HTMLTextAreaElement,
|
||||
max_height : number)
|
||||
: void
|
||||
{
|
||||
// if the user has manually resized their output, we do nothing
|
||||
if (checkbox_element.checked) {
|
||||
let target_height: number = target_element.scrollHeight;
|
||||
// resize it automagically up to 500px
|
||||
if (target_height < max_height)
|
||||
target_element.style.height = String(target_height) + 'px';
|
||||
else
|
||||
target_element.style.height = String(max_height) + 'px';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function
|
||||
auto_scroll_to_bottom
|
||||
(checkbox_element : HTMLInputElement,
|
||||
target_element : HTMLTextAreaElement)
|
||||
: void
|
||||
{
|
||||
if (checkbox_element.checked) {
|
||||
// scroll to bottom
|
||||
target_element.scrollTop = target_element.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Tetris
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
export {
|
||||
|
||||
};
|
||||
|
||||
import * as libfewd from './libfewd.js';
|
||||
|
||||
main();
|
||||
|
||||
async function
|
||||
main
|
||||
()
|
||||
: Promise<void>
|
||||
{
|
||||
let ws : WebSocket = new WebSocket("/ws/tetris") ;
|
||||
let elt_tetris_state : HTMLTextAreaElement = document.getElementById('tetris-state') as HTMLTextAreaElement ;
|
||||
|
||||
ws.onmessage =
|
||||
(e: MessageEvent) => {
|
||||
handle_evt(e, elt_tetris_state);
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------------------------
|
||||
// Tetris
|
||||
//-----------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
* take the entire tetris state, render the html elements
|
||||
*
|
||||
* then fish out the element in the document, and replace it
|
||||
*
|
||||
* blitting basically
|
||||
*/
|
||||
async function
|
||||
handle_evt
|
||||
(e : MessageEvent,
|
||||
oelt : HTMLTextAreaElement)
|
||||
: Promise<void>
|
||||
{
|
||||
let state_str : string = e.data as string;
|
||||
oelt.value = state_str;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Home page ts/js
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import * as libfewd from './libfewd.js'
|
||||
|
||||
//------------------------------------------------------------------
|
||||
// page element stuff
|
||||
//------------------------------------------------------------------
|
||||
|
||||
main();
|
||||
|
||||
function
|
||||
main
|
||||
()
|
||||
: void
|
||||
{
|
||||
let ielt : HTMLInputElement = document.getElementById('wfc-input') as HTMLInputElement ;
|
||||
let oelt : HTMLTextAreaElement = document.getElementById('wfc-output') as HTMLTextAreaElement ;
|
||||
let cb_resize : HTMLInputElement = document.getElementById('auto-resize-output') as HTMLInputElement ;
|
||||
let cb_scroll : HTMLInputElement = document.getElementById('auto-scroll') as HTMLInputElement ;
|
||||
let MAX_OELT_HEIGHT : number = 300;
|
||||
|
||||
|
||||
ielt.addEventListener('keydown',
|
||||
function(e: KeyboardEvent) {
|
||||
on_input_key(e, ielt, oelt, cb_resize, cb_scroll, MAX_OELT_HEIGHT);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// when user hits any key
|
||||
async function
|
||||
on_input_key
|
||||
(evt : KeyboardEvent,
|
||||
ielt : HTMLInputElement,
|
||||
oelt : HTMLTextAreaElement,
|
||||
cb_resize : HTMLInputElement,
|
||||
cb_scroll : HTMLInputElement,
|
||||
max_height : number)
|
||||
: Promise<void>
|
||||
{
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents : string = ielt.value;
|
||||
let trimmed : string = contents.trim();
|
||||
let nonempty : boolean = trimmed.length > 0;
|
||||
// if contents are nonempty
|
||||
if (nonempty) {
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// put in output
|
||||
oelt.value += '> ' + trimmed + '\n';
|
||||
oelt.hidden = false;
|
||||
|
||||
// query backend for result
|
||||
let result : wfcout = await fetch_wfcin(trimmed);
|
||||
|
||||
if (result.ok)
|
||||
oelt.value += result.result;
|
||||
else
|
||||
oelt.value += result.error;
|
||||
oelt.value += '\n';
|
||||
|
||||
// auto-resize
|
||||
libfewd.auto_resize(cb_resize, oelt, max_height);
|
||||
libfewd.auto_scroll_to_bottom(cb_scroll, oelt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------
|
||||
// wfc api
|
||||
//------------------------------------------------------------------
|
||||
|
||||
type ok_err<t> = {ok: true, result: t}
|
||||
| {ok: false, error: string};
|
||||
|
||||
type wfcin = {wfcin: string};
|
||||
type wfcout = ok_err<string>;
|
||||
|
||||
function
|
||||
assert
|
||||
(condition : boolean,
|
||||
fail_msg : string)
|
||||
: void
|
||||
{
|
||||
if(!condition)
|
||||
throw new Error(fail_msg);
|
||||
}
|
||||
|
||||
|
||||
async function
|
||||
fetch_wfcin
|
||||
(user_line : string)
|
||||
: Promise<wfcout>
|
||||
{
|
||||
let req_body_obj = {wfcin: user_line};
|
||||
let req_body_str = JSON.stringify(req_body_obj);
|
||||
|
||||
let req_options = {method: 'POST',
|
||||
headers: {'content-type': 'application/json'},
|
||||
body: req_body_str};
|
||||
|
||||
// default result = somehow neither branch of code below was run(?)
|
||||
// putting this here so ts doesn't chimp out
|
||||
let result: wfcout = {ok : false,
|
||||
error : 'IT DO BE LIKE THAT MISTA STANCIL'};
|
||||
|
||||
try {
|
||||
let response : Response = await fetch('/wfcin', req_options);
|
||||
if (response.ok)
|
||||
result = await response.json() as wfcout;
|
||||
else {
|
||||
console.log('bad http response:', response);
|
||||
result = {ok: false, error: 'BAD HTTP RESPONSE'};
|
||||
}
|
||||
}
|
||||
catch (x: any) {
|
||||
console.log('network error:', x);
|
||||
result = {ok: false, error: 'NETWORK ERROR'};
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{"compilerOptions" : {"target" : "es2022",
|
||||
"strict" : true,
|
||||
"esModuleInterop" : true,
|
||||
"skipLibCheck" : true,
|
||||
"forceConsistentCasingInFileNames" : true,
|
||||
"noImplicitAny" : true,
|
||||
"strictNullChecks" : true,
|
||||
"strictPropertyInitialization" : true,
|
||||
"sourceMap" : true,
|
||||
"outDir" : "dist",
|
||||
"declaration" : true},
|
||||
"$schema" : "https://json.schemastore.org/tsconfig",
|
||||
"display" : "Recommended",
|
||||
"include" : ["ts/**/*"],
|
||||
"exclude" : [],
|
||||
"composite" : true}
|
||||
@@ -1,56 +0,0 @@
|
||||
/* header */
|
||||
div#header {
|
||||
background: var(--lgray2);
|
||||
height: 50px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
img#header-logo {
|
||||
height: 40px;
|
||||
margin-top: 5px;
|
||||
margin-bottom: 5px;
|
||||
margin-left: 5px;
|
||||
}
|
||||
|
||||
|
||||
.main {
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.content-diagram {
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
padding: 0 auto;
|
||||
}
|
||||
|
||||
|
||||
/* Pandoc makes some wacky choices with how it lays out code blocks
|
||||
*
|
||||
* this means all <code> blocks that do not have a <pre> block as an ancestor
|
||||
*
|
||||
* ie the `inline code`
|
||||
*/
|
||||
code:not(pre *) {
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--lgray1);
|
||||
padding-left: 3px;
|
||||
padding-right: 3px;
|
||||
padding-top: 1px;
|
||||
padding-bottom: 1px;
|
||||
background: var(--lgreen1);
|
||||
}
|
||||
|
||||
/* this is specifically for ```fenced blocks``` */
|
||||
pre {
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--lgray1);
|
||||
padding: 5px;
|
||||
background: var(--lgreen1);
|
||||
overflow: scroll;
|
||||
}
|
||||
|
||||
/* All `unfenced` or ```fenced``` blocks */
|
||||
code {
|
||||
font-family: Liberation Mono, Roboto Mono, monospace;
|
||||
color: var(--dgreen1);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>FEWD: WF Compiler Demo</title>
|
||||
<link rel="stylesheet" href="/css/default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="titlebar">
|
||||
<div class="content">
|
||||
<a href="/" class="tb-home">Home</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
<h1 class="content-title">WFC Demo</h1>
|
||||
|
||||
<div class="content-body">
|
||||
<textarea disabled id="wfc-output"></textarea>
|
||||
<input autofocus id="wfc-input"></input>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<input type="checkbox" checked id="auto-resize-output">Auto-resize output</input> <br>
|
||||
<input type="checkbox" checked id="auto-scroll" >Auto-scroll output to bottom</input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="./js/dist/wfc.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,65 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Websockets echo test</title>
|
||||
<link rel="stylesheet" href="./default.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
<h1 class="content-title">Websockets echo test</h1>
|
||||
|
||||
<div class="content-body">
|
||||
<textarea id="wfc-output"
|
||||
disabled></textarea>
|
||||
<input autofocus id="wfc-input"></input>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let ielt = document.getElementById('wfc-input');
|
||||
let oelt = document.getElementById('wfc-output');
|
||||
let ws = new WebSocket("/ws/echo");
|
||||
|
||||
// when user hits any key while typing in ielt
|
||||
function on_input_key(evt) {
|
||||
if (evt.key === 'Enter') {
|
||||
// don't do default thing
|
||||
evt.preventDefault();
|
||||
// grab contents
|
||||
let contents = ielt.value;
|
||||
let trimmed = contents.trim();
|
||||
// if contents are nonempty
|
||||
let nonempty_contents = trimmed.length > 0;
|
||||
if (nonempty_contents) {
|
||||
console.log('message to server:', contents.trim());
|
||||
// query backend for result
|
||||
ws.send(contents.trim());
|
||||
|
||||
// clear input
|
||||
ielt.value = '';
|
||||
|
||||
// add to output
|
||||
oelt.value += '> ';
|
||||
oelt.value += trimmed;
|
||||
oelt.value += '\n';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
ielt.addEventListener('keydown', on_input_key);
|
||||
ws.onmessage =
|
||||
function (msg_evt) {
|
||||
console.log('message from server:', msg_evt);
|
||||
let msg_str = msg_evt.data;
|
||||
oelt.value += '< ';
|
||||
oelt.value += msg_str;
|
||||
oelt.value += '\n';
|
||||
};
|
||||
}
|
||||
|
||||
main();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,5 +1,6 @@
|
||||
% @doc storing map #{cookie := Context}
|
||||
-module(fd_cache).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-behavior(gen_server).
|
||||
|
||||
|
||||
-262
@@ -1,262 +0,0 @@
|
||||
% @doc
|
||||
% controller for chat
|
||||
-module(fd_chat).
|
||||
-vsn("0.1.0").
|
||||
-behavior(gen_server).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-license("BSD-2-Clause-FreeBSD").
|
||||
|
||||
-export([
|
||||
join/1,
|
||||
relay/1,
|
||||
nick_available/1
|
||||
]).
|
||||
-export([start_link/0]).
|
||||
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||
code_change/3, terminate/2]).
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
|
||||
-record(o, {pid :: pid(),
|
||||
nick :: string()}).
|
||||
-type orator() :: #o{}.
|
||||
|
||||
-record(s, {orators = [] :: [orator()]}).
|
||||
|
||||
-type state() :: #s{}.
|
||||
|
||||
|
||||
|
||||
%%% Service Interface
|
||||
|
||||
-spec join(Nick) -> Result
|
||||
when Nick :: string(),
|
||||
Result :: ok
|
||||
| {error, Reason :: any()}.
|
||||
|
||||
join(Nick) ->
|
||||
gen_server:call(?MODULE, {join, Nick}).
|
||||
|
||||
|
||||
|
||||
-spec nick_available(Nick) -> Result
|
||||
when Nick :: string(),
|
||||
Result :: boolean().
|
||||
|
||||
nick_available(Nick) ->
|
||||
gen_server:call(?MODULE, {nick_available, Nick}).
|
||||
|
||||
|
||||
|
||||
-spec relay(Message) -> ok
|
||||
when Message :: string().
|
||||
|
||||
relay(Message) ->
|
||||
gen_server:cast(?MODULE, {relay, self(), Message}).
|
||||
|
||||
|
||||
%%% Startup Functions
|
||||
|
||||
|
||||
-spec start_link() -> Result
|
||||
when Result :: {ok, pid()}
|
||||
| {error, Reason :: term()}.
|
||||
%% @private
|
||||
%% This should only ever be called by fd_chat_orators (the service-level supervisor).
|
||||
|
||||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||
|
||||
|
||||
-spec init(none) -> {ok, state()}.
|
||||
%% @private
|
||||
%% Called by the supervisor process to give the process a chance to perform any
|
||||
%% preparatory work necessary for proper function.
|
||||
|
||||
init(none) ->
|
||||
ok = tell("~p Starting.", [?MODULE]),
|
||||
State = #s{},
|
||||
{ok, State}.
|
||||
|
||||
|
||||
|
||||
%%% gen_server Message Handling Callbacks
|
||||
|
||||
|
||||
-spec handle_call(Message, From, State) -> Result
|
||||
when Message :: term(),
|
||||
From :: {pid(), reference()},
|
||||
State :: state(),
|
||||
Result :: {reply, Response, NewState}
|
||||
| {noreply, State},
|
||||
Response :: term(),
|
||||
NewState :: state().
|
||||
%% @private
|
||||
%% The gen_server:handle_call/3 callback.
|
||||
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_call-3
|
||||
|
||||
handle_call({join, Nick}, {Pid, _}, State) ->
|
||||
{Reply, NewState} = do_join(Pid, Nick, State),
|
||||
{reply, Reply, NewState};
|
||||
handle_call({nick_available, Nick}, _, State = #s{orators = Orators}) ->
|
||||
Reply = is_nick_available(Nick, Orators),
|
||||
{reply, Reply, State};
|
||||
handle_call(Unexpected, From, State) ->
|
||||
ok = tell("~p Unexpected call from ~tp: ~tp~n", [?MODULE, From, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
-spec handle_cast(Message, State) -> {noreply, NewState}
|
||||
when Message :: term(),
|
||||
State :: state(),
|
||||
NewState :: state().
|
||||
%% @private
|
||||
%% The gen_server:handle_cast/2 callback.
|
||||
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_cast-2
|
||||
|
||||
handle_cast({relay, From, Message}, State = #s{orators = Orators}) ->
|
||||
do_relay(From, Message, Orators),
|
||||
{noreply, State};
|
||||
handle_cast(Unexpected, State) ->
|
||||
ok = tell("~p Unexpected cast: ~tp~n", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
-spec handle_info(Message, State) -> {noreply, NewState}
|
||||
when Message :: term(),
|
||||
State :: state(),
|
||||
NewState :: state().
|
||||
%% @private
|
||||
%% The gen_server:handle_info/2 callback.
|
||||
%% See: http://erlang.org/doc/man/gen_server.html#Module:handle_info-2
|
||||
|
||||
handle_info(Msg = {'DOWN', _Mon, process, _Pid, _Reason}, State) ->
|
||||
NewState = handle_down(Msg, State),
|
||||
{noreply, NewState};
|
||||
handle_info(Unexpected, State) ->
|
||||
ok = tell("~p Unexpected info: ~tp~n", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
|
||||
%%% OTP Service Functions
|
||||
|
||||
-spec code_change(OldVersion, State, Extra) -> Result
|
||||
when OldVersion :: {down, Version} | Version,
|
||||
Version :: term(),
|
||||
State :: state(),
|
||||
Extra :: term(),
|
||||
Result :: {ok, NewState}
|
||||
| {error, Reason :: term()},
|
||||
NewState :: state().
|
||||
%% @private
|
||||
%% The gen_server:code_change/3 callback.
|
||||
%% See: http://erlang.org/doc/man/gen_server.html#Module:code_change-3
|
||||
|
||||
code_change(_, State, _) ->
|
||||
{ok, State}.
|
||||
|
||||
|
||||
-spec terminate(Reason, State) -> no_return()
|
||||
when Reason :: normal
|
||||
| shutdown
|
||||
| {shutdown, term()}
|
||||
| term(),
|
||||
State :: state().
|
||||
%% @private
|
||||
%% The gen_server:terminate/2 callback.
|
||||
%% See: http://erlang.org/doc/man/gen_server.html#Module:terminate-2
|
||||
|
||||
terminate(_, _) ->
|
||||
ok.
|
||||
|
||||
|
||||
%%% internals
|
||||
|
||||
-spec do_join(Pid, Nick, State) -> {Reply, NewState}
|
||||
when Pid :: pid(),
|
||||
Nick :: string(),
|
||||
Reply :: ok | {error, Reason :: any()},
|
||||
NewState :: State.
|
||||
|
||||
do_join(Pid, Nick, State = #s{orators = Orators}) ->
|
||||
case ensure_can_join(Pid, Nick, Orators) of
|
||||
ok -> do_join2(Pid, Nick, State);
|
||||
Error -> {Error, State}
|
||||
end.
|
||||
|
||||
|
||||
do_join2(Pid, Nick, State = #s{orators = Orators}) ->
|
||||
_Monitor = erlang:monitor(process, Pid),
|
||||
NewOrator = #o{pid = Pid, nick = Nick},
|
||||
NewOrators = [NewOrator | Orators],
|
||||
NewState = State#s{orators = NewOrators},
|
||||
{ok, NewState}.
|
||||
|
||||
|
||||
-spec ensure_can_join(Pid, Nick, Orators) -> Result
|
||||
when Pid :: pid(),
|
||||
Nick :: string(),
|
||||
Orators :: [orator()],
|
||||
Result :: ok
|
||||
| {error, Reason},
|
||||
Reason :: any().
|
||||
% @private
|
||||
% ensures both Pid and Nick are unique
|
||||
|
||||
ensure_can_join(Pid, _ , [#o{pid = Pid} | _ ]) -> {error, already_joined};
|
||||
ensure_can_join(_ , Nick, [#o{nick = Nick} | _ ]) -> {error, {nick_taken, Nick}};
|
||||
ensure_can_join(Pid, Nick, [_ | Rest]) -> ensure_can_join(Pid, Nick, Rest);
|
||||
ensure_can_join(_ , _ , [] ) -> ok.
|
||||
|
||||
|
||||
-spec is_nick_available(Nick, Orators) -> boolean()
|
||||
when Nick :: string(),
|
||||
Orators :: [orator()].
|
||||
|
||||
is_nick_available(Nick, [#o{nick = Nick} | _ ]) -> false;
|
||||
is_nick_available(Nick, [_ | Rest]) -> is_nick_available(Nick, Rest);
|
||||
is_nick_available(_ , [] ) -> true.
|
||||
|
||||
|
||||
|
||||
-spec handle_down(Msg, State) -> NewState
|
||||
when Msg :: {'DOWN', Mon, process, Pid, Reason},
|
||||
Mon :: erlang:monitor(),
|
||||
Pid :: pid(),
|
||||
Reason :: any(),
|
||||
State :: state(),
|
||||
NewState :: State.
|
||||
|
||||
handle_down(Msg = {'DOWN', _, process, Pid, _}, State = #s{orators = Orators}) ->
|
||||
NewOrators = hdn(Msg, Pid, Orators, []),
|
||||
NewState = State#s{orators = NewOrators},
|
||||
NewState.
|
||||
|
||||
% encountered item, removing
|
||||
hdn(_, Pid, [#o{pid = Pid} | Rest], Acc) -> Rest ++ Acc;
|
||||
hdn(Msg, Pid, [Skip | Rest], Acc) -> hdn(Msg, Pid, Rest, [Skip | Acc]);
|
||||
hdn(Msg, _, [] , Acc) ->
|
||||
log("~tp: Unexpected message: ~tp", [?MODULE, Msg]),
|
||||
Acc.
|
||||
|
||||
|
||||
do_relay(Pid, Message, Orators) ->
|
||||
case lists:keyfind(Pid, #o.pid, Orators) of
|
||||
#o{nick = Nick} ->
|
||||
do_relay2(Nick, Message, Orators);
|
||||
false ->
|
||||
tell("~tp: Message received from outsider ~tp: ~tp", [?MODULE, Pid, Message]),
|
||||
error
|
||||
end.
|
||||
|
||||
% skip
|
||||
do_relay2(Nick, Msg, [#o{nick = Nick} | Rest]) ->
|
||||
do_relay2(Nick, Msg, Rest);
|
||||
do_relay2(Nick, Msg, [#o{pid = Pid} | Rest]) ->
|
||||
Pid ! {chat, {relay, Nick, Msg}},
|
||||
do_relay2(Nick, Msg, Rest);
|
||||
do_relay2(_, _, []) ->
|
||||
ok.
|
||||
@@ -0,0 +1,39 @@
|
||||
-module(fd_httpd).
|
||||
-vsn("0.2.0").
|
||||
-behaviour(supervisor).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-license("BSD-2-Clause-FreeBSD").
|
||||
|
||||
-export([start_link/0]).
|
||||
-export([init/1]).
|
||||
|
||||
|
||||
-spec start_link() -> {ok, pid()}.
|
||||
%% @private
|
||||
%% This supervisor's own start function.
|
||||
|
||||
start_link() ->
|
||||
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
|
||||
|
||||
|
||||
-spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
|
||||
%% @private
|
||||
%% The OTP init/1 function.
|
||||
|
||||
init([]) ->
|
||||
RestartStrategy = {one_for_one, 1, 60},
|
||||
FileCache = {fd_httpd_sfc,
|
||||
{fd_httpd_sfc, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
worker,
|
||||
[fd_httpd_sfc]},
|
||||
Clients = {fd_httpd_clients,
|
||||
{fd_httpd_clients, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
supervisor,
|
||||
[fd_httpd_clients]},
|
||||
Children = [FileCache, Clients],
|
||||
{ok, {RestartStrategy, Children}}.
|
||||
@@ -13,8 +13,8 @@
|
||||
%%% http://erlang.org/doc/design_principles/spec_proc.html
|
||||
%%% @end
|
||||
|
||||
-module(fd_client).
|
||||
-vsn("0.1.0").
|
||||
-module(fd_httpd_client).
|
||||
-vsn("0.2.0").
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-license("BSD-2-Clause-FreeBSD").
|
||||
@@ -32,7 +32,7 @@
|
||||
|
||||
|
||||
-record(s, {socket = none :: none | gen_tcp:socket(),
|
||||
next = none :: none | binary()}).
|
||||
next = <<>> :: binary()}).
|
||||
|
||||
|
||||
%% An alias for the state record above. Aliasing state can smooth out annoyances
|
||||
@@ -52,11 +52,11 @@
|
||||
| {shutdown, term()}
|
||||
| term().
|
||||
%% @private
|
||||
%% How the fd_client_man or a prior fd_client kicks things off.
|
||||
%% This is called in the context of fd_client_man or the prior fd_client.
|
||||
%% How the fd_httpd_client_man or a prior fd_httpd_client kicks things off.
|
||||
%% This is called in the context of fd_httpd_client_man or the prior fd_httpd_client.
|
||||
|
||||
start(ListenSocket) ->
|
||||
fd_client_sup:start_acceptor(ListenSocket).
|
||||
fd_httpd_client_sup:start_acceptor(ListenSocket).
|
||||
|
||||
|
||||
-spec start_link(ListenSocket) -> Result
|
||||
@@ -67,7 +67,7 @@ start(ListenSocket) ->
|
||||
| {shutdown, term()}
|
||||
| term().
|
||||
%% @private
|
||||
%% This is called by the fd_client_sup. While start/1 is called to iniate a startup
|
||||
%% This is called by the fd_httpd_client_sup. While start/1 is called to iniate a startup
|
||||
%% (essentially requesting a new worker be started by the supervisor), this is
|
||||
%% actually called in the context of the supervisor.
|
||||
|
||||
@@ -86,7 +86,7 @@ start_link(ListenSocket) ->
|
||||
%% call to listen/3.
|
||||
|
||||
init(Parent, ListenSocket) ->
|
||||
ok = io:format("~p Listening.~n", [self()]),
|
||||
ok = tell("~p Listening.~n", [self()]),
|
||||
Debug = sys:debug_options([]),
|
||||
ok = proc_lib:init_ack(Parent, {ok, self()}),
|
||||
listen(Parent, Debug, ListenSocket).
|
||||
@@ -98,7 +98,7 @@ init(Parent, ListenSocket) ->
|
||||
ListenSocket :: gen_tcp:socket().
|
||||
%% @private
|
||||
%% This function waits for a TCP connection. The owner of the socket is still
|
||||
%% the fd_client_man (so it can still close it on a call to fd_client_man:ignore/0),
|
||||
%% the fd_httpd_client_man (so it can still close it on a call to fd_httpd_client_man:ignore/0),
|
||||
%% but the only one calling gen_tcp:accept/1 on it is this process. Closing the socket
|
||||
%% is one way a manager process can gracefully unblock child workers that are blocking
|
||||
%% on a network accept.
|
||||
@@ -110,12 +110,12 @@ listen(Parent, Debug, ListenSocket) ->
|
||||
{ok, Socket} ->
|
||||
{ok, _} = start(ListenSocket),
|
||||
{ok, Peer} = inet:peername(Socket),
|
||||
ok = io:format("~p Connection accepted from: ~p~n", [self(), Peer]),
|
||||
ok = fd_client_man:enroll(),
|
||||
ok = tell("~p Connection accepted from: ~p~n", [self(), Peer]),
|
||||
ok = fd_httpd_client_man:enroll(),
|
||||
State = #s{socket = Socket},
|
||||
loop(Parent, Debug, State);
|
||||
{error, closed} ->
|
||||
ok = io:format("~p Retiring: Listen socket closed.~n", [self()]),
|
||||
ok = tell("~p Retiring: Listen socket closed.~n", [self()]),
|
||||
exit(normal)
|
||||
end.
|
||||
|
||||
@@ -128,38 +128,31 @@ listen(Parent, Debug, ListenSocket) ->
|
||||
%% The service loop itself. This is the service state. The process blocks on receive
|
||||
%% of Erlang messages, TCP segments being received themselves as Erlang messages.
|
||||
|
||||
loop(Parent, Debug, State = #s{socket = Socket, next = Next}) ->
|
||||
loop(Parent, Debug, State = #s{socket = Socket, next = Next0}) ->
|
||||
ok = inet:setopts(Socket, [{active, once}]),
|
||||
receive
|
||||
{tcp, Socket, Message} ->
|
||||
tell("~p Next = ~p", [?LINE, Next]),
|
||||
Received =
|
||||
case Next of
|
||||
none -> Message;
|
||||
_ -> <<Next/binary, Message/binary>>
|
||||
end,
|
||||
tell("qhl_parse(Socket, ~tp)", [Received]),
|
||||
Received = <<Next0/binary, Message/binary>>,
|
||||
case qhl:parse(Socket, Received) of
|
||||
{ok, Req, NewNext} ->
|
||||
tell("qhl return: {ok, ~p, ~p}", [Req, NewNext]),
|
||||
handle_request(Socket, Req),
|
||||
NewState = State#s{next = NewNext},
|
||||
{ok, Req, Next1} ->
|
||||
Next2 = handle_request(Socket, Req, Next1),
|
||||
NewState = State#s{next = Next2},
|
||||
loop(Parent, Debug, NewState);
|
||||
Error ->
|
||||
%% should trigger bad request
|
||||
io:format("~p QHL parse error: ~tp", [?LINE, Error]),
|
||||
io:format("~p bad request:~n~ts", [?LINE, Received]),
|
||||
http_err(Socket, 400),
|
||||
tell(error, "~p QHL parse error: ~tp", [?LINE, Error]),
|
||||
tell(error, "~p bad request:~n~ts", [?LINE, Received]),
|
||||
fd_httpd_utils:http_err(Socket, 400),
|
||||
gen_tcp:shutdown(Socket, read_write),
|
||||
exit(normal)
|
||||
end;
|
||||
{tcp_closed, Socket} ->
|
||||
ok = io:format("~p Socket closed, retiring.~n", [self()]),
|
||||
ok = tell("~p Socket closed, retiring.~n", [self()]),
|
||||
exit(normal);
|
||||
{system, From, Request} ->
|
||||
sys:handle_system_msg(Request, From, Parent, ?MODULE, Debug, State);
|
||||
Unexpected ->
|
||||
ok = io:format("~p Unexpected message: ~tp", [self(), Unexpected]),
|
||||
ok = tell("~p Unexpected message: ~tp", [self(), Unexpected]),
|
||||
loop(Parent, Debug, State)
|
||||
end.
|
||||
|
||||
@@ -217,120 +210,119 @@ system_replace_state(StateFun, State) ->
|
||||
|
||||
%%% http request handling
|
||||
|
||||
handle_request(Sock, R = #request{method = M, path = P}) when M =/= undefined, P =/= undefined ->
|
||||
tell("~p ~ts", [M, P]),
|
||||
route(Sock, M, P, R).
|
||||
-spec handle_request(Sock, Request, Received) -> NewReceived
|
||||
when Sock :: gen_tcp:socket(),
|
||||
Request :: request(),
|
||||
Received :: binary(),
|
||||
NewReceived :: binary().
|
||||
|
||||
handle_request(Sock, R = #request{method = M, path = P}, Received) when M =/= undefined, P =/= undefined ->
|
||||
tell("~tp ~tp ~ts", [self(), M, P]),
|
||||
route(Sock, M, P, R, Received).
|
||||
|
||||
|
||||
route(Sock, get, Route, Request) ->
|
||||
|
||||
-spec route(Sock, Method, Route, Request, Received) -> NewReceived
|
||||
when Sock :: gen_tcp:socket(),
|
||||
Method :: get | post,
|
||||
Route :: binary(),
|
||||
Request :: request(),
|
||||
Received :: binary(),
|
||||
NewReceived :: binary().
|
||||
|
||||
route(Sock, get, Route, Request, Received) ->
|
||||
case Route of
|
||||
<<"/">> -> home(Sock);
|
||||
<<"/default.css">> -> default_css(Sock);
|
||||
<<"/chat.html">> -> chat_html(Sock);
|
||||
<<"/ws-test-echo.html">> -> ws_test_echo_html(Sock);
|
||||
<<"/ws/echo">> -> ws_echo(Sock, Request);
|
||||
_ -> http_err(Sock, 404)
|
||||
<<"/ws/echo">> -> ws_echo(Sock, Request) , Received;
|
||||
<<"/">> -> route_static(Sock, <<"/index.html">>) , Received;
|
||||
_ -> route_static(Sock, Route) , Received
|
||||
end;
|
||||
route(Sock, post, Route, Request) ->
|
||||
route(Sock, post, Route, Request, Received) ->
|
||||
case Route of
|
||||
<<"/wfcin">> -> wfcin(Sock, Request);
|
||||
_ -> http_err(Sock, 404)
|
||||
<<"/wfcin">> -> wfcin(Sock, Request) , Received;
|
||||
_ -> fd_httpd_utils:http_err(Sock, 404) , Received
|
||||
end;
|
||||
route(Sock, _, _, _) ->
|
||||
http_err(Sock, 404).
|
||||
route(Sock, _, _, _, Received) ->
|
||||
fd_httpd_utils:http_err(Sock, 404),
|
||||
Received.
|
||||
|
||||
|
||||
|
||||
-spec route_static(Socket, Route) -> ok
|
||||
when Socket :: gen_tcp:socket(),
|
||||
Route :: binary().
|
||||
|
||||
route_static(Sock, Route) ->
|
||||
respond_static(Sock, fd_httpd_sfc:query(Route)).
|
||||
|
||||
|
||||
|
||||
-spec respond_static(Sock, MaybeEty) -> ok
|
||||
when Sock :: gen_tcp:socket(),
|
||||
MaybeEty :: fd_httpd_sfc:maybe_entry().
|
||||
|
||||
respond_static(Sock, {found, Entry}) ->
|
||||
% -record(e, {fs_path :: file:filename(),
|
||||
% last_modified :: file:date_time(),
|
||||
% mime_type :: string(),
|
||||
% encoding :: encoding(),
|
||||
% contents :: binary()}).
|
||||
Headers0 =
|
||||
case fd_httpd_sfc_entry:encoding(Entry) of
|
||||
gzip -> [{"content-encoding", "gzip"}];
|
||||
none -> []
|
||||
end,
|
||||
Headers1 = [{"content-type", fd_httpd_sfc_entry:mime_type(Entry)} | Headers0],
|
||||
Response = #response{headers = Headers1,
|
||||
body = fd_httpd_sfc_entry:contents(Entry)},
|
||||
fd_httpd_utils:respond(Sock, Response);
|
||||
respond_static(Sock, not_found) ->
|
||||
fd_httpd_utils:http_err(Sock, 404).
|
||||
|
||||
|
||||
%% ------------------------------
|
||||
%% echo
|
||||
%% ------------------------------
|
||||
|
||||
ws_echo(Sock, Request) ->
|
||||
try
|
||||
ws_echo2(Sock, Request)
|
||||
catch
|
||||
X:Y:Z ->
|
||||
tell(error, "CRASH ws_echo: ~tp:~tp:~tp", [X, Y, Z]),
|
||||
http_err(Sock, 500)
|
||||
fd_httpd_utils:http_err(Sock, 500)
|
||||
end.
|
||||
|
||||
ws_echo2(Sock, Request) ->
|
||||
tell("~p: ws_echo request: ~tp", [?LINE, Request]),
|
||||
case fd_ws:handshake(Request) of
|
||||
case qhl_ws:handshake(Request) of
|
||||
{ok, Response} ->
|
||||
tell("~p: ws_echo response: ~tp", [?LINE, Response]),
|
||||
respond(Sock, Response),
|
||||
tell("~p: ws_echo: entering loop", [?LINE]),
|
||||
fd_httpd_utils:respond(Sock, Response),
|
||||
ws_echo_loop(Sock);
|
||||
Error ->
|
||||
tell("ws_echo: error: ~tp", [Error]),
|
||||
http_err(Sock, 400)
|
||||
fd_httpd_utils:http_err(Sock, 400)
|
||||
end.
|
||||
|
||||
ws_echo_loop(Sock) ->
|
||||
ws_echo_loop(Sock, [], <<>>).
|
||||
|
||||
ws_echo_loop(Sock, Frames, Received) ->
|
||||
tell("~p: ws_echo_loop: entering loop", [?LINE]),
|
||||
case fd_ws:recv(Sock, Received, 5*fd_ws:min(), Frames) of
|
||||
Result = {ok, Message, NewFrames, NewReceived} ->
|
||||
tell("~p: ws_echo_loop ok: ~tp", [?LINE, Result]),
|
||||
tell("~p ws_echo_loop(Sock, ~tp, ~tp)", [self(), Frames, Received]),
|
||||
case qhl_ws:recv(Sock, Received, 5*qhl_ws:min(), Frames) of
|
||||
{ok, Message, NewFrames, NewReceived} ->
|
||||
tell("~p echo message: ~tp", [self(), Message]),
|
||||
% send the same message back
|
||||
ok = fd_ws:send(Sock, Message),
|
||||
ok = qhl_ws:send(Sock, Message),
|
||||
ws_echo_loop(Sock, NewFrames, NewReceived);
|
||||
Error ->
|
||||
tell("ws_echo_loop: error: ~tp", [Error]),
|
||||
fd_ws:send(Sock, {close, <<>>}),
|
||||
tell(error, "ws_echo_loop: error: ~tp", [Error]),
|
||||
qhl_ws:send(Sock, {close, <<>>}),
|
||||
error(Error)
|
||||
end.
|
||||
|
||||
|
||||
home(Sock) ->
|
||||
%% fixme: cache
|
||||
Path_IH = filename:join([zx:get_home(), "priv", "index.html"]),
|
||||
case file:read_file(Path_IH) of
|
||||
{ok, Body} ->
|
||||
Resp = #response{headers = [{"content-type", "text/html"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp);
|
||||
Error ->
|
||||
tell("error: ~p~n", [self(), Error]),
|
||||
http_err(Sock, 500)
|
||||
end.
|
||||
|
||||
default_css(Sock) ->
|
||||
%% fixme: cache
|
||||
Path_IH = filename:join([zx:get_home(), "priv", "default.css"]),
|
||||
case file:read_file(Path_IH) of
|
||||
{ok, Body} ->
|
||||
Resp = #response{headers = [{"content-type", "text/css"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp);
|
||||
Error ->
|
||||
io:format("~p error: ~p~n", [self(), Error]),
|
||||
http_err(Sock, 500)
|
||||
end.
|
||||
|
||||
ws_test_echo_html(Sock) ->
|
||||
%% fixme: cache
|
||||
Path_IH = filename:join([zx:get_home(), "priv", "ws-test-echo.html"]),
|
||||
case file:read_file(Path_IH) of
|
||||
{ok, Body} ->
|
||||
Resp = #response{headers = [{"content-type", "text/html"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp);
|
||||
Error ->
|
||||
io:format("~p error: ~p~n", [self(), Error]),
|
||||
http_err(Sock, 500)
|
||||
end.
|
||||
|
||||
chat_html(Sock) ->
|
||||
%% fixme: cache
|
||||
Path_IH = filename:join([zx:get_home(), "priv", "chat.html"]),
|
||||
case file:read_file(Path_IH) of
|
||||
{ok, Body} ->
|
||||
Resp = #response{headers = [{"content-type", "text/html"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp);
|
||||
Error ->
|
||||
io:format("~p error: ~p~n", [self(), Error]),
|
||||
http_err(Sock, 500)
|
||||
end.
|
||||
%% ------------------------------
|
||||
%% wfc
|
||||
%% ------------------------------
|
||||
|
||||
wfcin(Sock, #request{enctype = json,
|
||||
cookies = Cookies,
|
||||
@@ -343,17 +335,17 @@ wfcin(Sock, #request{enctype = json,
|
||||
case wfc_read:expr(Input) of
|
||||
{ok, Expr, _Rest} ->
|
||||
case wfc_eval:eval(Expr, Ctx0) of
|
||||
{ok, noop, Ctx1} -> {jsgud("<noop>"), Ctx1};
|
||||
{ok, Sentence, Ctx1} -> {jsgud(wfc_pp:sentence(Sentence)), Ctx1};
|
||||
{error, Message} -> {jsbad(Message), Ctx0}
|
||||
{ok, noop, Ctx1} -> {fd_httpd_utils:jsgud("<noop>"), Ctx1};
|
||||
{ok, Sentence, Ctx1} -> {fd_httpd_utils:jsgud(wfc_pp:sentence(Sentence)), Ctx1};
|
||||
{error, Message} -> {fd_httpd_utils:jsbad(Message), Ctx0}
|
||||
end;
|
||||
{error, Message} ->
|
||||
{jsbad(Message), Ctx0}
|
||||
{fd_httpd_utils:jsbad(Message), Ctx0}
|
||||
end
|
||||
catch
|
||||
error:E:S ->
|
||||
ErrorMessage = unicode:characters_to_list(io_lib:format("parser crashed: ~p:~p", [E, S])),
|
||||
{jsbad(ErrorMessage), Ctx0}
|
||||
{fd_httpd_utils:jsbad(ErrorMessage), Ctx0}
|
||||
end,
|
||||
% update cache with new context
|
||||
ok = fd_cache:set(Cookie, NewCtx),
|
||||
@@ -361,77 +353,30 @@ wfcin(Sock, #request{enctype = json,
|
||||
Response = #response{headers = [{"content-type", "application/json"},
|
||||
{"set-cookie", ["wfc=", Cookie]}],
|
||||
body = Body},
|
||||
respond(Sock, Response);
|
||||
fd_httpd_utils:respond(Sock, Response);
|
||||
wfcin(Sock, Request) ->
|
||||
tell("wfcin: bad request: ~tp", [Request]),
|
||||
http_err(Sock, 400).
|
||||
fd_httpd_utils:http_err(Sock, 400).
|
||||
|
||||
|
||||
|
||||
-spec ctx(Cookies) -> {Cookie, Context}
|
||||
when Cookies :: #{binary() := Cookie},
|
||||
Cookie :: binary(),
|
||||
Context :: wfc_eval_context:context().
|
||||
|
||||
ctx(#{<<"wfc">> := Cookie}) ->
|
||||
case fd_cache:query(Cookie) of
|
||||
{ok, Context} -> {Cookie, Context};
|
||||
error -> {Cookie, wfc_eval_context:default()}
|
||||
end;
|
||||
ctx(_) ->
|
||||
{new_cookie(), wfc_eval_context:default()}.
|
||||
|
||||
new_cookie() ->
|
||||
binary:encode_hex(crypto:strong_rand_bytes(8)).
|
||||
|
||||
jsgud(X) ->
|
||||
#{"ok" => true,
|
||||
"result" => X}.
|
||||
|
||||
jsbad(X) ->
|
||||
#{"ok" => false,
|
||||
"error" => X}.
|
||||
|
||||
http_err(Sock, N) ->
|
||||
Slogan = qhl:slogan(N),
|
||||
Body = ["<!doctype html>"
|
||||
"<html lang=\"en\">"
|
||||
"<head>"
|
||||
"<meta charset=\"utf-8\">"
|
||||
"<title>QHL: ", integer_to_list(N), " ", Slogan, "</title>"
|
||||
"</head>"
|
||||
"<body>"
|
||||
"<h1>"
|
||||
"QHL: ", integer_to_list(N), " ", Slogan,
|
||||
"</h1>"
|
||||
"</body>"
|
||||
"</html>"],
|
||||
Resp = #response{code = N,
|
||||
headers = [{"content/type", "text/html"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp).
|
||||
{fd_httpd_utils:new_cookie(), wfc_eval_context:default()}.
|
||||
|
||||
|
||||
respond(Sock, Response) ->
|
||||
gen_tcp:send(Sock, fmtresp(Response)).
|
||||
|
||||
|
||||
fmtresp(#response{type = page, %% no idea what {data, String} is
|
||||
version = http11,
|
||||
code = Code,
|
||||
headers = Hs,
|
||||
body = Body}) ->
|
||||
%% need byte size for binary
|
||||
Headers = add_headers(Hs, Body),
|
||||
[io_lib:format("HTTP/1.1 ~tp ~ts", [Code, qhl:slogan(Code)]), "\r\n",
|
||||
[io_lib:format("~ts: ~ts\r\n", [K, V]) || {K, V} <- Headers],
|
||||
"\r\n",
|
||||
Body].
|
||||
|
||||
|
||||
%% body needed just for size
|
||||
add_headers(Hs, Body) ->
|
||||
Defaults = default_headers(Body),
|
||||
Hs2 = proplists:to_map(Hs),
|
||||
proplists:from_map(maps:merge(Defaults, Hs2)).
|
||||
|
||||
|
||||
default_headers(Body) ->
|
||||
BodySize = byte_size(iolist_to_binary(Body)),
|
||||
#{"Server" => "fewd 0.1.0",
|
||||
"Date" => qhl:ridiculous_web_date(),
|
||||
"Content-Length" => io_lib:format("~p", [BodySize])}.
|
||||
@@ -9,8 +9,8 @@
|
||||
%%% OTP should take care of for us.
|
||||
%%% @end
|
||||
|
||||
-module(fd_client_man).
|
||||
-vsn("0.1.0").
|
||||
-module(fd_httpd_client_man).
|
||||
-vsn("0.2.0").
|
||||
-behavior(gen_server).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
@@ -23,6 +23,8 @@
|
||||
code_change/3, terminate/2]).
|
||||
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
%%% Type and Record Definitions
|
||||
|
||||
|
||||
@@ -92,7 +94,7 @@ echo(Message) ->
|
||||
when Result :: {ok, pid()}
|
||||
| {error, Reason :: term()}.
|
||||
%% @private
|
||||
%% This should only ever be called by fd_clients (the service-level supervisor).
|
||||
%% This should only ever be called by fd_httpd_clients (the service-level supervisor).
|
||||
|
||||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||
@@ -104,8 +106,9 @@ start_link() ->
|
||||
%% preparatory work necessary for proper function.
|
||||
|
||||
init(none) ->
|
||||
ok = io:format("Starting.~n"),
|
||||
ok = tell("Starting fd_httpd_client_man."),
|
||||
State = #s{},
|
||||
ok = tell("fd_httpd_client_man init state: ~tp", [State]),
|
||||
{ok, State}.
|
||||
|
||||
|
||||
@@ -130,7 +133,7 @@ handle_call({listen, PortNum}, _, State) ->
|
||||
{Response, NewState} = do_listen(PortNum, State),
|
||||
{reply, Response, NewState};
|
||||
handle_call(Unexpected, From, State) ->
|
||||
ok = io:format("~p Unexpected call from ~tp: ~tp~n", [self(), From, Unexpected]),
|
||||
ok = tell("~p Unexpected call from ~tp: ~tp~n", [self(), From, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
@@ -152,7 +155,7 @@ handle_cast(ignore, State) ->
|
||||
NewState = do_ignore(State),
|
||||
{noreply, NewState};
|
||||
handle_cast(Unexpected, State) ->
|
||||
ok = io:format("~p Unexpected cast: ~tp~n", [self(), Unexpected]),
|
||||
ok = tell("~p Unexpected cast: ~tp~n", [self(), Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
@@ -168,7 +171,7 @@ handle_info({'DOWN', Mon, process, Pid, Reason}, State) ->
|
||||
NewState = handle_down(Mon, Pid, Reason, State),
|
||||
{noreply, NewState};
|
||||
handle_info(Unexpected, State) ->
|
||||
ok = io:format("~p Unexpected info: ~tp~n", [self(), Unexpected]),
|
||||
ok = tell("~p Unexpected info: ~tp~n", [self(), Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
@@ -225,10 +228,10 @@ do_listen(PortNum, State = #s{port_num = none}) ->
|
||||
{keepalive, true},
|
||||
{reuseaddr, true}],
|
||||
{ok, Listener} = gen_tcp:listen(PortNum, SocketOptions),
|
||||
{ok, _} = fd_client:start(Listener),
|
||||
{ok, _} = fd_httpd_client:start(Listener),
|
||||
{ok, State#s{port_num = PortNum, listener = Listener}};
|
||||
do_listen(_, State = #s{port_num = PortNum}) ->
|
||||
ok = io:format("~p Already listening on ~p~n", [self(), PortNum]),
|
||||
ok = tell("~p Already listening on ~p~n", [self(), PortNum]),
|
||||
{{error, {listening, PortNum}}, State}.
|
||||
|
||||
|
||||
@@ -254,7 +257,7 @@ do_enroll(Pid, State = #s{clients = Clients}) ->
|
||||
case lists:member(Pid, Clients) of
|
||||
false ->
|
||||
Mon = monitor(process, Pid),
|
||||
ok = io:format("Monitoring ~tp @ ~tp~n", [Pid, Mon]),
|
||||
ok = tell("Monitoring ~tp @ ~tp~n", [Pid, Mon]),
|
||||
State#s{clients = [Pid | Clients]};
|
||||
true ->
|
||||
State
|
||||
@@ -292,6 +295,6 @@ handle_down(Mon, Pid, Reason, State = #s{clients = Clients}) ->
|
||||
State#s{clients = NewClients};
|
||||
false ->
|
||||
Unexpected = {'DOWN', Mon, process, Pid, Reason},
|
||||
ok = io:format("~p Unexpected info: ~tp~n", [self(), Unexpected]),
|
||||
ok = tell("~p Unexpected info: ~tp~n", [self(), Unexpected]),
|
||||
State
|
||||
end.
|
||||
@@ -2,8 +2,8 @@
|
||||
%%% front end web development lab Client Supervisor
|
||||
%%%
|
||||
%%% This process supervises the client socket handlers themselves. It is a peer of the
|
||||
%%% fd_client_man (the manager interface to this network service component),
|
||||
%%% and a child of the supervisor named fd_clients.
|
||||
%%% fd_httpd_client_man (the manager interface to this network service component),
|
||||
%%% and a child of the supervisor named fd_httpd_clients.
|
||||
%%%
|
||||
%%% Because we don't know (or care) how many client connections the server may end up
|
||||
%%% handling this is a simple_one_for_one supervisor which can spawn and manage as
|
||||
@@ -13,8 +13,8 @@
|
||||
%%% http://erlang.org/doc/design_principles/sup_princ.html#id79244
|
||||
%%% @end
|
||||
|
||||
-module(fd_client_sup).
|
||||
-vsn("0.1.0").
|
||||
-module(fd_httpd_client_sup).
|
||||
-vsn("0.2.0").
|
||||
-behaviour(supervisor).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
@@ -35,9 +35,9 @@
|
||||
| {shutdown, term()}
|
||||
| term().
|
||||
%% @private
|
||||
%% Spawns the first listener at the request of the fd_client_man when
|
||||
%% Spawns the first listener at the request of the fd_httpd_client_man when
|
||||
%% fewd:listen/1 is called, or the next listener at the request of the
|
||||
%% currently listening fd_client when a connection is made.
|
||||
%% currently listening fd_httpd_client when a connection is made.
|
||||
%%
|
||||
%% Error conditions, supervision strategies and other important issues are
|
||||
%% explained in the supervisor module docs:
|
||||
@@ -61,10 +61,10 @@ start_link() ->
|
||||
|
||||
init(none) ->
|
||||
RestartStrategy = {simple_one_for_one, 1, 60},
|
||||
Client = {fd_client,
|
||||
{fd_client, start_link, []},
|
||||
Client = {fd_httpd_client,
|
||||
{fd_httpd_client, start_link, []},
|
||||
temporary,
|
||||
brutal_kill,
|
||||
worker,
|
||||
[fd_client]},
|
||||
[fd_httpd_client]},
|
||||
{ok, {RestartStrategy, [Client]}}.
|
||||
@@ -8,8 +8,8 @@
|
||||
%%% See: http://erlang.org/doc/apps/kernel/application.html
|
||||
%%% @end
|
||||
|
||||
-module(fd_clients).
|
||||
-vsn("0.1.0").
|
||||
-module(fd_httpd_clients).
|
||||
-vsn("0.2.0").
|
||||
-behavior(supervisor).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
@@ -32,17 +32,17 @@ start_link() ->
|
||||
|
||||
init(none) ->
|
||||
RestartStrategy = {rest_for_one, 1, 60},
|
||||
ClientMan = {fd_client_man,
|
||||
{fd_client_man, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
worker,
|
||||
[fd_client_man]},
|
||||
ClientSup = {fd_client_sup,
|
||||
{fd_client_sup, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
supervisor,
|
||||
[fd_client_sup]},
|
||||
Children = [ClientSup, ClientMan],
|
||||
HttpClientMan = {fd_httpd_client_man,
|
||||
{fd_httpd_client_man, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
worker,
|
||||
[fd_httpd_client_man]},
|
||||
HttpClientSup = {fd_httpd_client_sup,
|
||||
{fd_httpd_client_sup, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
supervisor,
|
||||
[fd_httpd_client_sup]},
|
||||
Children = [HttpClientSup, HttpClientMan],
|
||||
{ok, {RestartStrategy, Children}}.
|
||||
@@ -0,0 +1,112 @@
|
||||
% @doc static file cache
|
||||
-module(fd_httpd_sfc).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-behavior(gen_server).
|
||||
|
||||
-export_type([
|
||||
entry/0,
|
||||
maybe_entry/0
|
||||
]).
|
||||
|
||||
-export([
|
||||
%% caller context
|
||||
base_path/0,
|
||||
renew/0, query/1,
|
||||
start_link/0,
|
||||
|
||||
%% process context
|
||||
init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||
code_change/3, terminate/2
|
||||
]).
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
-type entry() :: fd_httpd_sfc_entry:entry().
|
||||
-type maybe_entry() :: {found, fd_httpd_sfc_entry:entry()} | not_found.
|
||||
|
||||
|
||||
-record(s, {base_path = base_path() :: file:filename(),
|
||||
cache = fd_httpd_sfc_cache:new(base_path()) :: fd_httpd_sfc_cache:cache(),
|
||||
auto_renew = 0_500 :: pos_integer()}).
|
||||
%-type state() :: #s{}.
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% caller context
|
||||
%%-----------------------------------------------------------------------------
|
||||
|
||||
-spec base_path() -> file:filename().
|
||||
base_path() ->
|
||||
filename:join([zx:get_home(), "priv", "static"]).
|
||||
|
||||
-spec renew() -> ok.
|
||||
renew() ->
|
||||
gen_server:cast(?MODULE, renew).
|
||||
|
||||
|
||||
-spec query(HttpPath) -> MaybeEntry
|
||||
when HttpPath :: binary(),
|
||||
MaybeEntry :: maybe_entry().
|
||||
query(Path) ->
|
||||
gen_server:call(?MODULE, {query, Path}).
|
||||
|
||||
|
||||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% process context below this line
|
||||
%%-----------------------------------------------------------------------------
|
||||
|
||||
%% gen_server callbacks
|
||||
|
||||
init(none) ->
|
||||
tell("starting fd_httpd_sfc"),
|
||||
InitState = #s{},
|
||||
erlang:send_after(InitState#s.auto_renew, self(), auto_renew),
|
||||
{ok, InitState}.
|
||||
|
||||
|
||||
handle_call({query, Path}, _, State = #s{cache = Cache}) ->
|
||||
Reply = fd_httpd_sfc_cache:query(Path, Cache),
|
||||
{reply, Reply, State};
|
||||
handle_call(Unexpected, From, State) ->
|
||||
tell("~tp: unexpected call from ~tp: ~tp", [?MODULE, Unexpected, From]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_cast(renew, State) ->
|
||||
NewState = i_renew(State),
|
||||
{noreply, NewState};
|
||||
handle_cast(Unexpected, State) ->
|
||||
tell("~tp: unexpected cast: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_info(auto_renew, State = #s{auto_renew = MS}) ->
|
||||
log(info, "~tp: auto_renew", [?MODULE]),
|
||||
erlang:send_after(MS, self(), auto_renew),
|
||||
NewState = i_renew(State),
|
||||
{noreply, NewState};
|
||||
handle_info(Unexpected, State) ->
|
||||
tell("~tp: unexpected info: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
code_change(_, State, _) ->
|
||||
{ok, State}.
|
||||
|
||||
terminate(_, _) ->
|
||||
ok.
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% internals
|
||||
%%-----------------------------------------------------------------------------
|
||||
|
||||
i_renew(State = #s{base_path = BasePath}) ->
|
||||
NewCache = fd_httpd_sfc_cache:new(BasePath),
|
||||
NewState = State#s{cache = NewCache},
|
||||
NewState.
|
||||
@@ -0,0 +1,82 @@
|
||||
% @doc
|
||||
% cache data management
|
||||
-module(fd_httpd_sfc_cache).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
cache/0
|
||||
]).
|
||||
|
||||
-export([
|
||||
query/2,
|
||||
new/0, new/1
|
||||
]).
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
-type cache() :: #{HttpPath :: binary() := Entry :: fd_httpd_sfc_entry:entry()}.
|
||||
|
||||
|
||||
-spec query(HttpPath, Cache) -> Result
|
||||
when HttpPath :: binary(),
|
||||
Cache :: cache(),
|
||||
Result :: {found, Entry}
|
||||
| not_found,
|
||||
Entry :: fd_httpd_sfc_entry:entry().
|
||||
|
||||
query(HttpPath, Cache) ->
|
||||
case maps:find(HttpPath, Cache) of
|
||||
{ok, Entry} -> {found, Entry};
|
||||
error -> not_found
|
||||
end.
|
||||
|
||||
|
||||
-spec new() -> cache().
|
||||
new() -> #{}.
|
||||
|
||||
|
||||
-spec new(BasePath) -> cache()
|
||||
when BasePath :: file:filename().
|
||||
% @doc
|
||||
% if you give a file path it just takes the parent dir
|
||||
%
|
||||
% recursively crawls through file tree and picks
|
||||
%
|
||||
% IO errors will be logged but will result in cache misses
|
||||
|
||||
new(BasePath) ->
|
||||
case filelib:is_file(BasePath) of
|
||||
true -> new2(BasePath);
|
||||
false ->
|
||||
tell("~p:new(~p): no such file or directory, returning empty cache", [?MODULE, BasePath]),
|
||||
#{}
|
||||
end.
|
||||
|
||||
new2(BasePath) ->
|
||||
BaseDir =
|
||||
case filelib:is_dir(BasePath) of
|
||||
true -> filename:absname(BasePath);
|
||||
false -> filename:absname(filename:dirname(BasePath))
|
||||
end,
|
||||
BBaseDir = unicode:characters_to_binary(BaseDir),
|
||||
HandlePath =
|
||||
fun(AbsPath, AccCache) ->
|
||||
BAbsPath = unicode:characters_to_binary(AbsPath),
|
||||
HttpPath = remove_prefix(BBaseDir, BAbsPath),
|
||||
NewCache =
|
||||
case fd_httpd_sfc_entry:new(AbsPath) of
|
||||
{found, Entry} -> maps:put(HttpPath, Entry, AccCache);
|
||||
not_found -> AccCache
|
||||
end,
|
||||
NewCache
|
||||
end,
|
||||
filelib:fold_files(_dir = BaseDir,
|
||||
_match = ".+",
|
||||
_recursive = true,
|
||||
_fun = HandlePath,
|
||||
_init_acc = #{}).
|
||||
|
||||
remove_prefix(Prefix, From) ->
|
||||
Size = byte_size(Prefix),
|
||||
<<Prefix:Size/bytes, Rest/bytes>> = From,
|
||||
Rest.
|
||||
@@ -0,0 +1,100 @@
|
||||
% @doc non-servery functions for static file caching
|
||||
%
|
||||
% this spams the filesystem, so it's not "pure" code
|
||||
-module(fd_httpd_sfc_entry).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
encoding/0,
|
||||
entry/0
|
||||
]).
|
||||
|
||||
-export([
|
||||
%% constructor
|
||||
new/1,
|
||||
%% accessors
|
||||
fs_path/1, last_modified/1, mime_type/1, encoding/1, contents/1
|
||||
]).
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
%% types
|
||||
|
||||
% id = not compressed
|
||||
-type encoding() :: none | gzip.
|
||||
|
||||
-record(e, {fs_path :: file:filename(),
|
||||
last_modified :: file:date_time(),
|
||||
mime_type :: string(),
|
||||
encoding :: encoding(),
|
||||
contents :: binary()}).
|
||||
|
||||
-opaque entry() :: #e{}.
|
||||
|
||||
%% accessors
|
||||
|
||||
fs_path(#e{fs_path = X}) -> X.
|
||||
last_modified(#e{last_modified = X}) -> X.
|
||||
mime_type(#e{mime_type = X}) -> X.
|
||||
encoding(#e{encoding = X}) -> X.
|
||||
contents(#e{contents = X}) -> X.
|
||||
|
||||
%% API
|
||||
|
||||
-spec new(Path) -> Result
|
||||
when Path :: file:filename(),
|
||||
Result :: {found, entry()}
|
||||
| not_found.
|
||||
% @doc
|
||||
% absolute file path stored in resulting record
|
||||
%
|
||||
% returns not_found if ANY I/O error occurs during the process. will be logged
|
||||
|
||||
new(Path) ->
|
||||
log(info, "~tp:new(~tp)", [?MODULE, Path]),
|
||||
case file:read_file(Path) of
|
||||
{ok, Binary} ->
|
||||
{found, new2(Path, Binary)};
|
||||
Error ->
|
||||
tell("~tp:new(~tp): file read error: ~tp", [?MODULE, Path, Error]),
|
||||
not_found
|
||||
end.
|
||||
|
||||
%% can assume file exists
|
||||
new2(FsPath, FileBytes) ->
|
||||
LastModified = filelib:last_modified(FsPath),
|
||||
{Encoding, MimeType} = mimetype_compress(FsPath),
|
||||
Contents =
|
||||
case Encoding of
|
||||
none -> FileBytes;
|
||||
gzip -> zlib:gzip(FileBytes)
|
||||
end,
|
||||
#e{fs_path = FsPath,
|
||||
last_modified = LastModified,
|
||||
mime_type = MimeType,
|
||||
encoding = Encoding,
|
||||
contents = Contents}.
|
||||
|
||||
mimetype_compress(FsPath) ->
|
||||
case string:casefold(filename:extension(FsPath)) of
|
||||
%% only including the ones i anticipate encountering
|
||||
%% plaintext formats
|
||||
".css" -> {gzip, "text/css"};
|
||||
".htm" -> {gzip, "text/html"};
|
||||
".html" -> {gzip, "text/html"};
|
||||
".js" -> {gzip, "text/javascript"};
|
||||
".json" -> {gzip, "application/json"};
|
||||
".map" -> {gzip, "application/json"};
|
||||
".md" -> {gzip, "text/markdown"};
|
||||
".ts" -> {gzip, "text/x-typescript"};
|
||||
".txt" -> {gzip, "text/plain"};
|
||||
%% binary formats
|
||||
".gif" -> {none, "image/gif"};
|
||||
".jpg" -> {none, "image/jpeg"};
|
||||
".jpeg" -> {none, "image/jpeg"};
|
||||
".mp4" -> {none, "video/mp4"};
|
||||
".png" -> {none, "image/png"};
|
||||
".webm" -> {none, "video/webm"};
|
||||
".webp" -> {none, "image/webp"};
|
||||
_ -> {none, "application/octet-stream"}
|
||||
end.
|
||||
@@ -0,0 +1,119 @@
|
||||
% @doc http utility functions
|
||||
-module(fd_httpd_utils).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export([
|
||||
new_cookie/0,
|
||||
jsgud/1, jsbad/1,
|
||||
http_err/2,
|
||||
respond/2,
|
||||
fmtresp/1
|
||||
]).
|
||||
|
||||
-include("http.hrl").
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
|
||||
-spec new_cookie() -> Cookie
|
||||
when Cookie :: binary().
|
||||
|
||||
new_cookie() ->
|
||||
binary:encode_hex(crypto:strong_rand_bytes(8)).
|
||||
|
||||
|
||||
|
||||
-spec jsgud(JSON) -> Encodable
|
||||
when JSON :: zj:value(),
|
||||
Encodable :: JSON.
|
||||
|
||||
jsgud(X) ->
|
||||
#{"ok" => true,
|
||||
"result" => X}.
|
||||
|
||||
|
||||
|
||||
-spec jsbad(JSON) -> JSBad
|
||||
when JSON :: zj:value(),
|
||||
JSBad :: zj:value().
|
||||
|
||||
jsbad(X) ->
|
||||
#{"ok" => false,
|
||||
"error" => X}.
|
||||
|
||||
|
||||
|
||||
-spec http_err(Socket, ErrorCode) -> ok
|
||||
when Socket :: gen_tcp:socket(),
|
||||
ErrorCode :: integer().
|
||||
|
||||
http_err(Sock, N) ->
|
||||
Slogan = qhl:slogan(N),
|
||||
Body = ["<!doctype html>"
|
||||
"<html lang=\"en\">"
|
||||
"<head>"
|
||||
"<meta charset=\"utf-8\">"
|
||||
"<title>QHL: ", integer_to_list(N), " ", Slogan, "</title>"
|
||||
"</head>"
|
||||
"<body>"
|
||||
"<h1>"
|
||||
"QHL: ", integer_to_list(N), " ", Slogan,
|
||||
"</h1>"
|
||||
"</body>"
|
||||
"</html>"],
|
||||
Resp = #response{code = N,
|
||||
headers = [{"content/type", "text/html"}],
|
||||
body = Body},
|
||||
respond(Sock, Resp).
|
||||
|
||||
|
||||
|
||||
-spec respond(Sock, Response) -> ok
|
||||
when Sock :: gen_tcp:socket(),
|
||||
Response :: response().
|
||||
|
||||
respond(Sock, Response = #response{code = Code}) ->
|
||||
tell("~tp ~tp ~ts", [self(), Code, qhl:slogan(Code)]),
|
||||
gen_tcp:send(Sock, fmtresp(Response)).
|
||||
|
||||
|
||||
|
||||
-spec fmtresp(Response) -> Formatted
|
||||
when Response :: response(),
|
||||
Formatted :: iolist().
|
||||
|
||||
fmtresp(#response{type = page, %% no idea what {data, String} is
|
||||
version = http11,
|
||||
code = Code,
|
||||
headers = Hs,
|
||||
body = Body}) ->
|
||||
%% need byte size for binary
|
||||
Headers = add_headers(Hs, Body),
|
||||
[io_lib:format("HTTP/1.1 ~tp ~ts", [Code, qhl:slogan(Code)]), "\r\n",
|
||||
[io_lib:format("~ts: ~ts\r\n", [K, V]) || {K, V} <- Headers],
|
||||
"\r\n",
|
||||
Body].
|
||||
|
||||
|
||||
|
||||
-spec add_headers(Existing, Body) -> Hdrs
|
||||
when Existing :: [{iolist(), iolist()}],
|
||||
Body :: iolist(),
|
||||
Hdrs :: [{iolist(), iolist()}].
|
||||
|
||||
%% body needed just for size
|
||||
add_headers(Hs, Body) ->
|
||||
Defaults = default_headers(Body),
|
||||
Hs2 = proplists:to_map(Hs),
|
||||
proplists:from_map(maps:merge(Defaults, Hs2)).
|
||||
|
||||
|
||||
|
||||
-spec default_headers(Body) -> HdrsMap
|
||||
when Body :: iolist(),
|
||||
HdrsMap :: #{iolist() := iolist()}.
|
||||
|
||||
default_headers(Body) ->
|
||||
BodySize = byte_size(iolist_to_binary(Body)),
|
||||
#{"Server" => "fewd 0.2.0",
|
||||
"Date" => qhl:ridiculous_web_date(),
|
||||
"Content-Length" => io_lib:format("~p", [BodySize])}.
|
||||
@@ -1,125 +0,0 @@
|
||||
% @doc static file cache
|
||||
-module(fd_static_cache).
|
||||
|
||||
-behavior(gen_server).
|
||||
|
||||
-export([
|
||||
start_link/0,
|
||||
query/1, set/2, unset/1,
|
||||
%%---
|
||||
%% everything below here runs in process context
|
||||
%%--
|
||||
%% gen_server callbacks
|
||||
init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||
code_change/3, terminate/2
|
||||
]).
|
||||
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
-record(f, {http_path :: binary(),
|
||||
fs_path :: file:filename(),
|
||||
last_modified :: file:date_time(),
|
||||
mime_type :: string(),
|
||||
contents :: binary()}).
|
||||
-type context() :: wfc_eval_context:context().
|
||||
|
||||
-record(s,
|
||||
{cookies = #{} :: #{Cookie :: binary() := context()}}).
|
||||
% -type state() :: #s{}.
|
||||
|
||||
|
||||
%%--------------------------------
|
||||
%% api (runs in context of caller)
|
||||
%%--------------------------------
|
||||
|
||||
-spec start_link() -> {ok, pid()} | {error, term()}.
|
||||
start_link() ->
|
||||
gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
|
||||
|
||||
|
||||
|
||||
-spec query(Cookie) -> {ok, Context} | error
|
||||
when Cookie :: binary(),
|
||||
Context :: context().
|
||||
|
||||
query(Cookie) ->
|
||||
gen_server:call(?MODULE, {query, Cookie}).
|
||||
|
||||
|
||||
|
||||
-spec set(Cookie, Context) -> ok
|
||||
when Cookie :: binary(),
|
||||
Context :: context().
|
||||
|
||||
set(Cookie, Context) ->
|
||||
gen_server:cast(?MODULE, {set, Cookie, Context}).
|
||||
|
||||
|
||||
-spec unset(Cookie) -> ok
|
||||
when Cookie :: binary().
|
||||
|
||||
unset(Cookie) ->
|
||||
gen_server:cast(?MODULE, {unset, Cookie}).
|
||||
|
||||
|
||||
%%----------------------
|
||||
%% gen-server bs
|
||||
%%----------------------
|
||||
|
||||
|
||||
|
||||
init(none) ->
|
||||
log(info, "starting fd_cache"),
|
||||
InitState = #s{},
|
||||
{ok, InitState}.
|
||||
|
||||
|
||||
handle_call({query, Cookie}, _, State) ->
|
||||
Result = do_query(Cookie, State),
|
||||
{reply, Result, State};
|
||||
handle_call(Unexpected, From, State) ->
|
||||
tell("~tp: unexpected call from ~tp: ~tp", [?MODULE, Unexpected, From]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_cast({set, Cookie, Context}, State) ->
|
||||
NewState = do_set(Cookie, Context, State),
|
||||
{noreply, NewState};
|
||||
handle_cast({unset, Cookie}, State) ->
|
||||
NewState = do_unset(Cookie, State),
|
||||
{noreply, NewState};
|
||||
handle_cast(Unexpected, State) ->
|
||||
tell("~tp: unexpected cast: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_info(Unexpected, State) ->
|
||||
tell("~tp: unexpected info: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
code_change(_, State, _) ->
|
||||
{ok, State}.
|
||||
|
||||
terminate(_, _) ->
|
||||
ok.
|
||||
|
||||
|
||||
%%---------------------
|
||||
%% doers
|
||||
%%---------------------
|
||||
|
||||
do_set(Cookie, Context, State = #s{cookies = Cookies}) ->
|
||||
NewCookies = maps:put(Cookie, Context, Cookies),
|
||||
NewState = State#s{cookies = NewCookies},
|
||||
NewState.
|
||||
|
||||
|
||||
do_unset(Cookie, State = #s{cookies = Cookies}) ->
|
||||
NewCookies = maps:remove(Cookie, Cookies),
|
||||
NewState = State#s{cookies = NewCookies},
|
||||
NewState.
|
||||
|
||||
|
||||
do_query(Cookie, _State = #s{cookies = Cookies}) ->
|
||||
maps:find(Cookie, Cookies).
|
||||
+8
-14
@@ -12,7 +12,7 @@
|
||||
%%% @end
|
||||
|
||||
-module(fd_sup).
|
||||
-vsn("0.1.0").
|
||||
-vsn("0.2.0").
|
||||
-behaviour(supervisor).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
@@ -36,23 +36,17 @@ start_link() ->
|
||||
|
||||
init([]) ->
|
||||
RestartStrategy = {one_for_one, 1, 60},
|
||||
Clients = {fd_clients,
|
||||
{fd_clients, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
supervisor,
|
||||
[fd_clients]},
|
||||
Chat = {fd_chat,
|
||||
{fd_chat, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
worker,
|
||||
[fd_chat]},
|
||||
Cache = {fd_cache,
|
||||
{fd_cache, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
worker,
|
||||
[fd_cache]},
|
||||
Children = [Clients, Chat, Cache],
|
||||
Httpd = {fd_httpd,
|
||||
{fd_httpd, start_link, []},
|
||||
permanent,
|
||||
5000,
|
||||
supervisor,
|
||||
[fd_httpd]},
|
||||
Children = [Cache, Httpd],
|
||||
{ok, {RestartStrategy, Children}}.
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
% @doc Abstracts a web socket into a process
|
||||
%
|
||||
% hands the TCP socket over to this process, also this process does the
|
||||
% handshake.
|
||||
%
|
||||
% this process sends back `{ws, self(), Message: qhl_ws:ws_msg()}'
|
||||
%
|
||||
% for each websocket message it gets
|
||||
-module(fd_wsp).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-behavior(gen_server).
|
||||
|
||||
-export_type([
|
||||
|
||||
]).
|
||||
|
||||
-export([
|
||||
%% caller context
|
||||
%handshake/0,
|
||||
start_link/3,
|
||||
|
||||
%% process context
|
||||
init/1, handle_call/3, handle_cast/2, handle_info/2,
|
||||
code_change/3, terminate/2
|
||||
]).
|
||||
|
||||
-include("http.hrl").
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
-record(s, {socket :: gen_tcp:socket()}).
|
||||
-type state() :: #s{}.
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% caller context
|
||||
%%-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
-spec start_link(Socket, HandshakeReq, Received) -> Result
|
||||
when Socket :: gen_tcp:socket(),
|
||||
HandshakeReq :: request(),
|
||||
Received :: binary(),
|
||||
Result :: {ok, pid()}
|
||||
| {error, term()}.
|
||||
% @doc
|
||||
% starts a websocket and hands control of socket over to child process
|
||||
|
||||
start_link(Socket, HandshakeReq, Received) ->
|
||||
case gen_server:start_link(?MODULE, [Socket, HandshakeReq, Received], []) of
|
||||
{ok, PID} ->
|
||||
gen_tcp:controlling_process(Socket, PID),
|
||||
{ok, PID};
|
||||
Error ->
|
||||
Error
|
||||
end.
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% process context below this line
|
||||
%%-----------------------------------------------------------------------------
|
||||
|
||||
%% gen_server callbacks
|
||||
|
||||
init([Socket, HandshakeReq, Received]) ->
|
||||
log("~p:~p init", [?MODULE, self()]),
|
||||
case qhl_ws:handshake(HandshakeReq) of
|
||||
{ok, Response} ->
|
||||
ok = fd_http_utils:respond(Socket, Response),
|
||||
InitState = #s{socket = Socket},
|
||||
{ok, InitState};
|
||||
Error ->
|
||||
tell("~p:~p websocket handshake err: ~p", [?MODULE, self(), Error]),
|
||||
fd_http_utils:http_err(Socket, 400),
|
||||
Error
|
||||
end.
|
||||
|
||||
|
||||
handle_call(Unexpected, From, State) ->
|
||||
tell("~tp: unexpected call from ~tp: ~tp", [?MODULE, Unexpected, From]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_cast(Unexpected, State) ->
|
||||
tell("~tp: unexpected cast: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
handle_info({tcp, Sock, Bytes}, State = #s{socket = Sock}) ->
|
||||
{noreply, State};
|
||||
handle_info(Unexpected, State) ->
|
||||
tell("~tp: unexpected info: ~tp", [?MODULE, Unexpected]),
|
||||
{noreply, State}.
|
||||
|
||||
|
||||
code_change(_, State, _) ->
|
||||
{ok, State}.
|
||||
|
||||
terminate(_, _) ->
|
||||
ok.
|
||||
|
||||
|
||||
%%-----------------------------------------------------------------------------
|
||||
%% internals
|
||||
%%-----------------------------------------------------------------------------
|
||||
+3
-3
@@ -3,7 +3,7 @@
|
||||
%%% @end
|
||||
|
||||
-module(fewd).
|
||||
-vsn("0.1.0").
|
||||
-vsn("0.2.0").
|
||||
-behavior(application).
|
||||
-author("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
-copyright("Peter Harpending <peterharpending@qpq.swiss>").
|
||||
@@ -24,7 +24,7 @@
|
||||
%% Returns an {error, Reason} tuple if it is already listening.
|
||||
|
||||
listen(PortNum) ->
|
||||
fd_client_man:listen(PortNum).
|
||||
fd_httpd_client_man:listen(PortNum).
|
||||
|
||||
|
||||
-spec ignore() -> ok.
|
||||
@@ -32,7 +32,7 @@ listen(PortNum) ->
|
||||
%% Make the server stop listening if it is, or continue to do nothing if it isn't.
|
||||
|
||||
ignore() ->
|
||||
fd_client_man:ignore().
|
||||
fd_httpd_client_man:ignore().
|
||||
|
||||
|
||||
-spec start(normal, term()) -> {ok, pid()}.
|
||||
|
||||
+4
-25
@@ -49,62 +49,52 @@ parse(Socket, Received) ->
|
||||
%% socket.
|
||||
|
||||
parse(Socket, Received, M = #request{method = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_method(Socket, Received) of
|
||||
{ok, Method, Rest} -> parse(Socket, Rest, M#request{method = Method});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{path = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_path(Socket, Received) of
|
||||
{ok, Path, Rest} -> parse(Socket, Rest, M#request{path = Path});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{qargs = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_qargs(Socket, Received) of
|
||||
{ok, Qargs, Rest} -> parse(Socket, Rest, M#request{qargs = Qargs});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{fragment = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_fragment(Socket, Received) of
|
||||
{ok, Fragment, Rest} -> parse(Socket, Rest, M#request{fragment = Fragment});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{version = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_version(Socket, Received) of
|
||||
{ok, Version, Rest} -> parse(Socket, Rest, M#request{version = Version});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{headers = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_headers(Socket, Received) of
|
||||
{ok, Headers, Rest} -> parse(Socket, Rest, M#request{headers = Headers});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{enctype = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_enctype(M) of
|
||||
{ok, Enctype} -> parse(Socket, Received, M#request{enctype = Enctype});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{cookies = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_cookies(M) of
|
||||
{ok, Cookies} -> parse(Socket, Received, M#request{cookies = Cookies});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{size = undefined}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_size(M) of
|
||||
{ok, 0} -> {ok, M#request{size = 0}, none};
|
||||
{ok, Size} -> parse(Socket, Received, M#request{size = Size});
|
||||
Error -> Error
|
||||
end;
|
||||
parse(Socket, Received, M = #request{method = get, body = undefined, size = Size}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_body(Received, Size) of
|
||||
{ok, Body} -> {ok, M#request{body = Body}, none};
|
||||
{ok, Body, Next} -> {ok, M#request{body = Body}, Next};
|
||||
@@ -117,7 +107,6 @@ parse(Socket,
|
||||
method = post,
|
||||
enctype = urlencoded,
|
||||
size = Size}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_body(Received, Size) of
|
||||
{ok, Body} ->
|
||||
{ok, M#request{body = parts_to_map(posted(Body))}, none};
|
||||
@@ -141,7 +130,6 @@ parse(Socket,
|
||||
method = post,
|
||||
enctype = {multipart, Boundary},
|
||||
size = Size}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_multipart(Socket, Received, Boundary, Size) of
|
||||
{ok, Parts} -> {ok, M#request{body = parts_to_map(Parts)}, none};
|
||||
{ok, Parts, Next} -> {ok, M#request{body = parts_to_map(Parts)}, Next};
|
||||
@@ -153,12 +141,10 @@ parse(Socket,
|
||||
method = post,
|
||||
enctype = json,
|
||||
size = Size}) ->
|
||||
io:format("~p parse(~p, ~p, ~p)~n", [?LINE, Socket, Received, M]),
|
||||
case read_body(Received, Size) of
|
||||
{ok, Body} -> read_json(M#request{body = Body}, none);
|
||||
{ok, Body, Next} -> read_json(M#request{body = Body}, Next);
|
||||
{incomplete, Body} ->
|
||||
io:format("~p {incomplete, ~p}~n", [?LINE, Body]),
|
||||
case accumulate(Socket, M#request{body = Body}) of
|
||||
{ok, NewM = #request{body = NewBody}} ->
|
||||
read_json(NewM#request{body = NewBody}, none);
|
||||
@@ -528,7 +514,6 @@ read_size(#request{method = options}) ->
|
||||
|
||||
|
||||
read_body(Received, Size) ->
|
||||
io:format("~p read_body(~p, ~p)~n", [?LINE, Received, Size]),
|
||||
case Received of
|
||||
<<Bin:Size/binary>> ->
|
||||
{ok, Bin};
|
||||
@@ -826,11 +811,9 @@ accumulate(Socket, M = #request{size = Size, body = Body}) ->
|
||||
end.
|
||||
|
||||
accumulate(Socket, Remaining, Received) when Remaining > 0 ->
|
||||
io:format("~p accumulate(~p, ~p, ~p)~n", [?LINE, Socket, Remaining, Received]),
|
||||
ok = inet:setopts(Socket, [{active, once}]),
|
||||
receive
|
||||
{tcp, Socket, Bin} ->
|
||||
io:format("~p~n", [?LINE]),
|
||||
Size = byte_size(Bin),
|
||||
if
|
||||
Size == Remaining ->
|
||||
@@ -845,16 +828,12 @@ accumulate(Socket, Remaining, Received) when Remaining > 0 ->
|
||||
{ok, NewReceived, Next}
|
||||
end;
|
||||
{tcp_closed, Socket} ->
|
||||
io:format("~p~n", [?LINE]),
|
||||
{error, tcp_closed};
|
||||
{tcp_error, Socket, Reason} ->
|
||||
io:format("~p~n", [?LINE]),
|
||||
{error, {tcp_error, Reason}};
|
||||
X ->
|
||||
io:format("~p raseevd: ~p~n", [?LINE, X])
|
||||
after 10_000 ->
|
||||
io:format("~p~n", [?LINE]),
|
||||
{error, timeout}
|
||||
{error, {tcp_error, Reason}}
|
||||
%X ->
|
||||
after 3_000 ->
|
||||
{error, timeout}
|
||||
end;
|
||||
accumulate(_, 0, Received) ->
|
||||
{ok, Received};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
% @doc websockets
|
||||
%
|
||||
% ref: https://datatracker.ietf.org/doc/html/rfc6455
|
||||
-module(fd_ws).
|
||||
-module(qhl_ws).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
opcode/0,
|
||||
@@ -19,13 +20,7 @@
|
||||
]).
|
||||
|
||||
-include("http.hrl").
|
||||
-include("$zx_include/zx_logger.hrl").
|
||||
|
||||
-type request() :: #request{}.
|
||||
-type response() :: #response{}.
|
||||
-type tcp_error() :: closed
|
||||
| {timeout, RestData :: binary() | erlang:iovec()}
|
||||
| inet:posix().
|
||||
|
||||
-define(MAX_PAYLOAD_SIZE, ((1 bsl 63) - 1)).
|
||||
|
||||
@@ -70,10 +65,8 @@ day() -> 24*hr().
|
||||
|
||||
-spec handshake(Req) -> Result
|
||||
when Req :: request(),
|
||||
Result :: {ok, ClientProtocols, ClientExtensions, DraftResponse}
|
||||
Result :: {ok, DraftResponse}
|
||||
| {error, Reason},
|
||||
ClientProtocols :: [binary()],
|
||||
ClientExtensions :: binary(),
|
||||
DraftResponse :: response(),
|
||||
Reason :: any().
|
||||
% @doc
|
||||
@@ -639,11 +632,8 @@ recv_frame_await(Frame, Sock, Received, Timeout) ->
|
||||
% @end
|
||||
|
||||
send(Socket, {Type, Payload}) ->
|
||||
tell("fd_ws: send(~tp, {~tp, ~tp})", [Socket, Type, Payload]),
|
||||
BPayload = payload_to_binary(Payload),
|
||||
tell("fd_ws: BPayload = ~tp", [BPayload]),
|
||||
Frame = message_to_frame(Type, BPayload),
|
||||
tell("fd_ws: Frame = ~tp", [Frame]),
|
||||
send_frame(Socket, Frame).
|
||||
|
||||
payload_to_binary(Bin) when is_binary(Bin) -> Bin;
|
||||
@@ -682,7 +672,6 @@ message_to_frame(Control, Payload)
|
||||
|
||||
send_frame(Sock, Frame) ->
|
||||
Binary = render_frame(Frame),
|
||||
tell("send_frame: rendered frame: ~tp", [Binary]),
|
||||
gen_tcp:send(Sock, Binary).
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
% @doc
|
||||
% porcelain wfc ops
|
||||
-module(wfc).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
sentence/0
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
% @doc
|
||||
% bit matrices
|
||||
-module(wfc_bm).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
bit/0,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
-module(wfc_eval).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
]).
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
-module(wfc_eval_context).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
context/0
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
%
|
||||
% mathematically, this is a variable like "a", "b", "c", etc
|
||||
-module(wfc_ltr).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
ltr/0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
-module(wfc_pp).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export([
|
||||
eval_result/1,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
-module(wfc_read).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
]).
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
%
|
||||
% empty sentence is 0
|
||||
-module(wfc_sentence).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
sentence/0
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
% @doc
|
||||
% sentence-fun <-> truth table logic
|
||||
-module(wfc_sftt).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
sf/0, tt/0
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
% @doc
|
||||
% library of truth tables
|
||||
-module(wfc_ttfuns).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
bit/0,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
% @doc misc utility functions
|
||||
-module(wfc_utils).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export([err/2, str/2, emsg/2]).
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
%
|
||||
% operations assume all inputs are valid
|
||||
-module(wfc_word).
|
||||
-vsn("0.2.0").
|
||||
|
||||
-export_type([
|
||||
word/0
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
%%% @end
|
||||
|
||||
-module(zj).
|
||||
-vsn("1.1.2").
|
||||
-vsn("0.2.0").
|
||||
-author("Craig Everett <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-license("MIT").
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{name,"front end web development lab"}.
|
||||
{type,app}.
|
||||
{modules,[]}.
|
||||
{author,"Peter Harpending"}.
|
||||
{prefix,"fd"}.
|
||||
{desc,"Front End Web Dev in Erlang stuff"}.
|
||||
{author,"Peter Harpending"}.
|
||||
{package_id,{"otpr","fewd",{0,1,0}}}.
|
||||
{package_id,{"otpr","fewd",{0,2,0}}}.
|
||||
{deps,[]}.
|
||||
{key_name,none}.
|
||||
{a_email,"peterharpending@qpq.swiss"}.
|
||||
|
||||
Reference in New Issue
Block a user