Skip to content

⚡ Bolt: 디렉토리 순회 시 CSS 해시 계산 최적화 - #323

Closed
seonghobae wants to merge 2 commits into
masterfrom
bolt/optimize-css-hashing-17071118150460386097
Closed

⚡ Bolt: 디렉토리 순회 시 CSS 해시 계산 최적화#323
seonghobae wants to merge 2 commits into
masterfrom
bolt/optimize-css-hashing-17071118150460386097

Conversation

@seonghobae

@seonghobae seonghobae commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

💡 What:
main.ktprocess_dir 내부에 선언되어 있던 cssContent (정적 문자열) 및 styleHash (SHA-256 해시 연산 결과) 변수들을 파일 최상위(Top-level) 수준의 internal val로 추출했습니다.

🎯 Why:
기존 코드에서는 디렉토리를 순회하며 process_dir 함수가 호출될 때마다 동일한 거대한 CSS 문자열이 새로 할당되고, CPU 집약적인 무거운 SHA-256 해시 연산이 매번 중복해서 실행되는 성능 병목 현상이 있었습니다. 애플리케이션 수명 주기 동안 변하지 않는 값이므로 한 번만 계산하도록 캐싱(최상위 속성으로 이동)하는 것이 효율적입니다.

📊 Impact:
디렉토리 크롤링 시 각 디렉토리 처리마다 발생하던 문자열 메모리 할당 및 MessageDigest 객체 생성/해시 연산을 애플리케이션 시작 시 단 1회로 줄여, 파일 트리가 크고 깊을수록 전체 실행 시간이 크게 단축되고 GC 오버헤드가 감소합니다.

🔬 Measurement:

  • 추출된 변수의 상태를 검증하기 위해 MainTest.kttestCssTopLevelPropertiesCoverage를 추가했습니다.
  • jacocoTestReport를 통해 INSTRUCTION 커버리지가 100%를 유지함을 확인했습니다.

PR created automatically by Jules for task 17071118150460386097 started by @seonghobae

Summary by CodeRabbit

  • 성능 개선

    • 여러 디렉터리를 처리할 때 공통 CSS와 스타일 해시를 재사용하여 처리 성능을 향상했습니다.
    • 생성되는 HTML의 인라인 스타일과 CSS 구조를 안정적으로 유지합니다.
  • 테스트

    • CSS 글꼴 설정, SHA-256 기반 스타일 해시, HTML 내 스타일 삽입을 검증하는 테스트를 추가했습니다.

- `main.kt`의 `process_dir` 내에 있던 정적 문자열 `cssContent`와 무거운 `SHA-256` 해시 계산(`styleHash`)을 파일 최상위(Top-level) 속성으로 분리하여 디렉토리마다 발생하던 반복적인 메모리 할당 및 연산 오버헤드 제거
- `MainTest.kt`에 `testCssTopLevelPropertiesCoverage` 테스트를 추가하여 추출된 최상위 속성들에 대한 테스트 커버리지 100% 유지
- `.jules/bolt.md`에 최적화 학습 내용(한국어) 기록 추가
@google-labs-jules

Copy link
Copy Markdown

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

정적 CSS 콘텐츠, SHA-256 스타일 해시 및 인라인 스타일을 process_dir 외부의 파일 최상위 속성으로 이동했습니다. CSS 생성 결과와 HTML 스타일 삽입을 검증하는 테스트를 추가했습니다.

Changes

CSS 값 재사용

Layer / File(s) Summary
CSS 값의 파일 수준 초기화
.jules/bolt.md, src/main/kotlin/html4tree/main.kt
cssContent, styleHash, css를 파일 최상위 internal 속성으로 이동했습니다. process_dir는 해당 값을 재사용합니다.
CSS 생성 결과 검증
src/test/kotlin/html4tree/MainTest.kt
CSS의 font-family, SHA-256 해시 형식, <style> 요소 및 CSS 본문 삽입을 검증합니다.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed 제목은 디렉터리 순회 중 CSS 해시 계산 최적화라는 PR의 주요 변경 사항을 명확하고 간결하게 설명합니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt/optimize-css-hashing-17071118150460386097

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/test/kotlin/html4tree/MainTest.kt (1)

32-38: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

styleHash와 실제 CSS 본문을 정확히 비교하세요.

Line [35]는 sha256- 접두사만 검증합니다. 잘못된 해시 값과 <style> 본문의 추가 공백을 감지하지 못합니다. 태그 사이의 본문을 추출한 뒤 SHA-256을 계산하고 styleHash와 정확히 비교하세요. cssContent와 추출한 본문도 동일한지 확인하세요.

