Thanks to visit codestin.com
Credit goes to Github.com

Skip to content

Conversation

@ayamzh
Copy link

@ayamzh ayamzh commented Sep 23, 2025

What this PR does:

This PR enhances the Getty framework documentation by adding comprehensive explanations and examples for core components including Session, Server, and Options. The updates include:

  • Detailed Session documentation: Added explanations for SetPkgHandler, SetEventListener, SetCronPeriod methods with code examples
  • Server implementation guide: Added TCP server example code and configuration options
  • Framework architecture diagram: Added visual representation of the layered architecture
  • Active time update mechanism: Documented when GetActive() is updated (data reception, WebSocket ping/pong, but NOT TCP/UDP Send())
  • Data flow processing: Detailed sequence of PkgHandler.Read(), EventListener.OnMessage(), and PkgHandler.Write()
  • Concurrency model: Explained OnMessage parallel processing capabilities and task pool usage

The documentation now provides both English and Chinese versions with consistent content and improved formatting for better readability.

Which issue(s) this PR fixes:

Fixes #

Special notes for your reviewer:

  • All existing content in README files has been preserved without modification or deletion
  • Added comprehensive examples and explanations for core Getty framework concepts
  • Improved documentation structure with better formatting and visual diagrams
  • Both English (README.md) and Chinese (README_CN.md) versions have been updated consistently
  • Added practical TCP server example code for better understanding

Does this PR introduce a user-facing change?:

Enhanced Getty framework documentation with comprehensive Session, Server, and Options explanations, TCP server examples, architecture diagrams, and improved concurrency model documentation. Both English and Chinese versions updated.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Documentation**
  * Added a comprehensive Session management section to the English and Chinese READMEs.
  * Explains session lifecycle, configuration, active time/heartbeat, event handling, data flow (with diagrams), attributes, and I/O usage.
  * Provides practical examples for setting handlers/listeners, cron/heartbeat patterns, message callbacks, and timeouts.
  * Includes server/client configuration samples and a TCP server walkthrough to help integrate and manage sessions effectively.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai
Copy link

coderabbitai bot commented Sep 23, 2025

Walkthrough

Adds extensive README and README_CN documentation introducing a public Session interface, its methods, and usage patterns, including handlers, event listeners, cron/heartbeat, I/O, attributes, and lifecycle callbacks. No code files changed; content is explanatory with examples and flow descriptions.

Changes

Cohort / File(s) Summary
Docs: Session management (EN)
README.md
Adds a new “Session management” section documenting a Session interface extending Connection, enumerating lifecycle/config/handler/I/O/attribute/callback methods, plus examples for SetPkgHandler, SetEventListener, cron/heartbeat, data flow, and usage patterns.
Docs: Session management (ZH-CN)
README_CN.md
Adds a comprehensive “Session 会话管理” section covering the Session interface, method signatures, event/handler setup, heartbeat/活跃时间, data flow diagrams/explanations, and full examples for server/client configuration and callbacks.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Session
  participant Reader
  participant Writer
  participant PkgHandler as ReadWriter
  participant EventListener
  participant Cron as OnCron Timer

  Note over Session: Initialization
  Client->>Session: SetPkgHandler(ReadWriter)
  Client->>Session: SetEventListener(EventListener)
  Client->>Session: SetCronPeriod(n), SetWaitTime(d)

  rect rgba(200,230,255,0.25)
    Note over Reader,Session: Incoming data
    Client-->>Session: Bytes
    Session->>Reader: Read()
    Reader->>PkgHandler: Decode(bytes) -> pkg
    PkgHandler-->>Session: pkg
    Session->>EventListener: OnMessage(pkg)
  end

  rect rgba(200,255,200,0.25)
    Note over Session,Writer: Outgoing data
    Client->>Session: WritePkg(pkg, timeout)
    Session->>PkgHandler: Encode(pkg) -> bytes
    PkgHandler-->>Writer: bytes
    Writer-->>Client: Send(bytes)
  end

  rect rgba(255,240,200,0.35)
    Note over Cron,Session: Heartbeat / Cron
    Cron-->>Session: OnCron(tick)
    Session->>EventListener: OnCron()
    alt idle timeout
      Session->>EventListener: OnSessionIdle/Close
      Session--x Client: Close()
    end
  end

  Note over Session: Attributes
  Client->>Session: SetAttribute(k, v) / GetAttribute(k)

  Note over Session: Close callbacks
  Client->>Session: AddCloseCallback(h, key, fn)
  Session-->>Client: RemoveCloseCallback(h, key)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested reviewers

  • AlexStocks
  • marsevilspirit
  • No-SilverBullet

