Skip to content

Commit fd600f3

Browse files
committed
Add
1 parent 629b669 commit fd600f3

File tree

15 files changed

+2944
-0
lines changed

15 files changed

+2944
-0
lines changed

hello-pingora/Cargo.lock

+2,557
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

hello-pingora/Cargo.toml

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "hello-pingora"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
async-trait = "0.1.77"
10+
pingora = { version = "0.1.0", features = ["lb"] }

hello-pingora/src/main.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use async_trait::async_trait;
2+
use pingora::prelude::*;
3+
use std::sync::Arc;
4+
5+
pub struct LB(Arc<LoadBalancer<RoundRobin>>);
6+
7+
#[async_trait]
8+
impl ProxyHttp for LB {
9+
type CTX = ();
10+
fn new_ctx(&self) -> () {
11+
()
12+
}
13+
14+
async fn upstream_peer(&self, _session: &mut Session, _ctx: &mut ()) -> Result<Box<HttpPeer>> {
15+
let upstream = self.0.select(b"", 256).unwrap();
16+
17+
println!("upstream peer is: {:?}", upstream);
18+
19+
let peer = Box::new(HttpPeer::new(upstream, true, "one.one.one.one".to_string()));
20+
Ok(peer)
21+
}
22+
23+
async fn upstream_request_filter(
24+
&self,
25+
_session: &mut Session,
26+
upstream_request: &mut RequestHeader,
27+
_ctx: &mut (),
28+
) -> Result<()> {
29+
upstream_request
30+
.insert_header("Host", "one.one.one.one")
31+
.unwrap();
32+
Ok(())
33+
}
34+
}
35+
36+
fn main() {
37+
let mut my_server = Server::new(Some(Opt::default())).unwrap();
38+
my_server.bootstrap();
39+
40+
let mut upstreams =
41+
LoadBalancer::try_from_iter(["1.1.1.1:443", "1.0.0.1:443", "127.0.0.1:343"]).unwrap();
42+
43+
let hc = TcpHealthCheck::new();
44+
upstreams.set_health_check(hc);
45+
upstreams.health_check_frequency = Some(std::time::Duration::from_secs(1));
46+
47+
let background = background_service("health check", upstreams);
48+
let upstreams = background.task();
49+
50+
let mut lb = http_proxy_service(&my_server.configuration, LB(upstreams));
51+
lb.add_tcp("0.0.0.0:6188");
52+
53+
my_server.add_service(background);
54+
55+
my_server.add_service(lb);
56+
my_server.run_forever();
57+
}

hello-wasm/add.wasm

41 Bytes
Binary file not shown.

hello-wasm/add.wat

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
(module
2+
(func $add (param $lhs i32) (param $rhs i32) (result i32)
3+
local.get $lhs
4+
local.get $rhs
5+
i32.add
6+
)
7+
(export "add" (func $add))
8+
)

