Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
50 changes: 46 additions & 4 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,24 @@ name: Documentation
on:
pull_request:
branches: [ master ]
paths: &docs_paths
push:
branches: [ master ]
paths:
- 'docs/**'
- 'zensical.toml'
- 'README.md'
- 'pom.xml'
- 'mvnw'
- '.mvn/**'
- '.github/workflows/docs.yml'
- 'src/main/resources/application.properties'
- 'src/main/resources/application-test.properties'
- 'src/main/java/xyz/subho/clone/twitter/config/OpenApiConfig.java'
- 'src/main/java/xyz/subho/clone/twitter/constant/**'
- 'src/main/java/xyz/subho/clone/twitter/controller/**'
- 'src/main/java/xyz/subho/clone/twitter/model/**'
- 'src/main/java/xyz/subho/clone/twitter/security/SecurityConfig.java'
- 'src/test/java/xyz/subho/clone/twitter/OpenApiDocumentationTest.java'
push:
branches: [ master ]
paths: *docs_paths
workflow_dispatch:

permissions:
Expand All @@ -39,42 +42,81 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Detect documentation changes
if: github.event_name == 'pull_request'
id: documentation
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
changed_paths="$(mktemp)"
trap 'rm -f "$changed_paths"' EXIT
if ! git diff --no-renames --name-only -z "$BASE_SHA...$HEAD_SHA" > "$changed_paths"; then
echo '::error::Unable to compute the pull-request diff'
exit 1
fi
if grep -zEq '^(docs/|zensical\.toml$|README\.md$|pom\.xml$|mvnw$|\.mvn/|\.github/workflows/docs\.yml$|src/main/resources/application(-test)?\.properties$|src/main/java/xyz/subho/clone/twitter/(config/OpenApiConfig\.java$|constant/|controller/|model/|security/SecurityConfig\.java$)|src/test/java/xyz/subho/clone/twitter/OpenApiDocumentationTest\.java$)' "$changed_paths"; then
echo 'affected=true' >> "$GITHUB_OUTPUT"
else
grep_status=$?
if [ "$grep_status" -eq 1 ]; then
echo 'affected=false' >> "$GITHUB_OUTPUT"
else
echo '::error::Unable to match changed documentation paths'
exit 1
fi
fi
- name: Set up Microsoft JDK 25
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
uses: actions/setup-java@v6
with:
distribution: 'microsoft'
java-version: '25'
cache: 'maven'
- name: Export OpenAPI
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: ./mvnw -B -Dtest=OpenApiDocumentationTest test
- name: Set up Python
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
uses: actions/setup-python@v6
with:
python-version: '3.13'
cache: 'pip'
cache-dependency-path: docs/tooling/requirements.txt
- name: Install Zensical
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: 'pip install --require-hashes --only-binary :all: -r docs/tooling/requirements.txt'
- name: Set up Node.js
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: docs/tooling/package-lock.json
- name: Install API documentation tooling
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: npm --prefix docs/tooling ci --ignore-scripts
- name: Build Markdown site
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: zensical build --clean --strict
- name: Validate and build API reference
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: |
npm --prefix docs/tooling run api:lint
npm --prefix docs/tooling run api:build
cp target/generated-docs/openapi.json site/api/openapi.json
env:
REDOCLY_TELEMETRY: off
- name: Check mobile layout
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
run: npm --prefix docs/tooling run site:mobile-check
- name: Configure GitHub Pages
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
uses: actions/configure-pages@v6
- name: Upload GitHub Pages artifact
if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true'
uses: actions/upload-pages-artifact@v5
with:
path: site
Expand Down
10 changes: 10 additions & 0 deletions docs/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@media screen and (max-width: 44.984375rem) {
.md-typeset__scrollwrap,
.md-typeset details .md-typeset__scrollwrap {
margin-inline: 0;
}

.md-typeset__table {
width: 100%;
}
}
160 changes: 160 additions & 0 deletions docs/tooling/check-mobile-layout.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { execFileSync, spawn } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const chrome = process.env.CHROME_PATH ?? findChrome();

function findChrome() {
if (process.platform === "darwin") {
return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
}
for (const command of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) {
try {
return execFileSync("which", [command], { encoding: "utf8" }).trim();
} catch {}
}
throw new Error("No supported Chrome or Chromium executable was found");
}
const profile = await mkdtemp(join(tmpdir(), "moo-docs-chrome-"));
const server = spawn("python3", ["-m", "http.server", "4173", "-d", "../../site"], {
cwd: import.meta.dirname,
stdio: "ignore",
});
for (let attempt = 0; attempt < 50; attempt++) {
try {
const response = await fetch("http://127.0.0.1:4173/");
if (response.ok) break;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100));
}
const browser = spawn(
chrome,
[
"--headless=new",
"--no-sandbox",
"--disable-dev-shm-usage",
"--remote-debugging-port=0",
`--user-data-dir=${profile}`,
"http://127.0.0.1:4173/",
],
{ stdio: ["ignore", "ignore", "pipe"] },
);
let browserError = "";
browser.stderr.on("data", (data) => {
browserError += data.toString();
});
browser.on("error", (error) => {
browserError += `${error.message}\n`;
});
const browserExit = new Promise((resolve) => browser.once("close", resolve));
const serverExit = new Promise((resolve) => server.once("close", resolve));

