-
Notifications
You must be signed in to change notification settings - Fork 190
Fix the links to the examples project in the Chinese version of the README; add a close callback mechanism for sessions. #91
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
Merged
Merged
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
9b65fd2
修复中文版readme的examples工程跳转链接
6bbc2b5
为session增加closecallback机制用于断线时做一些回收操作
af7c6e6
整合test文件
f7fe83d
change desc to english
558c626
翻译注释,增加许可证
0d94634
Merge branch 'master' into mazheng
a51bf83
调整格式
ecef7cc
test file add License Header
a1fa804
invokeCloseCallbacks panic add stack info
c27bc00
采纳ai comment
f585a70
remove ai commets recover design
6391338
格式整理
5c5b156
funcname count change to len,change recover logic
63ab8bf
update readme
d1359ce
update readme
8a74d19
文档里说明handler key的参数类型要求
27e1af0
ai comment内容修改
7fb5dbb
unlock在defer中执行,增加cbnum来记录链表元素数量
aedd29e
增加iscompare方法对不可比较类型进行判断
8aeb952
修改文档描述
7585325
修改代码格式
a951232
gofmt
979da7b
调整文档
59ecd59
isclose放在unlock后
8200644
修复callback.go格式
c0ee5b7
doc描述修改
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,7 +18,71 @@ Additionally, you can manage heartbeat logic within the (Codec)OnCron method in | |
|
|
||
| If you're using WebSocket, you don't need to worry about heartbeat request/response, as Getty handles this task within session.go's (Session)handleLoop method by sending and receiving WebSocket ping/pong frames. Your responsibility is to check whether the WebSocket session has timed out or not within codec.go's (Codec)OnCron method using session.go's (Session)GetActive method. | ||
|
|
||
| For code examples, you can refer to https://github.com/AlexStocks/getty-examples. | ||
| For code examples, you can refer to [getty-examples](https://github.com/AlexStocks/getty-examples). | ||
|
|
||
| ## Callback System | ||
|
|
||
| Getty provides a robust callback system that allows you to register and manage callback functions for session lifecycle events. This is particularly useful for cleanup operations, resource management, and custom event handling. | ||
|
|
||
| ### Key Features | ||
|
|
||
| - **Thread-safe operations**: All callback operations are protected by mutex locks | ||
| - **Replace semantics**: Adding a callback with the same handler and key will replace the existing one | ||
| - **Panic safety**: Callback panics are properly handled and logged with stack traces | ||
| - **Ordered execution**: Callbacks are executed in the order they were added | ||
|
|
||
| ### Usage Example | ||
|
|
||
| ```go | ||
| // Add a close callback | ||
| session.AddCloseCallback("cleanup", "resources", func() { | ||
| // Cleanup resources when session closes | ||
| cleanupResources() | ||
| }) | ||
|
|
||
| // Remove a specific callback | ||
| session.RemoveCloseCallback("cleanup", "resources") | ||
|
|
||
| // Callbacks are automatically executed when the session closes | ||
| ``` | ||
|
|
||
| **Note**: Callbacks should be fast/non-blocking; move heavy work to separate goroutines to avoid delaying shutdown. | ||
|
|
||
| ### Callback Management | ||
|
|
||
| - **AddCloseCallback**: Register a callback to be executed when the session closes | ||
| - **RemoveCloseCallback**: Remove a previously registered callback | ||
| - **Thread Safety**: All operations are thread-safe and can be called concurrently | ||
|
|
||
|
Comment on lines
52
to
57
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Document comparable requirement for (handler, key). Add a note: “handler and key must be comparable (e.g., string/int/pointer). Passing maps/slices will cause a runtime error; convert to a stable identifier first.” 🤖 Prompt for AI Agents |
||
| ### Type Requirements | ||
|
|
||
| The `handler` and `key` parameters must be **comparable types** that support the `==` operator: | ||
|
|
||
| **✅ Supported types:** | ||
| - **Basic types**: `string`, `int`, `int8`, `int16`, `int32`, `int64`, `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `uintptr`, `float32`, `float64`, `bool`, `complex64`, `complex128` | ||
| - **Pointer types**: Pointers to any type (e.g., `*int`, `*string`, `*MyStruct`) | ||
| - **Interface types**: Interface types (compared by type and value) | ||
| - **Channel types**: Channel types (compared by channel identity) | ||
| - **Array types**: Arrays of comparable elements (e.g., `[3]int`, `[2]string`) | ||
| - **Struct types**: Structs where all fields are comparable types | ||
|
|
||
| **❌ Not supported (will cause compile errors):** | ||
| - `map` types (e.g., `map[string]int`) | ||
| - `slice` types (e.g., `[]int`, `[]string`) | ||
| - `func` types (e.g., `func()`, `func(int) string`) | ||
| - Structs containing non-comparable fields (maps, slices, functions) | ||
|
|
||
| **Examples:** | ||
| ```go | ||
| // ✅ Valid usage | ||
| session.AddCloseCallback("user", "cleanup", callback) | ||
| session.AddCloseCallback(123, "cleanup", callback) | ||
| session.AddCloseCallback(true, false, callback) | ||
|
|
||
| // ❌ Invalid usage (compile error) | ||
| session.AddCloseCallback(map[string]int{"a": 1}, "key", callback) | ||
| session.AddCloseCallback([]int{1, 2, 3}, "key", callback) | ||
| ``` | ||
|
|
||
| ## About network transmission in getty | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package getty | ||
AlexStocks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // callbackNode represents a node in the callback linked list | ||
| // Each node contains handler identifier, key, callback function and pointer to next node | ||
| type callbackNode struct { | ||
| handler any // Handler identifier, used to identify the source or type of callback | ||
| key any // Unique identifier key for callback, used in combination with handler | ||
| call func() // Actual callback function to be executed | ||
| next *callbackNode // Pointer to next node, forming linked list structure | ||
| } | ||
|
|
||
| // callbacks is a singly linked list structure for managing multiple callback functions | ||
| // Supports dynamic addition, removal and execution of callbacks | ||
| type callbacks struct { | ||
| first *callbackNode // Pointer to the first node of the linked list | ||
| last *callbackNode // Pointer to the last node of the linked list, used for quick addition of new nodes | ||
| } | ||
|
|
||
| // Add adds a new callback function to the callback linked list | ||
| // Parameters: | ||
| // - handler: Handler identifier, can be any type | ||
| // - key: Unique identifier key for callback, used in combination with handler | ||
| // - callback: Callback function to be executed, ignored if nil | ||
| // | ||
| // Note: If a callback with the same handler and key already exists, it will be replaced | ||
| func (t *callbacks) Add(handler, key any, callback func()) { | ||
| // Prevent adding empty callback function | ||
| if callback == nil { | ||
| return | ||
| } | ||
|
|
||
| // Check if a callback with the same handler and key already exists | ||
| for cb := t.first; cb != nil; cb = cb.next { | ||
ayamzh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if cb.handler == handler && cb.key == key { | ||
| // Replace existing callback | ||
| cb.call = callback | ||
| return | ||
| } | ||
| } | ||
|
|
||
| // Create new callback node | ||
| newItem := &callbackNode{handler, key, callback, nil} | ||
|
|
||
| if t.first == nil { | ||
| // If linked list is empty, new node becomes the first node | ||
| t.first = newItem | ||
| } else { | ||
| // Otherwise add new node to the end of linked list | ||
| t.last.next = newItem | ||
| } | ||
| // Update pointer to last node | ||
| t.last = newItem | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Remove removes the specified callback function from the callback linked list | ||
| // Parameters: | ||
| // - handler: Handler identifier of the callback to be removed | ||
| // - key: Unique identifier key of the callback to be removed | ||
| // | ||
| // Note: If no matching callback is found, this method has no effect | ||
| func (t *callbacks) Remove(handler, key any) { | ||
| var prev *callbackNode | ||
|
|
||
| // Traverse linked list to find the node to be removed | ||
| for callback := t.first; callback != nil; prev, callback = callback, callback.next { | ||
ayamzh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Found matching node | ||
| if callback.handler == handler && callback.key == key { | ||
| if t.first == callback { | ||
| // If it's the first node, update first pointer | ||
| t.first = callback.next | ||
| } else if prev != nil { | ||
| // If it's a middle node, update the next pointer of the previous node | ||
| prev.next = callback.next | ||
| } | ||
|
|
||
| if t.last == callback { | ||
| // If it's the last node, update last pointer | ||
| t.last = prev | ||
| } | ||
|
|
||
| // Return immediately after finding and removing | ||
| return | ||
| } | ||
| } | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // Invoke executes all registered callback functions in the linked list | ||
| // Executes each callback in the order they were added | ||
| // Note: If a callback function is nil, it will be skipped | ||
| // If a callback panics, it will be handled by the outer caller's panic recovery | ||
AlexStocks marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| func (t *callbacks) Invoke() { | ||
| // Traverse the entire linked list starting from the head node | ||
| for callback := t.first; callback != nil; callback = callback.next { | ||
| // Ensure callback function is not nil before executing | ||
| if callback.call != nil { | ||
| callback.call() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Len returns the number of callback functions in the linked list | ||
| // Return value: Total number of currently registered callback functions | ||
| func (t *callbacks) Len() int { | ||
ayamzh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var count int | ||
|
|
||
| // Traverse linked list to count | ||
| for callback := t.first; callback != nil; callback = callback.next { | ||
| count++ | ||
| } | ||
|
|
||
| return count | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doc vs code: Panic safety statement conflicts with implementation/tests.
Callbacks currently propagate panics; README says they’re recovered and logged. Align with the chosen behavior. I recommend adding recover in callbacks.Invoke (see suggested patch) and updating tests accordingly.
🤖 Prompt for AI Agents