hello-wasm/demo.wat

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
(module
2+
(import "wasi_snapshot_preview1" "fd_write"
3+
;; fd_write(fd, *iovs, iovs_len, *nwritten) -> i32
4+
(func $fd_write (param i32 i32 i32 i32) (result i32))
5+
)
6+
(memory 1)
7+
(export "memory" (memory 0))
8+
9+
(data (i32.const 8) "Hello, world!\n")
10+
11+
(func $main (export "_start")
12+
;; Create new io vector at the memory location 0
13+
(i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base
14+
(i32.store (i32.const 4) (i32.const 14)) ;; iov.iov_len -- length of "Hello, world!\n"
15+
16+
(call $fd_write
17+
(i32.const 1) ;; fd (1 for stdout)
18+
(i32.const 0) ;; *iovs
19+
(i32.const 1) ;; iovs_len
20+
(i32.const 20) ;; nwritten
21+
)
22+
drop
23+
)
24+
)

hello-wasm/simple.wasm

8 Bytes
Binary file not shown.

rust-bbs/sql/comments.sql

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
CREATE TABLE `comments` (
2+
`thread_id` bigint unsigned NOT NULL,
3+
`comment_id` bigint unsigned NOT NULL,
4+
`user_id` bigint unsigned NOT NULL,
5+
`created_at` datetime(6) NOT NULL,
6+
`body` text NOT NULL,
7+
PRIMARY KEY (`thread_id`, `comment_id`),
8+
CONSTRAINT `fk_comments_to_users_on_id`
9+
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
10+
CONSTRAINT `fk_comments_to_threads_on_id`
11+
FOREIGN KEY (`thread_id`) REFERENCES `threads` (`id`) ON DELETE CASCADE,
12+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin ROW_FORMAT=DYNAMIC;

rust-bbs/sql/threads.sql

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
CREATE TABLE `threads` (
2+
`thread_id` bigint unsigned NOT NULL,
3+
`title` varchar(191) NOT NULL,
4+
`creator_id` bigint unsigned NOT NULL,
5+
`created_at` datetime(6) NOT NULL,
6+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin ROW_FORMAT=DYNAMIC;

rust-bbs/sql/users.sql

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
CREATE TABLE `users` (
2+
`user_id` bigint unsigned NOT NULL,
3+
`name` varchar(63) CHARSET ascii COLLATE ascii_general_ci NOT NULL,
4+
`display_name` varchar(63) NOT NULL,
5+
`password_hash` varchar(255) CHARSET ascii COLLATE ascii_bin NOT NULL,
6+
`created_at` datetime(6) NOT NULL,
7+
`deleted_at` datetime(6) NOT NULL DEFAULT '9999-12-31 23:59:59.999999',
8+
PRIMARY KEY (`user_id`),
9+
UNIQUE KEY `name` (`name`)
10+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin ROW_FORMAT=DYNAMIC;

rust-lex/Cargo.lock

+117
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust-lex/Cargo.toml

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "rust-lex"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
once_cell = "1"
10+
regex = "1"
11+
thiserror = "1"

rust-lex/src/lex.rs

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
use once_cell::sync::Lazy;
2+
use regex::Regex;
3+
4+
use crate::token::Token;
5+
6+
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
7+
pub enum LexicalError {
8+
#[error("Unexpected character: {0}")]
9+
UnexpectedCharacter(char),
10+
#[error("Unexpected end of input")]
11+
UnexpectedEndOfInput,
12+
}
13+
14+
macro_rules! regex {
15+
($pattern:expr) => {{
16+
static RE: Lazy<Regex> = Lazy::new(|| Regex::new($pattern).unwrap());
17+
&RE
18+
}};
19+
}
20+
21+
// 成功: Ok(Some((Token, 消費したバイト数)))
22+
// 失敗: Err(LexicalError)
23+
// EOF: Ok(None)
24+
type LexResult = std::result::Result<Option<(Token, usize)>, LexicalError>;
25+
26+
fn ok(token: Token, bytes_consumed: usize) -> LexResult {
27+
Ok(Some((token, bytes_consumed)))
28+
}
29+
30+
fn err(e: LexicalError) -> LexResult {
31+
Err(e)
32+
}
33+
34+
fn eof() -> LexResult {
35+
Ok(None)
36+
}
37+
38+
// input からトークンをひとつ読み取り、トークンと消費したバイト数を返す。
39+
pub fn lex(input: &str) -> LexResult {
40+
if input.is_empty() {
41+
return eof();
42+
}
43+
44+
let re_whitespace = regex!(r"^[ \t\r\n]+");
45+
if let Some(m) = re_whitespace.find(input) {
46+
let r = lex(&input[m.end()..]);
47+
return match r {
48+
Ok(Some((token, bytes_consumed))) => ok(token, m.end() + bytes_consumed),
49+
_ => r,
50+
};
51+
}
52+
53+
let re_identifier_or_keyword = regex!(r"^[a-zA-Z_][a-zA-Z0-9_]*");
54+
if let Some(m) = re_identifier_or_keyword.find(input) {
55+
let s = m.as_str();
56+
let token = match s {
57+
"true" => Token::True,
58+
"false" => Token::False,
59+
"null" => Token::Null,
60+
_ => Token::Identifier(s.to_owned()),
61+
};
62+
return ok(token, m.end());
63+
}
64+
65+
let re_digits = regex!(r"^[0-9]+");
66+
if let Some(m) = re_digits.find(input) {
67+
let n = m.as_str().parse::<f64>().unwrap();
68+
return ok(Token::Number(n), m.end());
69+
}
70+
71+
unimplemented!()
72+
}
73+
74+
// バイトオフセットを (行, 列) に変換する。
75+
// 行と列は 0 から始まる。
76+
// line_breaks はソースコードの改行文字のバイトオフセットの配列である。
77+
pub fn to_line_col(line_breaks: &[usize], pos: usize) -> (usize, usize) {
78+
let line = line_breaks.partition_point(|&x| x < pos);
79+
let col = if line == 0 {
80+
pos
81+
} else {
82+
pos - line_breaks[line - 1] - 1
83+
};
84+
(line, col)
85+
}
86+
87+
#[test]
88+
fn test_to_line_col() {
89+
let source_code = [
90+
"#include <stdio.h>",
91+
"",
92+
"int main(void) {",
93+
" return 0;",
94+
"}",
95+
].join("\n");
96+
97+
let line_breaks: Vec<usize> = source_code
98+
.match_indices('\n')
99+
.map(|(i, _)| i)
100+
.collect();
101+
102+
assert_eq!(to_line_col(&line_breaks, 0), (0, 0));
103+
assert_eq!(to_line_col(&line_breaks, 1), (0, 1));
104+
assert_eq!(to_line_col(&line_breaks, 18), (0, 18));
105+
assert_eq!(to_line_col(&line_breaks, 19), (1, 0));
106+
assert_eq!(to_line_col(&line_breaks, 20), (2, 0));
107+
assert_eq!(to_line_col(&line_breaks, 21), (2, 1));
108+
assert_eq!(to_line_col(&line_breaks, 36), (2, 16));
109+
}

rust-lex/src/main.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
mod token;
2+
mod lex;
3+
4+
fn main() {
5+
println!("Hello, world!");
6+
}

rust-lex/src/token.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#[derive(Debug, Clone, PartialEq)]
2+
pub enum Token {
3+
True,
4+
False,
5+
Null,
6+
7+
Number(f64),
8+
Identifier(String),
9+
String(String),
10+
11+
Colon,
12+
Comma,
13+
LBrace,
14+
RBrace,
15+
LBracket,
16+
RBracket,
17+
}

0 commit comments

Comments
 (0)