Poem

A rabbit taps README with tidy paws,
Sketching Sessions, timers, and callback laws.
Packets hop in, events leap out,
Heartbeats thump—no room for doubt.
Attributes tucked like carrots in code,
OnCron chimes softly along the road.
Hippity-hop—docs shipped, payloads flowed! 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately and concisely summarizes the primary change by stating that comprehensive documentation for Session, Server, and Options was added, which matches the README/README_CN additions and the PR objectives; it is specific, brief, and directly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@ayamzh ayamzh closed this Sep 23, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (6)
README_CN.md (3)

361-373: 为 ASCII 图添加 fenced code 语言标记以满足 MD040

为图形代码块指定语言,有利于 markdownlint 通过(可用 text)。

-```
+```text
@@
-```
+```text

Also applies to: 695-713


50-50: 将强调行改为小节标题以满足 MD036

把“注意”从加粗改为四级标题,便于结构化导航并满足 linter。

-**注意**:在会话关闭期间,回调在专用 goroutine 中顺序执行以保持添加顺序,带有 defer/recover 来记录 panic 而不让它们逃逸出关闭路径。
+#### 注意
+在会话关闭期间,回调在专用 goroutine 中顺序执行以保持添加顺序,带有 defer/recover 来记录 panic 而不让它们逃逸出关闭路径。

253-269: 内部类型示例可能引起混淆(gettyTCPConn/gettyWSConn)

示例引用内部未导出类型/方法名。建议标注为“示意代码”或改用更抽象的伪代码以免读者误以为为公共 API。

建议在代码块前添加一句:“以下为简化示意代码,用于说明活跃时间更新点,非公共 API。”

README.md (3)

361-373: Add fenced code language for ASCII diagrams (MD040)

Specify a language like text to satisfy markdownlint.

-```
+```text
@@
-```
+```text

Also applies to: 695-713


50-50: Use a subheading instead of bold for “Note” (MD036)

Improves structure and passes markdownlint.

-**Note**: During session shutdown, callbacks are executed sequentially in a dedicated goroutine to preserve add-order, with defer/recover to log panics without letting them escape the close path.
+#### Note
+During session shutdown, callbacks are executed sequentially in a dedicated goroutine to preserve add-order, with defer/recover to log panics without letting them escape the close path.

253-269: Examples reference internal types (gettyTCPConn/gettyWSConn)

These look like internal, unexported symbols. Label as illustrative pseudo-code or refactor to generic examples to prevent users from assuming public availability.

Add a short note before the snippet: “The following snippets use internal types for illustration only; APIs shown are not public.”

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a282367 and f15f9a2.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • README_CN.md (1 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.18.1)
README.md

153-153: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


186-186: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


226-226: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


249-249: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


274-274: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


293-293: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


312-312: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


339-339: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


361-361: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


362-362: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


695-695: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🔇 Additional comments (2)
README.md (1)

103-129: Session already exposes GetActive/UpdateActive via embedded Connection — update docs instead of the interface

Session embeds Connection; GetActive() and UpdateActive() are defined on Connection (transport/connection.go:60–62) and are therefore available on Session (transport/session.go:75–77). Clarify this in README under "Key Methods" rather than adding duplicate methods to Session.

Likely an incorrect or invalid review comment.

README_CN.md (1)

103-129: 说明:GetActive/UpdateActive 来自 Connection — 在 README 中说明或显式列出

