-
Notifications
You must be signed in to change notification settings - Fork 321
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
89 additions
and
40 deletions.
There are no files selected for viewing
This file contains 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,63 @@ | ||
package common | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"github.com/openimsdk/tools/log" | ||
"runtime" | ||
"runtime/debug" | ||
"strings" | ||
"time" | ||
) | ||
|
||
var packet string | ||
|
||
func init() { | ||
build, ok := debug.ReadBuildInfo() | ||
if !ok { | ||
return | ||
} | ||
packet = build.Main.Path | ||
if packet != "" && !strings.HasSuffix(packet, "/") { | ||
packet += "/" | ||
} | ||
} | ||
|
||
type Cmd2Value struct { | ||
Cmd string | ||
Value any | ||
Caller string | ||
Ctx context.Context | ||
} | ||
|
||
func sendCmd(ch chan<- Cmd2Value, value Cmd2Value, timeout time.Duration) error { | ||
if value.Caller == "" { | ||
value.Caller = getFuncName() | ||
} | ||
if ch == nil { | ||
log.ZError(value.Ctx, "sendCmd chan is nil", ErrChanNil, "caller", value.Caller, "cmd", value.Cmd, "value", value.Value) | ||
return ErrChanNil | ||
} | ||
timer := time.NewTimer(timeout) | ||
defer timer.Stop() | ||
select { | ||
case ch <- value: | ||
log.ZInfo(value.Ctx, "sendCmd chan success", "caller", value.Caller, "cmd", value.Cmd, "value", value.Value) | ||
return nil | ||
case <-timer.C: | ||
log.ZError(value.Ctx, "sendCmd chan timeout", ErrTimeout, "caller", value.Caller, "cmd", value.Cmd, "value", value.Value) | ||
return ErrTimeout | ||
} | ||
} | ||
|
||
func getFuncName() string { | ||
pc, _, line, ok := runtime.Caller(3) | ||
if !ok { | ||
return "runtime.caller.failed" | ||
} | ||
name := runtime.FuncForPC(pc).Name() | ||
if packet != "" { | ||
name = strings.TrimPrefix(name, packet) | ||
} | ||
return fmt.Sprintf("%s:%d", name, line) | ||
} |
This file contains 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