Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add cloudflare workers for backend process #13

Merged
merged 16 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/check-format-and-test-cloudflare-workers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Check PR Format and Test for cloudflare-workers

on:
pull_request:
branches:
- master

jobs:
check-format:
name: Check PR Format
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./cloudflare-workers
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
name: Set Node.js 20.x
with:
node-version: 20.x
- uses: borales/actions-yarn@v5
name: Run install
with:
cmd: install
dir: cloudflare-workers
- uses: borales/actions-yarn@v5
name: Check Format
with:
cmd: prettier --check .
dir: cloudflare-workers
54 changes: 54 additions & 0 deletions .github/workflows/deploy-cloudflare-workers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
name: Deploy cloudflare-workers to Workers

on:
push:
tags:
- "*"
paths:
- cloudflare-workers/**
workflow_dispatch:
Enter-tainer marked this conversation as resolved.
Show resolved Hide resolved

jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./cloudflare-workers
steps:
- uses: actions/checkout@v4
name: Checkout Repo
- uses: actions/setup-node@v4
name: Set Node.js 20.x
with:
node-version: 20.x
- uses: borales/actions-yarn@v5
name: Run install
with:
cmd: install
dir: cloudflare-workers
- name: Deploy
uses: cloudflare/wrangler-action@v3
with:
workingDirectory: "cloudflare-workers"
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
secrets: |
ADMINISTRATOR_SECRET
env:
ADMINISTRATOR_SECRET: ${{ secrets.ADMINISTRATOR_SECRET }}
shaokeyibb marked this conversation as resolved.
Show resolved Hide resolved
upload-artifacts:
name: Upload Artifacts
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./cloudflare-workers
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
name: Checkout Repo
- uses: actions/upload-artifact@v2
with:
name: cloudflare-workers
path: cloudflare-workers
12 changes: 12 additions & 0 deletions cloudflare-workers/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
172 changes: 172 additions & 0 deletions cloudflare-workers/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Logs

logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)

report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

# Runtime data

pids
_.pid
_.seed
\*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover

lib-cov

# Coverage directory used by tools like istanbul

coverage
\*.lcov

# nyc test coverage

.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)

.grunt

# Bower dependency directory (https://bower.io/)

bower_components

# node-waf configuration

.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)

build/Release

# Dependency directories

node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)

web_modules/

# TypeScript cache

\*.tsbuildinfo

# Optional npm cache directory

.npm

# Optional eslint cache

.eslintcache

# Optional stylelint cache

.stylelintcache

# Microbundle cache

.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history

.node_repl_history

# Output of 'npm pack'

\*.tgz

# Yarn Integrity file

.yarn-integrity

# dotenv environment variable files

.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)

.cache
.parcel-cache

# Next.js build output

.next
out

# Nuxt.js build / generate output

.nuxt
dist

# Gatsby files

.cache/

# Comment in the public line in if your project uses Gatsby and not Next.js

# https://nextjs.org/blog/next-9-1#public-directory-support

# public

# vuepress build output

.vuepress/dist

# vuepress v2.x temp and cache directory

.temp
.cache

# Docusaurus cache and generated files

.docusaurus

# Serverless directories

.serverless/

# FuseBox cache

.fusebox/

# DynamoDB Local files

.dynamodb/

# TernJS port file

.tern-port

# Stores VSCode versions used for testing VSCode extensions

.vscode-test

# yarn v2

.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*

# wrangler project

.dev.vars
.wrangler/
6 changes: 6 additions & 0 deletions cloudflare-workers/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": true
}
27 changes: 27 additions & 0 deletions cloudflare-workers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "cloudflare-workers",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev",
"test": "vitest",
"fmt": "prettier --write .",
"cf-typegen": "wrangler types",
"cf-initdb": "wrangler d1 execute comments --remote --file=schema.sql",
"cf-initdb-local": "wrangler d1 execute comments --local --file=schema.sql"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "^0.4.5",
"@cloudflare/workers-types": "^4.20240712.0",
"prettier": "3.3.3",
"typescript": "^5.5.2",
"vitest": "1.5.0",
"wrangler": "^3.60.3"
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
"dependencies": {
"itty-router": "^5.0.17"
}
}
41 changes: 41 additions & 0 deletions cloudflare-workers/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
DROP TABLE IF EXISTS `comments`;
DROP TABLE IF EXISTS `commenters`;
DROP TABLE IF EXISTS `offsets`;
DROP TABLE IF EXISTS `pages`;
DROP TABLE IF EXISTS `metas`;

CREATE TABLE IF NOT EXISTS `metas` (
`key` TEXT PRIMARY KEY,
`value` TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS `pages` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`path` TEXT UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS `offsets` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`page_id` INTEGER NOT NULL,
`start` INTEGER NOT NULL,
`end` INTEGER NOT NULL,
FOREIGN KEY(`page_id`) REFERENCES `pages`(`id`)
);
CREATE INDEX idx_offsets ON `offsets`(`start`, `end`);

CREATE TABLE IF NOT EXISTS `commenters`(
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT NOT NULL,
`user_agent` TEXT NOT NULL,
`ip_address` TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS `comments` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`offset_id` INTEGER NOT NULL,
`commenter_id` INTEGER NOT NULL,
`comment` TEXT NOT NULL,
`created_time` TEXT NOT NULL, -- SQLite currently not support TIMESTAMP, use ISO 8601 DateTime
FOREIGN KEY(`offset_id`) REFERENCES `offsets`(`id`),
FOREIGN KEY(`commenter_id`) REFERENCES `commenters`(`id`)
);
shaokeyibb marked this conversation as resolved.
Show resolved Hide resolved
23 changes: 23 additions & 0 deletions cloudflare-workers/src/administration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { getMeta, setMeta } from './db';

const encoder = new TextEncoder();

export function validateSecret(env: Env, secret: string): boolean {
const secretBytes = encoder.encode(env.ADMINISTRATOR_SECRET);
const inputBytes = encoder.encode(secret);

if (secretBytes.byteLength !== inputBytes.byteLength) {
return false;
}

return crypto.subtle.timingSafeEqual(secretBytes, inputBytes);
}

export async function setCommitHash(env: Env, hash: string) {
await setMeta(env, 'commit_hash', hash);
}

export async function compareCommitHash(env: Env, hash: string): Promise<boolean> {
const storedHash = await getMeta(env, 'commit_hash');
return storedHash === hash;
}
24 changes: 24 additions & 0 deletions cloudflare-workers/src/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { getPaths } from './db';

export async function purgeAllCommentCache(env: Env, cache: Cache, baseUrl: string) {
const paths = await getPaths(env);

await Promise.all(
paths.map((path) => {
purgeCommentCache(env, cache, baseUrl, path);
}),
);
}

export async function purgeCommentCache(env: Env, cache: Cache, baseUrl: string, path: string) {
// await cache.delete(`${baseUrl}/comment${path}`);
}

export async function putCommentCache(env: Env, cache: Cache, baseUrl: string, path: string, resp: Response): Promise<void> {
// await cache.put(`${baseUrl}/comment${path}`, resp);
}

export async function matchCommentCache(env: Env, cache: Cache, baseUrl: string, path: string): Promise<Response | undefined> {
// return await cache.match(`${baseUrl}/comment${path}`);
return undefined;
}
Loading