Session 在代码里嵌入了 Connection(transport/connection.go 定义了 GetActive() time.Time 和 UpdateActive()),示例中对 session.GetActive()/UpdateActive() 的调用是有效的;请在 README_CN.md 中注明这些方法来自 Connection 或将它们显式加入 Session 接口清单。

Likely an incorrect or invalid review comment.

Comment on lines +247 to +274
#### 活跃时间更新机制

**自动活跃时间更新**
```go
// Getty 在以下情况下自动更新会话活跃时间:
// 1. 从网络接收数据时
func (t *gettyTCPConn) recv(p []byte) (int, error) {
// ... 接收数据逻辑
t.UpdateActive() // 自动调用 - 更新 GetActive() 值
return length, err
}

// 2. WebSocket ping/pong 帧(仅 WebSocket)
func (w *gettyWSConn) handlePing(message string) error {
w.UpdateActive() // 收到 ping 时更新
return w.writePong([]byte(message))
}

func (w *gettyWSConn) handlePong(string) error {
w.UpdateActive() // 收到 pong 时更新
return nil
}

// 注意:TCP/UDP 的 Send() 方法不会自动调用 UpdateActive()
// 只有数据接收和 WebSocket ping/pong 会更新活跃时间
```

**服务端心跳检测**
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix contradictions about when GetActive() is updated

The section mixes “receive-only + WS ping/pong” with “receive/send”. Align wording to avoid misleading heartbeat/idle logic.

Apply these edits:

@@
-// 注意:TCP/UDP 的 Send() 方法不会自动调用 UpdateActive()
-// 只有数据接收和 WebSocket ping/pong 会更新活跃时间
+// 注意:TCP/UDP 的 Send() 方法不会自动调用 UpdateActive()
+// 只有【数据接收】和【WebSocket ping/pong】会更新活跃时间
@@
-    // 获取最后活跃时间(在数据接收/发送时自动更新)
+    // 获取最后活跃时间(仅在数据接收与 WebSocket ping/pong 时自动更新)
@@
-// 00:00:10 - 服务端发送响应,GetActive() = 2024-01-01 10:00:10
+// 00:00:10 - 服务端发送响应(GetActive() 不变;发送不会更新活跃时间)
@@
-- **自动更新**:活跃时间在数据接收/发送时自动更新
+- **自动更新**:活跃时间仅在【数据接收】与【WebSocket ping/pong】时自动更新(TCP/UDP 发送不会更新)

Also applies to: 282-290, 293-309

🤖 Prompt for AI Agents
In README_CN.md around lines 247 to 274 (also review and update similar wording
in 282-290 and 293-309), the text contradicts when GetActive() is updated by
stating both "receive-only + WS ping/pong" and implying Send() triggers updates;
update the prose to consistently state that only data reception and WebSocket
ping/pong update the session active timestamp (GetActive()), clarify that
Send()/TCP/UDP send methods do not call UpdateActive(), and adjust examples and
notes to remove any wording that suggests sending refreshes activity so the
heartbeat/idle logic is not misleading.

Comment on lines +658 to +663
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5)
session.SetWaitTime(time.Second * 3)

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

SetCronPeriod 单位不一致(毫秒 vs 示例为 5)

上文定义为“毫秒”,这里示例传入 5,读者会理解为 5ms,而前文示例使用 5000ms(5 秒)。请统一。

Apply this change if单位确认为毫秒:

-    session.SetCronPeriod(5)
+    session.SetCronPeriod(5000) // 5s in milliseconds

若单位实际为秒,请在“SetCronPeriod - 心跳配置”小节修改为“单位为秒”,并调整前文 5000 的示例。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5)
session.SetWaitTime(time.Second * 3)
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5000) // 5s in milliseconds
session.SetWaitTime(time.Second * 3)
🤖 Prompt for AI Agents
In README_CN.md around lines 658-663, the SetCronPeriod unit is inconsistent:
the docs earlier state “毫秒” but the example here uses 5 (ambiguous); verify the
actual SetCronPeriod unit in code, then update the documentation and examples to
be consistent — if the unit is milliseconds, change this example to
SetCronPeriod(5000) (or annotate as 5000ms) and keep the earlier 5000ms sample;
if the unit is seconds, change the “SetCronPeriod - 心跳配置” section text to state
the unit is 秒 and update the earlier 5000 example to 5 (or adjust examples
accordingly) so all references match.

