Files
EdgeNode/internal/caches/open_file_pool.go

107 lines
2.0 KiB
Go
Raw Permalink Normal View History

2024-05-17 18:30:33 +08:00
// Copyright 2022 GoEdge goedge.cdn@gmail.com. All rights reserved.
2022-01-12 21:09:00 +08:00
package caches
import (
"github.com/TeaOSLab/EdgeNode/internal/utils/fasttime"
2022-01-12 21:09:00 +08:00
"github.com/TeaOSLab/EdgeNode/internal/utils/linkedlist"
)
type OpenFilePool struct {
c chan *OpenFile
2023-10-03 21:38:45 +08:00
linkItem *linkedlist.Item[*OpenFilePool]
2022-01-12 21:09:00 +08:00
filename string
version int64
2022-12-05 11:16:04 +08:00
isClosed bool
2023-10-11 21:51:05 +08:00
usedSize int64
2022-01-12 21:09:00 +08:00
}
func NewOpenFilePool(filename string) *OpenFilePool {
var pool = &OpenFilePool{
filename: filename,
c: make(chan *OpenFile, 1024),
version: fasttime.Now().UnixMilli(),
2022-01-12 21:09:00 +08:00
}
2023-10-03 21:38:45 +08:00
pool.linkItem = linkedlist.NewItem[*OpenFilePool](pool)
2022-01-12 21:09:00 +08:00
return pool
}
func (this *OpenFilePool) Filename() string {
return this.filename
}
2023-10-11 21:51:05 +08:00
func (this *OpenFilePool) Get() (resultFile *OpenFile, consumed bool, consumedSize int64) {
2022-12-05 11:16:04 +08:00
// 如果已经关闭,直接返回
if this.isClosed {
2023-10-11 21:51:05 +08:00
return nil, false, 0
2022-12-05 11:16:04 +08:00
}
2022-01-12 21:09:00 +08:00
select {
case file := <-this.c:
2022-12-05 10:46:44 +08:00
if file != nil {
2023-10-11 21:51:05 +08:00
this.usedSize -= file.size
2022-12-05 10:46:44 +08:00
err := file.SeekStart()
if err != nil {
_ = file.Close()
2023-10-11 21:51:05 +08:00
return nil, true, file.size
2022-12-05 10:46:44 +08:00
}
file.version = this.version
2022-01-12 21:09:00 +08:00
2023-10-11 21:51:05 +08:00
return file, true, file.size
2022-12-05 10:46:44 +08:00
}
2023-10-11 21:51:05 +08:00
return nil, false, 0
2022-01-12 21:09:00 +08:00
default:
2023-10-11 21:51:05 +08:00
return nil, false, 0
2022-01-12 21:09:00 +08:00
}
}
func (this *OpenFilePool) Put(file *OpenFile) bool {
2022-12-05 11:16:04 +08:00
// 如果已关闭,则不接受新的文件
if this.isClosed {
_ = file.Close()
return false
}
// 检查文件版本号
if this.version > 0 && file.version > 0 && file.version != this.version {
2022-01-12 21:09:00 +08:00
_ = file.Close()
return false
}
2022-12-05 11:16:04 +08:00
// 加入Pool
2022-01-12 21:09:00 +08:00
select {
case this.c <- file:
2023-10-11 21:51:05 +08:00
this.usedSize += file.size
2022-01-12 21:09:00 +08:00
return true
default:
// 多余的直接关闭
_ = file.Close()
return false
}
}
func (this *OpenFilePool) Len() int {
return len(this.c)
}
2023-10-11 21:51:05 +08:00
func (this *OpenFilePool) TotalSize() int64 {
return this.usedSize
}
2022-12-05 11:16:04 +08:00
func (this *OpenFilePool) SetClosing() {
this.isClosed = true
}
2022-01-12 21:09:00 +08:00
func (this *OpenFilePool) Close() {
2022-12-05 11:16:04 +08:00
this.isClosed = true
2022-01-12 21:09:00 +08:00
for {
select {
case file := <-this.c:
_ = file.Close()
default:
2022-12-05 11:16:04 +08:00
return
2022-01-12 21:09:00 +08:00
}
}
}