const waitForTabs = async () => {
for (let attempt = 0; attempt < 300; attempt++) {
if (browser.exitCode !== null || browser.signalCode !== null) {
throw new Error(`Chrome did not start${browserError ? `: ${browserError.trim()}` : ""}`);
}
try {
const [port] = (await readFile(join(profile, "DevToolsActivePort"), "utf8")).split("\n");
const response = await fetch(`http://127.0.0.1:${port}/json`);
if (response.ok) return response.json();
} catch {}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`Chrome did not start${browserError ? `: ${browserError.trim()}` : ""}`);
};

try {
const tabs = await waitForTabs();
const tab = tabs.find(({ type }) => type === "page");
const socket = new WebSocket(tab.webSocketDebuggerUrl);
const pending = new Map();
let requestId = 0;
let loadReject;
socket.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.method === "Page.loadEventFired") {
pending.get("load")?.();
pending.delete("load");
}
pending.get(message.id)?.resolve(message);
pending.delete(message.id);
};
socket.addEventListener("close", () => {
const error = new Error("Chrome DevTools connection closed");
loadReject?.(error);
for (const pendingCall of pending.values()) pendingCall.reject?.(error);
pending.clear();
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await new Promise((resolve) => (socket.onopen = resolve));
const call = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++requestId;
pending.set(id, { resolve, reject });
socket.send(JSON.stringify({ id, method, params }));
});
await call("Page.enable");