수정 예시
         assertTrue(cssContent.contains("font-family:"))
-        assertTrue(styleHash.startsWith("sha256-"))
         assertTrue(css.contains("<style>"))
         assertTrue(css.contains(cssContent))
+        val styleBody = css.substringAfter("<style>").substringBefore("</style>")
+        assertEquals(cssContent, styleBody)
+        val expectedHash = "sha256-" + java.util.Base64.getEncoder()
+            .encodeToString(
+                java.security.MessageDigest.getInstance("SHA-256")
+                    .digest(styleBody.toByteArray(Charsets.UTF_8))
+            )
+        assertEquals(expectedHash, styleHash)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/test/kotlin/html4tree/MainTest.kt` around lines 32 - 38,
testCssTopLevelPropertiesCoverage에서 sha256- 접두사만 확인하지 말고, <style> 태그 사이의 실제 CSS
본문을 추출해 SHA-256을 계산한 값과 styleHash를 정확히 비교하세요. 또한 추출한 본문이 cssContent와 완전히 동일한지
검증해 본문 내 추가 공백이나 잘못된 해시를 감지하도록 수정하세요.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/kotlin/html4tree/main.kt`:
- Around line 313-318: Update the `css` template and `styleHash` calculation in
`main.kt` so the SHA-256 input exactly matches the bytes between the `<style>`
tags, with no added newline or indentation around `cssContent`; then update the
relevant `MainTest` assertion to hash the extracted tag body and verify it
matches `styleHash`.

---

Nitpick comments:
In `@src/test/kotlin/html4tree/MainTest.kt`:
- Around line 32-38: testCssTopLevelPropertiesCoverage에서 sha256- 접두사만 확인하지 말고,
<style> 태그 사이의 실제 CSS 본문을 추출해 SHA-256을 계산한 값과 styleHash를 정확히 비교하세요. 또한 추출한 본문이
cssContent와 완전히 동일한지 검증해 본문 내 추가 공백이나 잘못된 해시를 감지하도록 수정하세요.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 93574786-a9ba-456d-b4b4-7b3e4af60268

📥 Commits

Reviewing files that changed from the base of the PR and between a32b065 and 161e92f.

📒 Files selected for processing (3)
  • .jules/bolt.md
  • src/main/kotlin/html4tree/main.kt
  • src/test/kotlin/html4tree/MainTest.kt

Comment on lines +313 to 318
internal val styleHash = "sha256-" + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(cssContent.toByteArray(Charsets.UTF_8)))

val css = """
internal val css = """
<style>
${cssContent} </style>
"""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

CSP 해시와 실제 <style> 본문을 일치시키세요.

Line [313]은 cssContent만 SHA-256으로 계산합니다. 그러나 Line [315]-[318]은 <style> 태그 안에 cssContent 앞의 개행과 뒤의 공백을 추가합니다. CSP는 해시가 실제 인라인 스타일 블록과 일치할 때만 스타일을 허용합니다. 공백도 해시 입력에 포함됩니다. (w3.org)

현재 생성된 HTML에서는 CSS가 차단될 수 있습니다. css가 태그 사이에 cssContent만 포함하도록 구성하세요. src/test/kotlin/html4tree/MainTest.kt의 테스트도 태그 사이 본문을 해시하여 이 조건을 검증해야 합니다.

수정 예시
 internal val css = """
               <style>
-${cssContent}              </style>
+${cssContent}</style>
               """
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/kotlin/html4tree/main.kt` around lines 313 - 318, Update the `css`
template and `styleHash` calculation in `main.kt` so the SHA-256 input exactly
matches the bytes between the `<style>` tags, with no added newline or
indentation around `cssContent`; then update the relevant `MainTest` assertion
to hash the extracted tag body and verify it matches `styleHash`.

Copy link
Copy Markdown
Collaborator Author

Closing as superseded by #362. Both hoist the same immutable CSS and SHA-256 work out of process_dir; #362 is the newer clean protected-base implementation, keeps the values private rather than expanding the module-visible surface for test access, and its exact-head CI, Security Scan, and Semgrep have passed.

@seonghobae seonghobae closed this Aug 5, 2026
@google-labs-jules

Copy link
Copy Markdown

Closing as superseded by #362. Both hoist the same immutable CSS and SHA-256 work out of process_dir; #362 is the newer clean protected-base implementation, keeps the values private rather than expanding the module-visible surface for test access, and its exact-head CI, Security Scan, and Semgrep have passed.

Understood. Acknowledging that this work is superseded by #362 and stopping work on this task.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant