Files
gf/os/gspath/gspath.go
Lance Add d8a173d9f0 feat(instance): migrate instance containers to type-safe generics (#4617)
### 变更说明

本次重构将项目中用于**实例管理的容器**从 `StrAnyMap`/`IntAnyMap` 迁移到类型安全的泛型实现
`KVMapWithChecker`,同时将相关的 `glist.List` 和 `gqueue.Queue`
替换为对应的泛型版本,以提高实例管理的类型安全性。并且减少原先代码中的大量类型断言,提高性能。

### 前因

目前`goframe`中大量使用了包含`any`的容器,然后通过断言去转换类型,麻烦且影响性能,尤其是对`gdb/gredis/glog`等需要高频获取`instance`实例的组件影响较大。最近几个版本中gf完成了数据结构容器的泛型化改造,以及我最近解决了其中几个泛型容器对于`typed
nil`过滤的问题,所以可以逐步迁移这些实例容器到泛型容器,减少断言优化性能

### 主要改进

#### 1. 实例容器泛型化

以下模块的实例管理容器已迁移到泛型实现:

**核心实例管理**:
- `database/gdb`: 数据库实例容器 → `KVMap[string, DB]`
- `database/gredis`: Redis 实例容器 → `KVMap[string, *Redis]`
- `database/gredis`: Redis 配置容器 → `KVMap[string, *Config]`
- `os/gcfg`: 配置实例容器 → `KVMap[string, *Config]`
- `os/glog`: 日志实例容器 → `KVMap[string, *Logger]`
- `os/gview`: 视图实例容器 → `KVMap[string, *View]`
- `i18n/gi18n`: 国际化实例容器 → `KVMap[string, *Manager]`

**网络服务实例**:
- `net/ghttp`: HTTP 服务器容器 → `KVMap[string, *Server]`
- `net/gtcp`: TCP 服务器容器 → `KVMap[any, *Server]`
- `net/gudp`: UDP 服务器容器 → `KVMap[string, *Server]`

**其他实例容器**:
- `os/gres`: 资源实例容器 → `KVMap[string, *Resource]`
- `os/gfpool`: 文件池容器 → `KVMap[string, *Pool]`
- `os/gspath`: 路径搜索容器 → `KVMap[string, *SPath]`
- `net/gtcp`: 连接池容器 → `KVMap[string, *gpool.Pool]`

#### 2. 相关数据结构泛型化

- `os/gfsnotify`: 回调列表 → `TList[*Callback]`,事件队列 → `TQueue[*Event]`
- `os/grpool`: 任务队列 → `TList[*localPoolItem]`
- `os/gcache`: 事件队列 → `TList[*adapterMemoryEvent]`
- `net/ghttp`: 解析项列表 → `TList[*HandlerItemParsed]`
- `os/gproc`: 消息队列 → `TQueue[*MsgRequest]`
- `os/gmlock`: 锁映射 → `KVMap[string, *sync.RWMutex]`

### 技术实现

1. **引入检查器函数**: 为每个实例容器添加 `checker` 函数用于空值检测
2. **消除类型断言**: 实例获取时无需 `v.(*Type)` 转换
3. **明确函数签名**: `GetOrSetFuncLock` 的回调从 `func() any` 改为 `func() T`

### 使用示例

#### 实例容器的变更

**变更前**:
```go
// 旧的实例管理方式
var instances = gmap.NewStrAnyMap(true)

func Instance(name string) *Logger {
    v := instances.GetOrSetFuncLock(name, func() any {
        return New()
    })
    return v.(*Logger)  // 需要类型断言
}
```


**变更后**:
```go
// 新的泛型实例容器
var (
    checker   = func(v *Logger) bool { return v == nil }
    instances = gmap.NewKVMapWithChecker[string, *Logger](checker, true)
)

func Instance(name string) *Logger {
    return instances.GetOrSetFuncLock(name, New)  // 直接返回,无需断言
}
```


#### 队列容器的变更

**变更前**:
```go
// 旧的队列方式
events := gqueue.New()
events.Push(&Event{Path: "/tmp/file"})

if v := events.Pop(); v != nil {
    event := v.(*Event)  // 需要类型断言
    handleEvent(event)
}
```


**变更后**:
```go
// 新的泛型队列
events := gqueue.NewTQueue[*Event]()
events.Push(&Event{Path: "/tmp/file"})

if event := events.Pop(); event != nil {
    handleEvent(event)  // event 已是 *Event 类型
}
```


### 收益

-  **编译时类型安全**: 实例容器的类型错误在编译期捕获
-  **消除运行时断言**: 避免类型断言带来的 panic 风险
-  **提升代码可读性**: 实例管理逻辑更清晰
-  **改善开发体验**: IDE 类型提示和代码补全更准确

### 性能权衡

**编译时**:
- 泛型实例化会增加编译时间和二进制体积
- 预估编译时间增加 5-15%,二进制体积增加约 1-2MB

**运行时**:
- 减少类型断言的反射开销
- 提升实例获取等热点路径的性能
2026-01-16 15:23:13 +08:00

256 lines
8.0 KiB
Go

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gspath implements file index and search for folders.
//
// It searches file internally with high performance in order by the directory adding sequence.
// Note that:
// If caching feature enabled, there would be a searching delay after adding/deleting files.
package gspath
import (
"context"
"os"
"sort"
"strings"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/text/gstr"
)
// SPath manages the path searching feature.
type SPath struct {
paths *garray.StrArray // The searching directories array.
cache *gmap.StrStrMap // Searching cache map, it is not enabled if it's nil.
}
// SPathCacheItem is a cache item for searching.
type SPathCacheItem struct {
path string // Absolute path for file/dir.
isDir bool // Is directory or not.
}
var (
// checker is the checking function for checking the value is nil or not.
checker = func(v *SPath) bool { return v == nil }
// Path to searching object mapping, used for instance management.
pathsMap = gmap.NewKVMapWithChecker[string, *SPath](checker, true)
)
// New creates and returns a new path searching manager.
func New(path string, cache bool) *SPath {
sp := &SPath{
paths: garray.NewStrArray(true),
}
if cache {
sp.cache = gmap.NewStrStrMap(true)
}
if len(path) > 0 {
_, _ = sp.Add(path)
}
return sp
}
// Get creates and returns an instance of searching manager for given path.
// The parameter `cache` specifies whether using cache feature for this manager.
// If cache feature is enabled, it asynchronously and recursively scans the path
// and updates all sub files/folders to the cache using package gfsnotify.
func Get(root string, cache bool) *SPath {
if root == "" {
root = "/"
}
return pathsMap.GetOrSetFuncLock(root, func() *SPath {
return New(root, cache)
})
}
// Search searches file `name` under path `root`.
// The parameter `root` should be an absolute path. It will not automatically
// convert `root` to absolute path for performance reason.
// The optional parameter `indexFiles` specifies the searching index files when the result is a directory.
// For example, if the result `filePath` is a directory, and `indexFiles` is [index.html, main.html], it will also
// search [index.html, main.html] under `filePath`. It returns the absolute file path if any of them found,
// or else it returns `filePath`.
func Search(root string, name string, indexFiles ...string) (filePath string, isDir bool) {
return Get(root, false).Search(name, indexFiles...)
}
// SearchWithCache searches file `name` under path `root` with cache feature enabled.
// The parameter `root` should be an absolute path. It will not automatically
// convert `root` to absolute path for performance reason.
// The optional parameter `indexFiles` specifies the searching index files when the result is a directory.
// For example, if the result `filePath` is a directory, and `indexFiles` is [index.html, main.html], it will also
// search [index.html, main.html] under `filePath`. It returns the absolute file path if any of them found,
// or else it returns `filePath`.
func SearchWithCache(root string, name string, indexFiles ...string) (filePath string, isDir bool) {
return Get(root, true).Search(name, indexFiles...)
}
// Set deletes all other searching directories and sets the searching directory for this manager.
func (sp *SPath) Set(path string) (realPath string, err error) {
realPath = gfile.RealPath(path)
if realPath == "" {
realPath, _ = sp.Search(path)
if realPath == "" {
realPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + path)
}
}
if realPath == "" {
return realPath, gerror.NewCodef(gcode.CodeInvalidParameter, `path "%s" does not exist`, path)
}
// The set path must be a directory.
if gfile.IsDir(realPath) {
realPath = strings.TrimRight(realPath, gfile.Separator)
if sp.paths.Search(realPath) != -1 {
for _, v := range sp.paths.Slice() {
sp.removeMonitorByPath(v)
}
}
intlog.Print(context.TODO(), "paths clear:", sp.paths)
sp.paths.Clear()
if sp.cache != nil {
sp.cache.Clear()
}
sp.paths.Append(realPath)
sp.updateCacheByPath(realPath)
sp.addMonitorByPath(realPath)
return realPath, nil
} else {
return "", gerror.NewCode(gcode.CodeInvalidParameter, path+" should be a folder")
}
}
// Add adds more searching directory to the manager.
// The manager will search file in added order.
func (sp *SPath) Add(path string) (realPath string, err error) {
realPath = gfile.RealPath(path)
if realPath == "" {
realPath, _ = sp.Search(path)
if realPath == "" {
realPath = gfile.RealPath(gfile.Pwd() + gfile.Separator + path)
}
}
if realPath == "" {
return realPath, gerror.NewCodef(gcode.CodeInvalidParameter, `path "%s" does not exist`, path)
}
// The added path must be a directory.
if gfile.IsDir(realPath) {
// fmt.Println("gspath:", realPath, sp.paths.Search(realPath))
// It will not add twice for the same directory.
if sp.paths.Search(realPath) < 0 {
realPath = strings.TrimRight(realPath, gfile.Separator)
sp.paths.Append(realPath)
sp.updateCacheByPath(realPath)
sp.addMonitorByPath(realPath)
}
return realPath, nil
} else {
return "", gerror.NewCode(gcode.CodeInvalidParameter, path+" should be a folder")
}
}
// Search searches file `name` in the manager.
// The optional parameter `indexFiles` specifies the searching index files when the result is a directory.
// For example, if the result `filePath` is a directory, and `indexFiles` is [index.html, main.html], it will also
// search [index.html, main.html] under `filePath`. It returns the absolute file path if any of them found,
// or else it returns `filePath`.
func (sp *SPath) Search(name string, indexFiles ...string) (filePath string, isDir bool) {
// No cache enabled.
if sp.cache == nil {
sp.paths.LockFunc(func(array []string) {
path := ""
for _, v := range array {
path = gfile.Join(v, name)
if stat, err := os.Stat(path); stat != nil && !os.IsNotExist(err) {
path = gfile.Abs(path)
// Security check: the result file path must be under the searching directory.
if len(path) >= len(v) && path[:len(v)] == v {
filePath = path
isDir = stat.IsDir()
break
}
}
}
})
if len(indexFiles) > 0 && isDir {
if name == "/" {
name = ""
}
path := ""
for _, file := range indexFiles {
path = filePath + gfile.Separator + file
if gfile.Exists(path) {
filePath = path
isDir = false
break
}
}
}
return
}
// Using cache feature.
name = sp.formatCacheName(name)
if v := sp.cache.Get(name); v != "" {
filePath, isDir = sp.parseCacheValue(v)
if len(indexFiles) > 0 && isDir {
if name == "/" {
name = ""
}
for _, file := range indexFiles {
if v = sp.cache.Get(name + "/" + file); v != "" {
return sp.parseCacheValue(v)
}
}
}
}
return
}
// Remove deletes the `path` from cache files of the manager.
// The parameter `path` can be either an absolute path or just a relative file name.
func (sp *SPath) Remove(path string) {
if sp.cache == nil {
return
}
if gfile.Exists(path) {
for _, v := range sp.paths.Slice() {
name := gstr.Replace(path, v, "")
name = sp.formatCacheName(name)
sp.cache.Remove(name)
}
} else {
name := sp.formatCacheName(path)
sp.cache.Remove(name)
}
}
// Paths returns all searching directories.
func (sp *SPath) Paths() []string {
return sp.paths.Slice()
}
// AllPaths returns all paths cached in the manager.
func (sp *SPath) AllPaths() []string {
if sp.cache == nil {
return nil
}
paths := sp.cache.Keys()
if len(paths) > 0 {
sort.Strings(paths)
}
return paths
}
// Size returns the count of the searching directories.
func (sp *SPath) Size() int {
return sp.paths.Len()
}