for (const width of [320, 375]) {
await call("Emulation.setDeviceMetricsOverride", {
width,
height: 812,
deviceScaleFactor: 1,
mobile: true,
});
const loaded = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
loadReject = undefined;
pending.delete("load");
reject(new Error(`Page did not load at ${width}px`));
}, 10_000);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
loadReject = (error) => {
clearTimeout(timeout);
loadReject = undefined;
pending.delete("load");
reject(error);
};
pending.set("load", () => {
clearTimeout(timeout);
loadReject = undefined;
resolve();
});
});
await Promise.race([call("Page.reload"), loaded]);
await loaded;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let layout;
for (let attempt = 0; attempt < 50 && !layout; attempt++) {
const result = await call("Runtime.evaluate", {
expression: `(() => {
const root = document.documentElement;
const article = document.querySelector("article");
if (!article) return null;
const bounds = article.getBoundingClientRect();
const clipped = [...article.querySelectorAll("*")]
.filter((element) => {
const rect = element.getBoundingClientRect();
return !element.closest("pre") && rect.width > 0 && (rect.left < bounds.left - 1 || rect.right > bounds.right + 1);
})
.map((element) => element.tagName + "." + element.className)
.slice(0, 5);
return { rootFits: root.scrollWidth <= root.clientWidth, clipped };
})()`,
returnByValue: true,
});
layout = result.result.result.value;
if (!layout) await new Promise((resolve) => setTimeout(resolve, 100));
}
if (!layout) throw new Error(`${width}px layout did not load`);
if (!layout.rootFits || layout.clipped.length) {
throw new Error(`${width}px layout overflows: ${layout.clipped.join(", ")}`);
}
}
socket.close();
console.log("Mobile layout fits at 320px and 375px");
} finally {
browser.kill();
server.kill();
await Promise.all([browserExit, serverExit]);
await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
32 changes: 32 additions & 0 deletions docs/tooling/finalize-api-reference.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";

const output = new URL("../../site/api/reference/index.html", import.meta.url);
const basePath = "/twitter-backend-java/api/reference";
const canonicalUrl = `https://subho.xyz${basePath}/`;
const description = "Interactive OpenAPI reference for the Moo Twitter Backend.";
const routes = ["authentication", "hashtags", "models", "posts", "search", "users"];
let html = await readFile(output, "utf8");
const scriptStart = html.indexOf('<script type="module">');

if (scriptStart < 0) throw new Error("Redoc module script was not found");

const document = html.slice(0, scriptStart).replaceAll('href="/', `href="${basePath}/`);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
html = `${document}${html.slice(scriptStart)}`.replace(
"</title>",
`</title>\n <meta name="description" content="${description}">\n <meta property="og:title" content="Moo Twitter Backend API">\n <meta property="og:description" content="${description}">\n <link rel="canonical" href="${canonicalUrl}">`,
);

if (html.includes('href="/authentication"') || !html.includes(`href="${basePath}/authentication"`)) {
throw new Error("Redoc routes were not rebased");
}
if (!html.includes(`rel="canonical" href="${canonicalUrl}"`)) {
throw new Error("API reference metadata was not added");
}

await writeFile(output, html);

for (const route of routes) {
const directory = new URL(`./${route}/`, output);
await mkdir(directory, { recursive: true });
await copyFile(output, new URL("index.html", directory));
}
3 changes: 2 additions & 1 deletion docs/tooling/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"private": true,
"scripts": {
"api:lint": "redocly lint ../../target/generated-docs/openapi.json",
"api:build": "redocly build-docs ../../target/generated-docs/openapi.json --inlineBundle --output ../../site/api/reference/index.html"
"api:build": "redocly build-docs ../../target/generated-docs/openapi.json --inlineBundle --output ../../site/api/reference/index.html && node finalize-api-reference.mjs",
"site:mobile-check": "node check-mobile-layout.mjs"
},
"devDependencies": {
"@redocly/cli": "2.73.0"
Expand Down
1 change: 1 addition & 0 deletions docs/tooling/redocly.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ rules:
operation-4xx-response: off

openapi:
routingBasePath: /twitter-backend-java/api/reference
schemaDefinitionsTagName: Models
sortRequiredPropsFirst: true
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,7 @@ public ResponseEntity<PostModel> addPost(
@DeleteMapping(PostV1Constants.POST_ID)
@Operation(summary = "Delete an owned post")
@ApiResponse(responseCode = "200", description = "Post deleted")
public ResponseEntity<HttpStatus> deletePost(
@PathVariable("postId") UUID postId, Principal principal) {
public ResponseEntity<Void> deletePost(@PathVariable("postId") UUID postId, Principal principal) {

var user = userService.getUserByUserName(principal.getName());
if (user == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public ResponseEntity<UserModel> updateUser(
@Counted(value = "moo.users.follow", description = "Number of follow actions")
@Operation(summary = "Follow a user")
@ApiResponse(responseCode = "204", description = "User followed")
public ResponseEntity<HttpStatus> addFollower(@PathVariable UUID userId, Principal principal) {
public ResponseEntity<Void> addFollower(@PathVariable UUID userId, Principal principal) {
var follower = userService.getUserByUserName(principal.getName());
if (follower == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
Expand All @@ -129,7 +129,7 @@ public ResponseEntity<HttpStatus> addFollower(@PathVariable UUID userId, Princip
@DeleteMapping(UserV1Constants.FOLLOW)
@Operation(summary = "Unfollow a user")
@ApiResponse(responseCode = "204", description = "User unfollowed")
public ResponseEntity<HttpStatus> removeFollower(
public ResponseEntity<Void> removeFollower(
@PathVariable("userId") UUID userId, Principal principal) {
var follower = userService.getUserByUserName(principal.getName());
if (follower == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,25 @@ void exportsAnAccurateOpenApiDocument() throws Exception {
assertThat(openApi.at("/paths/~1v1~1posts/get/security/0/bearerAuth").isArray()).isTrue();
assertThat(openApi.at("/paths/~1v1~1posts/post/security/0/csrfHeader").isArray()).isTrue();
assertThat(openApi.at("/paths/~1v1~1users/patch/security/0/bearerAuth").isArray()).isTrue();
assertThat(openApi.at("/paths/~1v1~1users~1{userId}~1follow/put/responses/204").isMissingNode())
.isFalse();
assertThat(
openApi
.at("/paths/~1v1~1users~1{userId}~1follow/put/responses/204/content")
.isMissingNode())
.isTrue();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
assertThat(
openApi.at("/paths/~1v1~1users~1{userId}~1follow/delete/responses/204").isMissingNode())
.isFalse();
assertThat(
openApi
.at("/paths/~1v1~1users~1{userId}~1follow/delete/responses/204/content")
.isMissingNode())
.isTrue();
assertThat(openApi.at("/paths/~1v1~1posts~1{postId}/delete/responses/200").isMissingNode())
.isFalse();
assertThat(
openApi.at("/paths/~1v1~1posts~1{postId}/delete/responses/200/content").isMissingNode())
.isTrue();
}
}
1 change: 1 addition & 0 deletions zensical.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ site_dir = "site"
exclude_docs = """
tooling/
"""
extra_css = ["styles.css"]
nav = [
{ "Home" = "README.md" },
{ "Getting started" = [
Expand Down
Loading