Comment on lines +247 to +274
#### Active Time Update Mechanism

**Automatic Active Time Updates**
```go
// Getty automatically updates session active time when:
// 1. Receiving data from network
func (t *gettyTCPConn) recv(p []byte) (int, error) {
// ... receive data logic
t.UpdateActive() // Automatically called - updates GetActive() value
return length, err
}

// 2. WebSocket ping/pong frames (WebSocket only)
func (w *gettyWSConn) handlePing(message string) error {
w.UpdateActive() // Updates when receiving ping
return w.writePong([]byte(message))
}

func (w *gettyWSConn) handlePong(string) error {
w.UpdateActive() // Updates when receiving pong
return nil
}

// Note: TCP/UDP Send() methods do NOT automatically call UpdateActive()
// Only data reception and WebSocket ping/pong update active time
```

**Server-Side Heartbeat Detection**
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Resolve contradictions about when GetActive() updates

Docs alternate between “receive-only + WS ping/pong” and “receive/send”. Align wording to avoid incorrect idle/timeout logic.

Apply:

@@
-// Note: TCP/UDP Send() methods do NOT automatically call UpdateActive()
-// Only data reception and WebSocket ping/pong update active time
+// Note: TCP/UDP Send() methods do NOT automatically call UpdateActive()
+// Only data reception and WebSocket ping/pong update active time
@@
-    // Get last active time (automatically updated on data receive/send)
+    // Get last active time (updated only on data reception and WebSocket ping/pong)
@@
-// 00:00:10 - Server sends response, GetActive() = 2024-01-01 10:00:10
+// 00:00:10 - Server sends response (GetActive() unchanged; send does not update)
@@
-- **Automatic Updates**: Active time is updated automatically on data receive/send
+- **Automatic Updates**: Active time updates on data reception and WebSocket ping/pong (not on TCP/UDP send)

Also applies to: 282-290, 293-309

🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

249-249: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


274-274: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🤖 Prompt for AI Agents
In README.md around lines 247-274 (also apply same change at 282-290 and
293-309): the docs currently contradict whether GetActive() is updated on send
versus receive; update the wording and examples to consistently state that
UpdateActive()/GetActive() are updated only on data reception and WebSocket
ping/pong (not on TCP/UDP Send), remove any phrasing that implies sends
auto-update active time, clarify with a single note that Send() methods do NOT
call UpdateActive() and, if desired, show a brief instruction to call
UpdateActive() manually after sending to mark activity.

Comment on lines +658 to +663
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5)
session.SetWaitTime(time.Second * 3)

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

SetCronPeriod unit mismatch (ms vs example value 5)

Section defines milliseconds; this example passes 5 (likely 5ms). Make consistent.

-    session.SetCronPeriod(5)
+    session.SetCronPeriod(5000) // 5s in milliseconds

If the real unit is seconds, update the earlier section to say “seconds” and adjust the 5000ms example accordingly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5)
session.SetWaitTime(time.Second * 3)
session.SetMaxMsgLen(4096)
session.SetReadTimeout(time.Second * 10)
session.SetWriteTimeout(time.Second * 10)
session.SetCronPeriod(5000) // 5s in milliseconds
session.SetWaitTime(time.Second * 3)
🤖 Prompt for AI Agents
In README.md around lines 658 to 663, the SetCronPeriod call conflicts with the
earlier statement that units are milliseconds — the example uses 5 which is
ambiguous; either change the docs to state the period is in seconds and update
the illustrative value to match (e.g., show a 5-second example and mention
seconds), or keep the docs as milliseconds and change the example value to 5000
to reflect 5000ms; update the surrounding text so the units and the example
value are consistent.

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