repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/rangereader_test.go | core/filex/rangereader_test.go | package filex
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
)
func TestRangeReader(t *testing.T) {
const text = `hello
world`
file, err := fs.TempFileWithText(text)
assert.Nil(t, err)
defer func() {
file.Close()
os.Remove(file.Name())
}()
reader := NewRangeReader(file, 5, 8)
buf := make([]byte, 10)
n, err := reader.Read(buf)
assert.Nil(t, err)
assert.Equal(t, 3, n)
assert.Equal(t, `
wo`, string(buf[:n]))
}
func TestRangeReader_OutOfRange(t *testing.T) {
const text = `hello
world`
file, err := fs.TempFileWithText(text)
assert.Nil(t, err)
defer func() {
file.Close()
os.Remove(file.Name())
}()
reader := NewRangeReader(file, 50, 8)
buf := make([]byte, 10)
_, err = reader.Read(buf)
assert.NotNil(t, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/file.go | core/filex/file.go | package filex
import (
"io"
"os"
)
const bufSize = 1024
// FirstLine returns the first line of the file.
func FirstLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return firstLine(file)
}
// LastLine returns the last line of the file.
func LastLine(filename string) (string, error) {
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
return lastLine(filename, file)
}
func firstLine(file *os.File) (string, error) {
var first []byte
var offset int64
for {
buf := make([]byte, bufSize)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
for i := 0; i < n; i++ {
if buf[i] == '\n' {
return string(append(first, buf[:i]...)), nil
}
}
if err == io.EOF {
return string(append(first, buf[:n]...)), nil
}
first = append(first, buf[:n]...)
offset += bufSize
}
}
func lastLine(filename string, file *os.File) (string, error) {
info, err := os.Stat(filename)
if err != nil {
return "", err
}
var last []byte
bufLen := int64(bufSize)
offset := info.Size()
for offset > 0 {
if offset < bufLen {
bufLen = offset
offset = 0
} else {
offset -= bufLen
}
buf := make([]byte, bufLen)
n, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return "", err
}
if n == 0 {
break
}
if buf[n-1] == '\n' {
buf = buf[:n-1]
n--
} else {
buf = buf[:n]
}
for i := n - 1; i >= 0; i-- {
if buf[i] == '\n' {
return string(append(buf[i+1:], last...)), nil
}
}
last = append(buf, last...)
}
return string(last), nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/rangereader.go | core/filex/rangereader.go | package filex
import (
"errors"
"os"
)
// errExceedFileSize indicates that the file size is exceeded.
var errExceedFileSize = errors.New("exceed file size")
// A RangeReader is used to read a range of content from a file.
type RangeReader struct {
file *os.File
start int64
stop int64
}
// NewRangeReader returns a RangeReader, which will read the range of content from file.
func NewRangeReader(file *os.File, start, stop int64) *RangeReader {
return &RangeReader{
file: file,
start: start,
stop: stop,
}
}
// Read reads the range of content into p.
func (rr *RangeReader) Read(p []byte) (n int, err error) {
stat, err := rr.file.Stat()
if err != nil {
return 0, err
}
if rr.stop < rr.start || rr.start >= stat.Size() {
return 0, errExceedFileSize
}
if rr.stop-rr.start < int64(len(p)) {
p = p[:rr.stop-rr.start]
}
n, err = rr.file.ReadAt(p, rr.start)
if err != nil {
return n, err
}
rr.start += int64(n)
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/file_test.go | core/filex/file_test.go | package filex
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
)
const (
longLine = `Quid securi etiam tamquam eu fugiat nulla pariatur. Nec dubitamus multa iter quae et nos invenerat. Non equidem invideo, miror magis posuere velit aliquet. Integer legentibus erat a ante historiarum dapibus. Prima luce, cum quibus mons aliud consensu ab eo.Quid securi etiam tamquam eu fugiat nulla pariatur. Nec dubitamus multa iter quae et nos invenerat. Non equidem invideo, miror magis posuere velit aliquet. Integer legentibus erat a ante historiarum dapibus. Prima luce, cum quibus mons aliud consensu ab eo.Quid securi etiam tamquam eu fugiat nulla pariatur. Nec dubitamus multa iter quae et nos invenerat. Non equidem invideo, miror magis posuere velit aliquet. Integer legentibus erat a ante historiarum dapibus. Prima luce, cum quibus mons aliud consensu ab eo.Quid securi etiam tamquam eu fugiat nulla pariatur. Nec dubitamus multa iter quae et nos invenerat. Non equidem invideo, miror magis posuere velit aliquet. Integer legentibus erat a ante historiarum dapibus. Prima luce, cum quibus mons aliud consensu ab eo.Quid securi etiam tamquam eu fugiat nulla pariatur. Nec dubitamus multa iter quae et nos invenerat. Non equidem invideo, miror magis posuere velit aliquet. Integer legentibus erat a ante historiarum dapibus. Prima luce, cum quibus mons aliud consensu ab eo.`
longFirstLine = longLine + "\n" + text
text = `first line
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
` + longLine
textWithLastNewline = `first line
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
Cum sociis natoque penatibus et magnis dis parturient. Phasellus laoreet lorem vel dolor tempus vehicula. Vivamus sagittis lacus vel augue laoreet rutrum faucibus. Integer legentibus erat a ante historiarum dapibus.
Quisque ut dolor gravida, placerat libero vel, euismod. Quam temere in vitiis, legem sancimus haerentia. Qui ipsorum lingua Celtae, nostra Galli appellantur. Quis aute iure reprehenderit in voluptate velit esse. Fabio vel iudice vincam, sunt in culpa qui officia. Cras mattis iudicium purus sit amet fermentum.
Quo usque tandem abutere, Catilina, patientia nostra? Gallia est omnis divisa in partes tres, quarum. Quam diu etiam furor iste tuus nos eludet? Quid securi etiam tamquam eu fugiat nulla pariatur. Curabitur blandit tempus ardua ridiculous sed magna.
Magna pars studiorum, prodita quaerimus. Cum ceteris in veneratione tui montes, nascetur mus. Morbi odio eros, volutpat ut pharetra vitae, lobortis sed nibh. Plura mihi bona sunt, inclinet, amari petere vellent. Idque Caesaris facere voluntate liceret: sese habere. Tu quoque, Brute, fili mi, nihil timor populi, nihil!
Tityre, tu patulae recubans sub tegmine fagi dolor. Inmensae subtilitatis, obscuris et malesuada fames. Quae vero auctorem tractata ab fiducia dicuntur.
` + longLine + "\n"
shortText = `first line
second line
last line`
shortTextWithLastNewline = `first line
second line
last line
`
emptyContent = ``
)
func TestFirstLine(t *testing.T) {
filename, err := fs.TempFilenameWithText(longFirstLine)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, longLine, val)
}
func TestFirstLineShort(t *testing.T) {
filename, err := fs.TempFilenameWithText(shortText)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, "first line", val)
}
func TestFirstLineError(t *testing.T) {
_, err := FirstLine("/tmp/does-not-exist")
assert.Error(t, err)
}
func TestFirstLineEmptyFile(t *testing.T) {
filename, err := fs.TempFilenameWithText(emptyContent)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, "", val)
}
func TestFirstLineWithoutNewline(t *testing.T) {
filename, err := fs.TempFilenameWithText(longLine)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, longLine, val)
}
func TestLastLine(t *testing.T) {
filename, err := fs.TempFilenameWithText(text)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, longLine, val)
}
func TestLastLineWithLastNewline(t *testing.T) {
filename, err := fs.TempFilenameWithText(textWithLastNewline)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, longLine, val)
}
func TestLastLineWithoutLastNewline(t *testing.T) {
filename, err := fs.TempFilenameWithText(longLine)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, longLine, val)
}
func TestLastLineShort(t *testing.T) {
filename, err := fs.TempFilenameWithText(shortText)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, "last line", val)
}
func TestLastLineWithLastNewlineShort(t *testing.T) {
filename, err := fs.TempFilenameWithText(shortTextWithLastNewline)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, "last line", val)
}
func TestLastLineError(t *testing.T) {
_, err := LastLine("/tmp/does-not-exist")
assert.Error(t, err)
}
func TestLastLineEmptyFile(t *testing.T) {
filename, err := fs.TempFilenameWithText(emptyContent)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, "", val)
}
func TestFirstLineExactlyBufSize(t *testing.T) {
content := make([]byte, bufSize)
for i := range content {
content[i] = 'a'
}
content[bufSize-1] = '\n' // Ensure there is a newline at the edge
filename, err := fs.TempFilenameWithText(string(content))
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, string(content[:bufSize-1]), val)
}
func TestLastLineExactlyBufSize(t *testing.T) {
content := make([]byte, bufSize)
for i := range content {
content[i] = 'a'
}
content[bufSize-1] = '\n' // Ensure there is a newline at the edge
filename, err := fs.TempFilenameWithText(string(content))
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, string(content[:bufSize-1]), val)
}
func TestFirstLineLargeFile(t *testing.T) {
content := text + text + text + "\n" + "extra"
filename, err := fs.TempFilenameWithText(content)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := FirstLine(filename)
assert.Nil(t, err)
assert.Equal(t, "first line", val)
}
func TestLastLineLargeFile(t *testing.T) {
content := text + text + text + "\n" + "extra"
filename, err := fs.TempFilenameWithText(content)
assert.Nil(t, err)
defer os.Remove(filename)
val, err := LastLine(filename)
assert.Nil(t, err)
assert.Equal(t, "extra", val)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/lookup_test.go | core/filex/lookup_test.go | package filex
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
)
func TestSplitLineChunks(t *testing.T) {
const text = `first line
second line
third line
fourth line
fifth line
sixth line
seventh line
`
fp, err := fs.TempFileWithText(text)
assert.Nil(t, err)
defer func() {
fp.Close()
os.Remove(fp.Name())
}()
offsets, err := SplitLineChunks(fp.Name(), 3)
assert.Nil(t, err)
body := make([]byte, 512)
for _, offset := range offsets {
reader := NewRangeReader(fp, offset.Start, offset.Stop)
n, err := reader.Read(body)
assert.Nil(t, err)
assert.Equal(t, uint8('\n'), body[n-1])
}
}
func TestSplitLineChunksNoFile(t *testing.T) {
_, err := SplitLineChunks("nosuchfile", 2)
assert.NotNil(t, err)
}
func TestSplitLineChunksFull(t *testing.T) {
const text = `first line
second line
third line
fourth line
fifth line
sixth line
`
fp, err := fs.TempFileWithText(text)
assert.Nil(t, err)
defer func() {
fp.Close()
os.Remove(fp.Name())
}()
offsets, err := SplitLineChunks(fp.Name(), 1)
assert.Nil(t, err)
body := make([]byte, 512)
for _, offset := range offsets {
reader := NewRangeReader(fp, offset.Start, offset.Stop)
n, err := reader.Read(body)
assert.Nil(t, err)
assert.Equal(t, []byte(text), body[:n])
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/lookup.go | core/filex/lookup.go | package filex
import (
"io"
"os"
)
// OffsetRange represents a content block of a file.
type OffsetRange struct {
File string
Start int64
Stop int64
}
// SplitLineChunks splits file into chunks.
// The whole line are guaranteed to be split in the same chunk.
func SplitLineChunks(filename string, chunks int) ([]OffsetRange, error) {
info, err := os.Stat(filename)
if err != nil {
return nil, err
}
if chunks <= 1 {
return []OffsetRange{
{
File: filename,
Start: 0,
Stop: info.Size(),
},
}, nil
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
var ranges []OffsetRange
var offset int64
// avoid the last chunk too few bytes
preferSize := info.Size()/int64(chunks) + 1
for {
if offset+preferSize >= info.Size() {
ranges = append(ranges, OffsetRange{
File: filename,
Start: offset,
Stop: info.Size(),
})
break
}
offsetRange, err := nextRange(file, offset, offset+preferSize)
if err != nil {
return nil, err
}
ranges = append(ranges, offsetRange)
if offsetRange.Stop < info.Size() {
offset = offsetRange.Stop
} else {
break
}
}
return ranges, nil
}
func nextRange(file *os.File, start, stop int64) (OffsetRange, error) {
offset, err := skipPartialLine(file, stop)
if err != nil {
return OffsetRange{}, err
}
return OffsetRange{
File: file.Name(),
Start: start,
Stop: offset,
}, nil
}
func skipPartialLine(file *os.File, offset int64) (int64, error) {
for {
skipBuf := make([]byte, bufSize)
n, err := file.ReadAt(skipBuf, offset)
if err != nil && err != io.EOF {
return 0, err
}
if n == 0 {
return 0, io.EOF
}
for i := 0; i < n; i++ {
if skipBuf[i] != '\r' && skipBuf[i] != '\n' {
offset++
} else {
for ; i < n; i++ {
if skipBuf[i] == '\r' || skipBuf[i] == '\n' {
offset++
} else {
return offset, nil
}
}
return offset, nil
}
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/progressscanner_test.go | core/filex/progressscanner_test.go | package filex
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/cheggaaa/pb.v1"
)
func TestProgressScanner(t *testing.T) {
const text = "hello, world"
bar := pb.New(100)
var builder strings.Builder
builder.WriteString(text)
scanner := NewProgressScanner(&mockedScanner{builder: &builder}, bar)
assert.True(t, scanner.Scan())
assert.Equal(t, text, scanner.Text())
}
type mockedScanner struct {
builder *strings.Builder
}
func (s *mockedScanner) Scan() bool {
return s.builder.Len() > 0
}
func (s *mockedScanner) Text() string {
return s.builder.String()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/filex/progressscanner.go | core/filex/progressscanner.go | package filex
import "gopkg.in/cheggaaa/pb.v1"
type (
// A Scanner is used to read lines.
Scanner interface {
// Scan checks if it has remaining to read.
Scan() bool
// Text returns next line.
Text() string
}
progressScanner struct {
Scanner
bar *pb.ProgressBar
}
)
// NewProgressScanner returns a Scanner with progress indicator.
func NewProgressScanner(scanner Scanner, bar *pb.ProgressBar) Scanner {
return &progressScanner{
Scanner: scanner,
bar: bar,
}
}
func (ps *progressScanner) Text() string {
s := ps.Scanner.Text()
ps.bar.Add64(int64(len(s)) + 1) // take newlines into account
return s
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/sysx/automaxprocs.go | core/sysx/automaxprocs.go | package sysx
import "go.uber.org/automaxprocs/maxprocs"
// Automatically set GOMAXPROCS to match Linux container CPU quota.
func init() {
maxprocs.Set(maxprocs.Logger(nil))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/sysx/host.go | core/sysx/host.go | package sysx
import (
"os"
"github.com/zeromicro/go-zero/core/stringx"
)
var hostname string
func init() {
var err error
hostname, err = os.Hostname()
if err != nil {
hostname = stringx.RandId()
}
}
// Hostname returns the name of the host, if no hostname, a random id is returned.
func Hostname() string {
return hostname
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/sysx/host_test.go | core/sysx/host_test.go | package sysx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestHostname(t *testing.T) {
assert.True(t, len(Hostname()) > 0)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/service/servicegroup_test.go | core/service/servicegroup_test.go | package service
import (
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
)
var (
number = 1
mutex sync.Mutex
done = make(chan struct{})
)
func TestServiceGroup(t *testing.T) {
multipliers := []int{2, 3, 5, 7}
want := 1
group := NewServiceGroup()
for _, multiplier := range multipliers {
want *= multiplier
service := newMockedService(multiplier)
group.Add(service)
}
go group.Start()
for i := 0; i < len(multipliers); i++ {
<-done
}
group.Stop()
proc.Shutdown()
mutex.Lock()
defer mutex.Unlock()
assert.Equal(t, want, number)
}
func TestServiceGroup_WithStart(t *testing.T) {
multipliers := []int{2, 3, 5, 7}
want := 1
var wait sync.WaitGroup
var lock sync.Mutex
wait.Add(len(multipliers))
group := NewServiceGroup()
for _, multiplier := range multipliers {
mul := multiplier
group.Add(WithStart(func() {
lock.Lock()
want *= mul
lock.Unlock()
wait.Done()
}))
}
go group.Start()
wait.Wait()
group.Stop()
lock.Lock()
defer lock.Unlock()
assert.Equal(t, 210, want)
}
func TestServiceGroup_WithStarter(t *testing.T) {
multipliers := []int{2, 3, 5, 7}
want := 1
var wait sync.WaitGroup
var lock sync.Mutex
wait.Add(len(multipliers))
group := NewServiceGroup()
for _, multiplier := range multipliers {
mul := multiplier
group.Add(WithStarter(mockedStarter{
fn: func() {
lock.Lock()
want *= mul
lock.Unlock()
wait.Done()
},
}))
}
go group.Start()
wait.Wait()
group.Stop()
lock.Lock()
defer lock.Unlock()
assert.Equal(t, 210, want)
}
type mockedStarter struct {
fn func()
}
func (s mockedStarter) Start() {
s.fn()
}
type mockedService struct {
quit chan struct{}
multiplier int
}
func newMockedService(multiplier int) *mockedService {
return &mockedService{
quit: make(chan struct{}),
multiplier: multiplier,
}
}
func (s *mockedService) Start() {
mutex.Lock()
number *= s.multiplier
mutex.Unlock()
done <- struct{}{}
<-s.quit
}
func (s *mockedService) Stop() {
close(s.quit)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/service/serviceconf.go | core/service/serviceconf.go | package service
import (
"github.com/zeromicro/go-zero/core/load"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/prometheus"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/trace"
"github.com/zeromicro/go-zero/internal/devserver"
"github.com/zeromicro/go-zero/internal/profiling"
)
const (
// DevMode means development mode.
DevMode = "dev"
// TestMode means test mode.
TestMode = "test"
// RtMode means regression test mode.
RtMode = "rt"
// PreMode means pre-release mode.
PreMode = "pre"
// ProMode means production mode.
ProMode = "pro"
)
type (
// DevServerConfig is type alias for devserver.Config
DevServerConfig = devserver.Config
// A ServiceConf is a service config.
ServiceConf struct {
Name string
Log logx.LogConf
Mode string `json:",default=pro,options=dev|test|rt|pre|pro"`
MetricsUrl string `json:",optional"`
// Deprecated: please use DevServer
Prometheus prometheus.Config `json:",optional"`
Telemetry trace.Config `json:",optional"`
DevServer DevServerConfig `json:",optional"`
Shutdown proc.ShutdownConf `json:",optional"`
// Profiling is the configuration for continuous profiling.
Profiling profiling.Config `json:",optional"`
}
)
// MustSetUp sets up the service, exits on error.
func (sc ServiceConf) MustSetUp() {
logx.Must(sc.SetUp())
}
// SetUp sets up the service.
func (sc ServiceConf) SetUp() error {
if len(sc.Log.ServiceName) == 0 {
sc.Log.ServiceName = sc.Name
}
if err := logx.SetUp(sc.Log); err != nil {
return err
}
sc.initMode()
prometheus.StartAgent(sc.Prometheus)
if len(sc.Telemetry.Name) == 0 {
sc.Telemetry.Name = sc.Name
}
trace.StartAgent(sc.Telemetry)
proc.Setup(sc.Shutdown)
proc.AddShutdownListener(func() {
trace.StopAgent()
})
if len(sc.MetricsUrl) > 0 {
stat.SetReportWriter(stat.NewRemoteWriter(sc.MetricsUrl))
}
devserver.StartAgent(sc.DevServer)
profiling.Start(sc.Profiling)
return nil
}
func (sc ServiceConf) initMode() {
switch sc.Mode {
case DevMode, TestMode, RtMode, PreMode:
load.Disable()
stat.SetReporter(nil)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/service/servicegroup.go | core/service/servicegroup.go | package service
import (
"sync"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/threading"
)
type (
// Starter is the interface wraps the Start method.
Starter interface {
Start()
}
// Stopper is the interface wraps the Stop method.
Stopper interface {
Stop()
}
// Service is the interface that groups Start and Stop methods.
Service interface {
Starter
Stopper
}
// A ServiceGroup is a group of services.
// Attention: the starting order of the added services is not guaranteed.
ServiceGroup struct {
services []Service
stopOnce func()
}
)
// NewServiceGroup returns a ServiceGroup.
func NewServiceGroup() *ServiceGroup {
sg := new(ServiceGroup)
sg.stopOnce = sync.OnceFunc(sg.doStop)
return sg
}
// Add adds service into sg.
func (sg *ServiceGroup) Add(service Service) {
// push front, stop with reverse order.
sg.services = append([]Service{service}, sg.services...)
}
// Start starts the ServiceGroup.
// There should not be any logic code after calling this method, because this method is a blocking one.
// Also, quitting this method will close the logx output.
func (sg *ServiceGroup) Start() {
proc.AddShutdownListener(func() {
logx.Info("Shutting down services in group")
sg.stopOnce()
})
sg.doStart()
}
// Stop stops the ServiceGroup.
func (sg *ServiceGroup) Stop() {
sg.stopOnce()
}
func (sg *ServiceGroup) doStart() {
routineGroup := threading.NewRoutineGroup()
for i := range sg.services {
service := sg.services[i]
routineGroup.Run(func() {
service.Start()
})
}
routineGroup.Wait()
}
func (sg *ServiceGroup) doStop() {
group := threading.NewRoutineGroup()
for _, service := range sg.services {
// new variable to avoid closure problems, can be removed after go 1.22
// see https://golang.org/doc/faq#closures_and_goroutines
service := service
group.Run(service.Stop)
}
group.Wait()
}
// WithStart wraps a start func as a Service.
func WithStart(start func()) Service {
return startOnlyService{
start: start,
}
}
// WithStarter wraps a Starter as a Service.
func WithStarter(start Starter) Service {
return starterOnlyService{
Starter: start,
}
}
type (
stopper struct{}
startOnlyService struct {
start func()
stopper
}
starterOnlyService struct {
Starter
stopper
}
)
func (s stopper) Stop() {
}
func (s startOnlyService) Start() {
s.start()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/service/serviceconf_test.go | core/service/serviceconf_test.go | package service
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/internal/devserver"
)
func TestServiceConf(t *testing.T) {
c := ServiceConf{
Name: "foo",
Log: logx.LogConf{
Mode: "console",
},
Mode: "dev",
DevServer: devserver.Config{
Port: 6470,
HealthPath: "/healthz",
},
}
c.MustSetUp()
}
func TestServiceConfWithMetricsUrl(t *testing.T) {
c := ServiceConf{
Name: "foo",
Log: logx.LogConf{
Mode: "volume",
},
Mode: "dev",
MetricsUrl: "http://localhost:8080",
}
assert.NoError(t, c.SetUp())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/lang/lang_test.go | core/lang/lang_test.go | package lang
import (
"encoding/json"
"errors"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRepr(t *testing.T) {
var (
f32 float32 = 1.1
f64 = 2.2
i8 int8 = 1
i16 int16 = 2
i32 int32 = 3
i64 int64 = 4
u8 uint8 = 5
u16 uint16 = 6
u32 uint32 = 7
u64 uint64 = 8
)
tests := []struct {
v any
expect string
}{
{
nil,
"",
},
{
mockStringable{},
"mocked",
},
{
new(mockStringable),
"mocked",
},
{
newMockPtr(),
"mockptr",
},
{
&mockOpacity{
val: 1,
},
"{1}",
},
{
true,
"true",
},
{
false,
"false",
},
{
f32,
"1.1",
},
{
f64,
"2.2",
},
{
i8,
"1",
},
{
i16,
"2",
},
{
i32,
"3",
},
{
i64,
"4",
},
{
u8,
"5",
},
{
u16,
"6",
},
{
u32,
"7",
},
{
u64,
"8",
},
{
[]byte(`abcd`),
"abcd",
},
{
mockOpacity{val: 1},
"{1}",
},
}
for _, test := range tests {
t.Run(test.expect, func(t *testing.T) {
assert.Equal(t, test.expect, Repr(test.v))
})
}
}
func TestReprOfValue(t *testing.T) {
t.Run("error", func(t *testing.T) {
assert.Equal(t, "error", reprOfValue(reflect.ValueOf(errors.New("error"))))
})
t.Run("stringer", func(t *testing.T) {
assert.Equal(t, "1.23", reprOfValue(reflect.ValueOf(json.Number("1.23"))))
})
t.Run("int", func(t *testing.T) {
assert.Equal(t, "1", reprOfValue(reflect.ValueOf(1)))
})
t.Run("int", func(t *testing.T) {
assert.Equal(t, "1", reprOfValue(reflect.ValueOf("1")))
})
t.Run("int", func(t *testing.T) {
assert.Equal(t, "1", reprOfValue(reflect.ValueOf(uint(1))))
})
}
type mockStringable struct{}
func (m mockStringable) String() string {
return "mocked"
}
type mockPtr struct{}
func newMockPtr() *mockPtr {
return new(mockPtr)
}
func (m *mockPtr) String() string {
return "mockptr"
}
type mockOpacity struct {
val int
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/lang/lang.go | core/lang/lang.go | package lang
import (
"fmt"
"reflect"
"strconv"
)
// Placeholder is a placeholder object that can be used globally.
var Placeholder PlaceholderType
type (
// AnyType can be used to hold any type.
AnyType = any
// PlaceholderType represents a placeholder type.
PlaceholderType = struct{}
)
// Repr returns the string representation of v.
func Repr(v any) string {
if v == nil {
return ""
}
// if func (v *Type) String() string, we can't use Elem()
switch vt := v.(type) {
case fmt.Stringer:
return vt.String()
}
val := reflect.ValueOf(v)
for val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
return reprOfValue(val)
}
func reprOfValue(val reflect.Value) string {
switch vt := val.Interface().(type) {
case bool:
return strconv.FormatBool(vt)
case error:
return vt.Error()
case float32:
return strconv.FormatFloat(float64(vt), 'f', -1, 32)
case float64:
return strconv.FormatFloat(vt, 'f', -1, 64)
case fmt.Stringer:
return vt.String()
case int:
return strconv.Itoa(vt)
case int8:
return strconv.Itoa(int(vt))
case int16:
return strconv.Itoa(int(vt))
case int32:
return strconv.Itoa(int(vt))
case int64:
return strconv.FormatInt(vt, 10)
case string:
return vt
case uint:
return strconv.FormatUint(uint64(vt), 10)
case uint8:
return strconv.FormatUint(uint64(vt), 10)
case uint16:
return strconv.FormatUint(uint64(vt), 10)
case uint32:
return strconv.FormatUint(uint64(vt), 10)
case uint64:
return strconv.FormatUint(vt, 10)
case []byte:
return string(vt)
default:
return fmt.Sprint(val.Interface())
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/read_test.go | core/iox/read_test.go | package iox
import (
"bytes"
"io"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/fs"
"github.com/zeromicro/go-zero/core/stringx"
)
func TestReadText(t *testing.T) {
tests := []struct {
input string
expect string
}{
{
input: `a`,
expect: `a`,
}, {
input: `a
`,
expect: `a`,
}, {
input: `a
b`,
expect: `a
b`,
}, {
input: `a
b
`,
expect: `a
b`,
},
}
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
tmpFile, err := fs.TempFilenameWithText(test.input)
assert.Nil(t, err)
defer os.Remove(tmpFile)
content, err := ReadText(tmpFile)
assert.Nil(t, err)
assert.Equal(t, test.expect, content)
})
}
}
func TestReadTextError(t *testing.T) {
_, err := ReadText("not-exist")
assert.NotNil(t, err)
}
func TestReadTextLines(t *testing.T) {
text := `1
2
#a
3`
tmpFile, err := fs.TempFilenameWithText(text)
assert.Nil(t, err)
defer os.Remove(tmpFile)
tests := []struct {
options []TextReadOption
expectLines int
}{
{
nil,
6,
}, {
[]TextReadOption{KeepSpace(), OmitWithPrefix("#")},
6,
}, {
[]TextReadOption{WithoutBlank()},
4,
}, {
[]TextReadOption{OmitWithPrefix("#")},
5,
}, {
[]TextReadOption{WithoutBlank(), OmitWithPrefix("#")},
3,
},
}
for _, test := range tests {
t.Run(stringx.Rand(), func(t *testing.T) {
lines, err := ReadTextLines(tmpFile, test.options...)
assert.Nil(t, err)
assert.Equal(t, test.expectLines, len(lines))
})
}
}
func TestReadTextLinesError(t *testing.T) {
_, err := ReadTextLines("not-exist")
assert.NotNil(t, err)
}
func TestDupReadCloser(t *testing.T) {
input := "hello"
reader := io.NopCloser(bytes.NewBufferString(input))
r1, r2 := DupReadCloser(reader)
verify := func(r io.Reader) {
output, err := io.ReadAll(r)
assert.Nil(t, err)
assert.Equal(t, input, string(output))
}
verify(r1)
verify(r2)
}
func TestLimitDupReadCloser(t *testing.T) {
input := "hello world"
limitBytes := int64(4)
reader := io.NopCloser(bytes.NewBufferString(input))
r1, r2 := LimitDupReadCloser(reader, limitBytes)
verify := func(r io.Reader) {
output, err := io.ReadAll(r)
assert.Nil(t, err)
assert.Equal(t, input, string(output))
}
verifyLimit := func(r io.Reader, limit int64) {
output, err := io.ReadAll(r)
if limit < int64(len(input)) {
input = input[:limit]
}
assert.Nil(t, err)
assert.Equal(t, input, string(output))
}
verify(r1)
verifyLimit(r2, limitBytes)
}
func TestReadBytes(t *testing.T) {
reader := io.NopCloser(bytes.NewBufferString("helloworld"))
buf := make([]byte, 5)
err := ReadBytes(reader, buf)
assert.Nil(t, err)
assert.Equal(t, "hello", string(buf))
}
func TestReadBytesNotEnough(t *testing.T) {
reader := io.NopCloser(bytes.NewBufferString("hell"))
buf := make([]byte, 5)
err := ReadBytes(reader, buf)
assert.Equal(t, io.EOF, err)
}
func TestReadBytesChunks(t *testing.T) {
buf := make([]byte, 5)
reader, writer := io.Pipe()
go func() {
for i := 0; i < 10; i++ {
writer.Write([]byte{'a'})
time.Sleep(10 * time.Millisecond)
}
}()
err := ReadBytes(reader, buf)
assert.Nil(t, err)
assert.Equal(t, "aaaaa", string(buf))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/bufferpool_test.go | core/iox/bufferpool_test.go | package iox
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBufferPool(t *testing.T) {
capacity := 1024
pool := NewBufferPool(capacity)
pool.Put(bytes.NewBuffer(make([]byte, 0, 2*capacity)))
assert.True(t, pool.Get().Cap() <= capacity)
}
func TestBufferPool_Put(t *testing.T) {
t.Run("with nil buf", func(t *testing.T) {
pool := NewBufferPool(1024)
pool.Put(nil)
val := pool.Get()
assert.IsType(t, new(bytes.Buffer), val)
})
t.Run("with less-cap buf", func(t *testing.T) {
pool := NewBufferPool(1024)
pool.Put(bytes.NewBuffer(make([]byte, 0, 512)))
val := pool.Get()
assert.IsType(t, new(bytes.Buffer), val)
})
t.Run("with more-cap buf", func(t *testing.T) {
pool := NewBufferPool(1024)
pool.Put(bytes.NewBuffer(make([]byte, 0, 1024<<1)))
val := pool.Get()
assert.IsType(t, new(bytes.Buffer), val)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/tee.go | core/iox/tee.go | package iox
import "io"
// LimitTeeReader returns a Reader that writes up to n bytes to w what it reads from r.
// First n bytes reads from r performed through it are matched with
// corresponding writes to w. There is no internal buffering -
// the write must complete before the first n bytes read completes.
// Any error encountered while writing is reported as a read error.
func LimitTeeReader(r io.Reader, w io.Writer, n int64) io.Reader {
return &limitTeeReader{r, w, n}
}
type limitTeeReader struct {
r io.Reader
w io.Writer
n int64 // limit bytes remaining
}
func (t *limitTeeReader) Read(p []byte) (n int, err error) {
n, err = t.r.Read(p)
if n > 0 && t.n > 0 {
limit := int64(n)
if limit > t.n {
limit = t.n
}
if n, err := t.w.Write(p[:limit]); err != nil {
return n, err
}
t.n -= limit
}
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/nopcloser.go | core/iox/nopcloser.go | package iox
import "io"
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error {
return nil
}
// NopCloser returns an io.WriteCloser that does nothing on calling Close.
func NopCloser(w io.Writer) io.WriteCloser {
return nopCloser{w}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/pipe_test.go | core/iox/pipe_test.go | package iox
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRedirectInOut(t *testing.T) {
restore, err := RedirectInOut()
assert.Nil(t, err)
defer restore()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/textfile.go | core/iox/textfile.go | package iox
import (
"bytes"
"errors"
"io"
"os"
)
const bufSize = 32 * 1024
// CountLines returns the number of lines in the file.
func CountLines(file string) (int, error) {
f, err := os.Open(file)
if err != nil {
return 0, err
}
defer f.Close()
var noEol bool
buf := make([]byte, bufSize)
count := 0
lineSep := []byte{'\n'}
for {
c, err := f.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case errors.Is(err, io.EOF):
if noEol {
count++
}
return count, nil
case err != nil:
return count, err
}
noEol = c > 0 && buf[c-1] != '\n'
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/bufferpool.go | core/iox/bufferpool.go | package iox
import (
"bytes"
"sync"
)
// A BufferPool is a pool to buffer bytes.Buffer objects.
type BufferPool struct {
capability int
pool *sync.Pool
}
// NewBufferPool returns a BufferPool.
func NewBufferPool(capability int) *BufferPool {
return &BufferPool{
capability: capability,
pool: &sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
},
}
}
// Get returns a bytes.Buffer object from bp.
func (bp *BufferPool) Get() *bytes.Buffer {
buf := bp.pool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
// Put returns buf into bp.
func (bp *BufferPool) Put(buf *bytes.Buffer) {
if buf == nil {
return
}
if buf.Cap() < bp.capability {
bp.pool.Put(buf)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/nopcloser_test.go | core/iox/nopcloser_test.go | package iox
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNopCloser(t *testing.T) {
closer := NopCloser(nil)
assert.NoError(t, closer.Close())
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/read.go | core/iox/read.go | package iox
import (
"bufio"
"bytes"
"io"
"os"
"strings"
)
type (
textReadOptions struct {
keepSpace bool
withoutBlanks bool
omitPrefix string
}
// TextReadOption defines the method to customize the text reading functions.
TextReadOption func(*textReadOptions)
)
// DupReadCloser returns two io.ReadCloser that read from the first will be written to the second.
// The first returned reader needs to be read first, because the content
// read from it will be written to the underlying buffer of the second reader.
func DupReadCloser(reader io.ReadCloser) (io.ReadCloser, io.ReadCloser) {
var buf bytes.Buffer
tee := io.TeeReader(reader, &buf)
return io.NopCloser(tee), io.NopCloser(&buf)
}
// KeepSpace customizes the reading functions to keep leading and tailing spaces.
func KeepSpace() TextReadOption {
return func(o *textReadOptions) {
o.keepSpace = true
}
}
// LimitDupReadCloser returns two io.ReadCloser that read from the first will be written to the second.
// But the second io.ReadCloser is limited to up to n bytes.
// The first returned reader needs to be read first, because the content
// read from it will be written to the underlying buffer of the second reader.
func LimitDupReadCloser(reader io.ReadCloser, n int64) (io.ReadCloser, io.ReadCloser) {
var buf bytes.Buffer
tee := LimitTeeReader(reader, &buf, n)
return io.NopCloser(tee), io.NopCloser(&buf)
}
// ReadBytes reads exactly the bytes with the length of len(buf)
func ReadBytes(reader io.Reader, buf []byte) error {
var got int
for got < len(buf) {
n, err := reader.Read(buf[got:])
if err != nil {
return err
}
got += n
}
return nil
}
// ReadText reads content from the given file with leading and tailing spaces trimmed.
func ReadText(filename string) (string, error) {
content, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return strings.TrimSpace(string(content)), nil
}
// ReadTextLines reads the text lines from given file.
func ReadTextLines(filename string, opts ...TextReadOption) ([]string, error) {
var readOpts textReadOptions
for _, opt := range opts {
opt(&readOpts)
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !readOpts.keepSpace {
line = strings.TrimSpace(line)
}
if readOpts.withoutBlanks && len(line) == 0 {
continue
}
if len(readOpts.omitPrefix) > 0 && strings.HasPrefix(line, readOpts.omitPrefix) {
continue
}
lines = append(lines, line)
}
return lines, scanner.Err()
}
// WithoutBlank customizes the reading functions to ignore blank lines.
func WithoutBlank() TextReadOption {
return func(o *textReadOptions) {
o.withoutBlanks = true
}
}
// OmitWithPrefix customizes the reading functions to ignore the lines with given leading prefix.
func OmitWithPrefix(prefix string) TextReadOption {
return func(o *textReadOptions) {
o.omitPrefix = prefix
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/textlinescanner.go | core/iox/textlinescanner.go | package iox
import (
"bufio"
"errors"
"io"
"strings"
)
// A TextLineScanner is a scanner that can scan lines from the given reader.
type TextLineScanner struct {
reader *bufio.Reader
hasNext bool
line string
err error
}
// NewTextLineScanner returns a TextLineScanner with the given reader.
func NewTextLineScanner(reader io.Reader) *TextLineScanner {
return &TextLineScanner{
reader: bufio.NewReader(reader),
hasNext: true,
}
}
// Scan checks if scanner has more lines to read.
func (scanner *TextLineScanner) Scan() bool {
if !scanner.hasNext {
return false
}
line, err := scanner.reader.ReadString('\n')
scanner.line = strings.TrimRight(line, "\n")
if errors.Is(err, io.EOF) {
scanner.hasNext = false
return true
} else if err != nil {
scanner.err = err
return false
}
return true
}
// Line returns the next available line.
func (scanner *TextLineScanner) Line() (string, error) {
return scanner.line, scanner.err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/textlinescanner_test.go | core/iox/textlinescanner_test.go | package iox
import (
"strings"
"testing"
"testing/iotest"
"github.com/stretchr/testify/assert"
)
func TestScanner(t *testing.T) {
const val = `1
2
3
4`
reader := strings.NewReader(val)
scanner := NewTextLineScanner(reader)
var lines []string
for scanner.Scan() {
line, err := scanner.Line()
assert.Nil(t, err)
lines = append(lines, line)
}
assert.EqualValues(t, []string{"1", "2", "3", "4"}, lines)
}
func TestBadScanner(t *testing.T) {
scanner := NewTextLineScanner(iotest.ErrReader(iotest.ErrTimeout))
assert.False(t, scanner.Scan())
_, err := scanner.Line()
assert.ErrorIs(t, err, iotest.ErrTimeout)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/textfile_test.go | core/iox/textfile_test.go | package iox
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCountLines(t *testing.T) {
const val = `1
2
3
4`
file, err := os.CreateTemp(os.TempDir(), "test-")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
file.WriteString(val)
file.Close()
lines, err := CountLines(file.Name())
assert.Nil(t, err)
assert.Equal(t, 4, lines)
}
func TestCountLinesError(t *testing.T) {
_, err := CountLines("not-exist")
assert.NotNil(t, err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/tee_test.go | core/iox/tee_test.go | package iox
import (
"bytes"
"io"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLimitTeeReader(t *testing.T) {
limit := int64(4)
src := []byte("hello, world")
dst := make([]byte, len(src))
rb := bytes.NewBuffer(src)
wb := new(bytes.Buffer)
r := LimitTeeReader(rb, wb, limit)
if n, err := io.ReadFull(r, dst); err != nil || n != len(src) {
t.Fatalf("ReadFull(r, dst) = %d, %v; want %d, nil", n, err, len(src))
}
if !bytes.Equal(dst, src) {
t.Errorf("bytes read = %q want %q", dst, src)
}
if !bytes.Equal(wb.Bytes(), src[:limit]) {
t.Errorf("bytes written = %q want %q", wb.Bytes(), src)
}
n, err := r.Read(dst)
assert.Equal(t, 0, n)
assert.Equal(t, io.EOF, err)
rb = bytes.NewBuffer(src)
pr, pw := io.Pipe()
if assert.NoError(t, pr.Close()) {
r = LimitTeeReader(rb, pw, limit)
n, err := io.ReadFull(r, dst)
assert.Equal(t, 0, n)
assert.Equal(t, io.ErrClosedPipe, err)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/iox/pipe.go | core/iox/pipe.go | package iox
import "os"
// RedirectInOut redirects stdin to r, stdout to w, and callers need to call restore afterward.
func RedirectInOut() (restore func(), err error) {
var r, w *os.File
r, w, err = os.Pipe()
if err != nil {
return
}
ow := os.Stdout
os.Stdout = w
or := os.Stdin
os.Stdin = r
restore = func() {
os.Stdin = or
os.Stdout = ow
}
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/rescue/recover.go | core/rescue/recover.go | package rescue
import (
"context"
"runtime/debug"
"github.com/zeromicro/go-zero/core/logx"
)
// Recover is used with defer to do cleanup on panics.
// Use it like:
//
// defer Recover(func() {})
func Recover(cleanups ...func()) {
for _, cleanup := range cleanups {
cleanup()
}
if p := recover(); p != nil {
logx.ErrorStack(p)
}
}
// RecoverCtx is used with defer to do cleanup on panics.
func RecoverCtx(ctx context.Context, cleanups ...func()) {
for _, cleanup := range cleanups {
cleanup()
}
if p := recover(); p != nil {
logx.WithContext(ctx).Errorf("%+v\n%s", p, debug.Stack())
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/rescue/recover_test.go | core/rescue/recover_test.go | package rescue
import (
"context"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
)
func init() {
logx.Disable()
}
func TestRescue(t *testing.T) {
var count int32
assert.NotPanics(t, func() {
defer Recover(func() {
atomic.AddInt32(&count, 2)
}, func() {
atomic.AddInt32(&count, 3)
})
panic("hello")
})
assert.Equal(t, int32(5), atomic.LoadInt32(&count))
}
func TestRescueCtx(t *testing.T) {
var count int32
assert.NotPanics(t, func() {
defer RecoverCtx(context.Background(), func() {
atomic.AddInt32(&count, 2)
}, func() {
atomic.AddInt32(&count, 3)
})
panic("hello")
})
assert.Equal(t, int32(5), atomic.LoadInt32(&count))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/nopbreaker_test.go | core/breaker/nopbreaker_test.go | package breaker
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNopBreaker(t *testing.T) {
b := NopBreaker()
assert.Equal(t, nopBreakerName, b.Name())
_, err := b.Allow()
assert.Nil(t, err)
p, err := b.AllowCtx(context.Background())
assert.Nil(t, err)
p.Accept()
for i := 0; i < 1000; i++ {
p, err := b.Allow()
assert.Nil(t, err)
p.Reject("any")
}
assert.Nil(t, b.Do(func() error {
return nil
}))
assert.Nil(t, b.DoCtx(context.Background(), func() error {
return nil
}))
assert.Nil(t, b.DoWithAcceptable(func() error {
return nil
}, defaultAcceptable))
assert.Nil(t, b.DoWithAcceptableCtx(context.Background(), func() error {
return nil
}, defaultAcceptable))
errDummy := errors.New("any")
assert.Equal(t, errDummy, b.DoWithFallback(func() error {
return errDummy
}, func(err error) error {
return nil
}))
assert.Equal(t, errDummy, b.DoWithFallbackCtx(context.Background(), func() error {
return errDummy
}, func(err error) error {
return nil
}))
assert.Equal(t, errDummy, b.DoWithFallbackAcceptable(func() error {
return errDummy
}, func(err error) error {
return nil
}, defaultAcceptable))
assert.Equal(t, errDummy, b.DoWithFallbackAcceptableCtx(context.Background(), func() error {
return errDummy
}, func(err error) error {
return nil
}, defaultAcceptable))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/bucket.go | core/breaker/bucket.go | package breaker
const (
success = iota
fail
drop
)
// bucket defines the bucket that holds sum and num of additions.
type bucket struct {
Sum int64
Success int64
Failure int64
Drop int64
}
func (b *bucket) Add(v int64) {
switch v {
case fail:
b.fail()
case drop:
b.drop()
default:
b.succeed()
}
}
func (b *bucket) Reset() {
b.Sum = 0
b.Success = 0
b.Failure = 0
b.Drop = 0
}
func (b *bucket) drop() {
b.Sum++
b.Drop++
}
func (b *bucket) fail() {
b.Sum++
b.Failure++
}
func (b *bucket) succeed() {
b.Sum++
b.Success++
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/breakers_test.go | core/breaker/breakers_test.go | package breaker
import (
"context"
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stat"
)
func init() {
stat.SetReporter(nil)
}
func TestBreakersDo(t *testing.T) {
assert.Nil(t, Do("any", func() error {
return nil
}))
errDummy := errors.New("any")
assert.Equal(t, errDummy, Do("any", func() error {
return errDummy
}))
assert.Equal(t, errDummy, DoCtx(context.Background(), "any", func() error {
return errDummy
}))
}
func TestBreakersDoWithAcceptable(t *testing.T) {
errDummy := errors.New("anyone")
for i := 0; i < 10000; i++ {
assert.Equal(t, errDummy, GetBreaker("anyone").DoWithAcceptable(func() error {
return errDummy
}, func(err error) bool {
return err == nil || errors.Is(err, errDummy)
}))
}
verify(t, func() bool {
return Do("anyone", func() error {
return nil
}) == nil
})
verify(t, func() bool {
return DoWithAcceptableCtx(context.Background(), "anyone", func() error {
return nil
}, func(err error) bool {
return true
}) == nil
})
for i := 0; i < 10000; i++ {
err := DoWithAcceptable("another", func() error {
return errDummy
}, func(err error) bool {
return err == nil
})
assert.True(t, errors.Is(err, errDummy) || errors.Is(err, ErrServiceUnavailable))
}
verify(t, func() bool {
return errors.Is(Do("another", func() error {
return nil
}), ErrServiceUnavailable)
})
}
func TestBreakersNoBreakerFor(t *testing.T) {
NoBreakerFor("any")
errDummy := errors.New("any")
for i := 0; i < 10000; i++ {
assert.Equal(t, errDummy, GetBreaker("any").Do(func() error {
return errDummy
}))
}
assert.Equal(t, nil, Do("any", func() error {
return nil
}))
}
func TestBreakersFallback(t *testing.T) {
errDummy := errors.New("any")
for i := 0; i < 10000; i++ {
err := DoWithFallback("fallback", func() error {
return errDummy
}, func(err error) error {
return nil
})
assert.True(t, err == nil || errors.Is(err, errDummy))
err = DoWithFallbackCtx(context.Background(), "fallback", func() error {
return errDummy
}, func(err error) error {
return nil
})
assert.True(t, err == nil || errors.Is(err, errDummy))
}
verify(t, func() bool {
return errors.Is(Do("fallback", func() error {
return nil
}), ErrServiceUnavailable)
})
}
func TestBreakersAcceptableFallback(t *testing.T) {
errDummy := errors.New("any")
for i := 0; i < 5000; i++ {
err := DoWithFallbackAcceptable("acceptablefallback", func() error {
return errDummy
}, func(err error) error {
return nil
}, func(err error) bool {
return err == nil
})
assert.True(t, err == nil || errors.Is(err, errDummy))
err = DoWithFallbackAcceptableCtx(context.Background(), "acceptablefallback", func() error {
return errDummy
}, func(err error) error {
return nil
}, func(err error) bool {
return err == nil
})
assert.True(t, err == nil || errors.Is(err, errDummy))
}
verify(t, func() bool {
return errors.Is(Do("acceptablefallback", func() error {
return nil
}), ErrServiceUnavailable)
})
}
func verify(t *testing.T, fn func() bool) {
var count int
for i := 0; i < 100; i++ {
if fn() {
count++
}
}
assert.True(t, count >= 75, fmt.Sprintf("should be greater than 75, actual %d", count))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/googlebreaker.go | core/breaker/googlebreaker.go | package breaker
import (
"time"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
)
const (
// 250ms for bucket duration
window = time.Second * 10
buckets = 40
forcePassDuration = time.Second
k = 1.5
minK = 1.1
protection = 5
)
// googleBreaker is a netflixBreaker pattern from google.
// see Client-Side Throttling section in https://landing.google.com/sre/sre-book/chapters/handling-overload/
type (
googleBreaker struct {
k float64
stat *collection.RollingWindow[int64, *bucket]
proba *mathx.Proba
lastPass *syncx.AtomicDuration
}
windowResult struct {
accepts int64
total int64
failingBuckets int64
workingBuckets int64
}
)
func newGoogleBreaker() *googleBreaker {
bucketDuration := time.Duration(int64(window) / int64(buckets))
st := collection.NewRollingWindow[int64, *bucket](func() *bucket {
return new(bucket)
}, buckets, bucketDuration)
return &googleBreaker{
stat: st,
k: k,
proba: mathx.NewProba(),
lastPass: syncx.NewAtomicDuration(),
}
}
func (b *googleBreaker) accept() error {
var w float64
history := b.history()
w = b.k - (b.k-minK)*float64(history.failingBuckets)/buckets
weightedAccepts := mathx.AtLeast(w, minK) * float64(history.accepts)
// https://landing.google.com/sre/sre-book/chapters/handling-overload/#eq2101
// for better performance, no need to care about the negative ratio
dropRatio := (float64(history.total-protection) - weightedAccepts) / float64(history.total+1)
if dropRatio <= 0 {
return nil
}
lastPass := b.lastPass.Load()
if lastPass > 0 && timex.Since(lastPass) > forcePassDuration {
b.lastPass.Set(timex.Now())
return nil
}
dropRatio *= float64(buckets-history.workingBuckets) / buckets
if b.proba.TrueOnProba(dropRatio) {
return ErrServiceUnavailable
}
b.lastPass.Set(timex.Now())
return nil
}
func (b *googleBreaker) allow() (internalPromise, error) {
if err := b.accept(); err != nil {
b.markDrop()
return nil, err
}
return googlePromise{
b: b,
}, nil
}
func (b *googleBreaker) doReq(req func() error, fallback Fallback, acceptable Acceptable) error {
if err := b.accept(); err != nil {
b.markDrop()
if fallback != nil {
return fallback(err)
}
return err
}
var succ bool
defer func() {
// if req() panic, success is false, mark as failure
if succ {
b.markSuccess()
} else {
b.markFailure()
}
}()
err := req()
if acceptable(err) {
succ = true
}
return err
}
func (b *googleBreaker) markDrop() {
b.stat.Add(drop)
}
func (b *googleBreaker) markFailure() {
b.stat.Add(fail)
}
func (b *googleBreaker) markSuccess() {
b.stat.Add(success)
}
func (b *googleBreaker) history() windowResult {
var result windowResult
b.stat.Reduce(func(b *bucket) {
result.accepts += b.Success
result.total += b.Sum
if b.Failure > 0 {
result.workingBuckets = 0
} else if b.Success > 0 {
result.workingBuckets++
}
if b.Success > 0 {
result.failingBuckets = 0
} else if b.Failure > 0 {
result.failingBuckets++
}
})
return result
}
type googlePromise struct {
b *googleBreaker
}
func (p googlePromise) Accept() {
p.b.markSuccess()
}
func (p googlePromise) Reject() {
p.b.markFailure()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/breakers.go | core/breaker/breakers.go | package breaker
import (
"context"
"sync"
)
var (
lock sync.RWMutex
breakers = make(map[string]Breaker)
)
// Do calls Breaker.Do on the Breaker with given name.
func Do(name string, req func() error) error {
return do(name, func(b Breaker) error {
return b.Do(req)
})
}
// DoCtx calls Breaker.DoCtx on the Breaker with given name.
func DoCtx(ctx context.Context, name string, req func() error) error {
return do(name, func(b Breaker) error {
return b.DoCtx(ctx, req)
})
}
// DoWithAcceptable calls Breaker.DoWithAcceptable on the Breaker with given name.
func DoWithAcceptable(name string, req func() error, acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithAcceptable(req, acceptable)
})
}
// DoWithAcceptableCtx calls Breaker.DoWithAcceptableCtx on the Breaker with given name.
func DoWithAcceptableCtx(ctx context.Context, name string, req func() error,
acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithAcceptableCtx(ctx, req, acceptable)
})
}
// DoWithFallback calls Breaker.DoWithFallback on the Breaker with given name.
func DoWithFallback(name string, req func() error, fallback Fallback) error {
return do(name, func(b Breaker) error {
return b.DoWithFallback(req, fallback)
})
}
// DoWithFallbackCtx calls Breaker.DoWithFallbackCtx on the Breaker with given name.
func DoWithFallbackCtx(ctx context.Context, name string, req func() error, fallback Fallback) error {
return do(name, func(b Breaker) error {
return b.DoWithFallbackCtx(ctx, req, fallback)
})
}
// DoWithFallbackAcceptable calls Breaker.DoWithFallbackAcceptable on the Breaker with given name.
func DoWithFallbackAcceptable(name string, req func() error, fallback Fallback,
acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithFallbackAcceptable(req, fallback, acceptable)
})
}
// DoWithFallbackAcceptableCtx calls Breaker.DoWithFallbackAcceptableCtx on the Breaker with given name.
func DoWithFallbackAcceptableCtx(ctx context.Context, name string, req func() error,
fallback Fallback, acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithFallbackAcceptableCtx(ctx, req, fallback, acceptable)
})
}
// GetBreaker returns the Breaker with the given name.
func GetBreaker(name string) Breaker {
lock.RLock()
b, ok := breakers[name]
lock.RUnlock()
if ok {
return b
}
lock.Lock()
b, ok = breakers[name]
if !ok {
b = NewBreaker(WithName(name))
breakers[name] = b
}
lock.Unlock()
return b
}
// NoBreakerFor disables the circuit breaker for the given name.
func NoBreakerFor(name string) {
lock.Lock()
breakers[name] = NopBreaker()
lock.Unlock()
}
func do(name string, execute func(b Breaker) error) error {
return execute(GetBreaker(name))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/bucket_test.go | core/breaker/bucket_test.go | package breaker
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestBucketAdd(t *testing.T) {
b := &bucket{}
// Test succeed
b.Add(0) // Using 0 for success
assert.Equal(t, int64(1), b.Sum, "Sum should be incremented")
assert.Equal(t, int64(1), b.Success, "Success should be incremented")
assert.Equal(t, int64(0), b.Failure, "Failure should not be incremented")
assert.Equal(t, int64(0), b.Drop, "Drop should not be incremented")
// Test failure
b.Add(fail)
assert.Equal(t, int64(2), b.Sum, "Sum should be incremented")
assert.Equal(t, int64(1), b.Failure, "Failure should be incremented")
assert.Equal(t, int64(0), b.Drop, "Drop should not be incremented")
// Test drop
b.Add(drop)
assert.Equal(t, int64(3), b.Sum, "Sum should be incremented")
assert.Equal(t, int64(1), b.Drop, "Drop should be incremented")
}
func TestBucketReset(t *testing.T) {
b := &bucket{
Sum: 3,
Success: 1,
Failure: 1,
Drop: 1,
}
b.Reset()
assert.Equal(t, int64(0), b.Sum, "Sum should be reset to 0")
assert.Equal(t, int64(0), b.Success, "Success should be reset to 0")
assert.Equal(t, int64(0), b.Failure, "Failure should be reset to 0")
assert.Equal(t, int64(0), b.Drop, "Drop should be reset to 0")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/breaker_test.go | core/breaker/breaker_test.go | package breaker
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stat"
)
func init() {
stat.SetReporter(nil)
}
func TestCircuitBreaker_Allow(t *testing.T) {
t.Run("allow", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
_, err := b.Allow()
assert.Nil(t, err)
})
t.Run("allow with ctx", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
_, err := b.AllowCtx(context.Background())
assert.Nil(t, err)
})
t.Run("allow with ctx timeout", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond)
defer cancel()
time.Sleep(time.Millisecond)
_, err := b.AllowCtx(ctx)
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("allow with ctx cancel", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
_, err := b.AllowCtx(ctx)
assert.ErrorIs(t, err, context.Canceled)
}
_, err := b.AllowCtx(context.Background())
assert.NoError(t, err)
})
}
func TestCircuitBreaker_Do(t *testing.T) {
t.Run("do", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.Do(func() error {
return nil
})
assert.Nil(t, err)
})
t.Run("do with ctx", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoCtx(context.Background(), func() error {
return nil
})
assert.Nil(t, err)
})
t.Run("do with ctx timeout", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond)
defer cancel()
time.Sleep(time.Millisecond)
err := b.DoCtx(ctx, func() error {
return nil
})
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("do with ctx cancel", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
err := b.DoCtx(ctx, func() error {
return nil
})
assert.ErrorIs(t, err, context.Canceled)
}
assert.NoError(t, b.DoCtx(context.Background(), func() error {
return nil
}))
})
}
func TestCircuitBreaker_DoWithAcceptable(t *testing.T) {
t.Run("doWithAcceptable", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithAcceptable(func() error {
return nil
}, func(err error) bool {
return true
})
assert.Nil(t, err)
})
t.Run("doWithAcceptable with ctx", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithAcceptableCtx(context.Background(), func() error {
return nil
}, func(err error) bool {
return true
})
assert.Nil(t, err)
})
t.Run("doWithAcceptable with ctx timeout", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond)
defer cancel()
time.Sleep(time.Millisecond)
err := b.DoWithAcceptableCtx(ctx, func() error {
return nil
}, func(err error) bool {
return true
})
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("doWithAcceptable with ctx cancel", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
err := b.DoWithAcceptableCtx(ctx, func() error {
return nil
}, func(err error) bool {
return true
})
assert.ErrorIs(t, err, context.Canceled)
}
assert.NoError(t, b.DoWithAcceptableCtx(context.Background(), func() error {
return nil
}, func(err error) bool {
return true
}))
})
}
func TestCircuitBreaker_DoWithFallback(t *testing.T) {
t.Run("doWithFallback", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithFallback(func() error {
return nil
}, func(err error) error {
return err
})
assert.Nil(t, err)
})
t.Run("doWithFallback with ctx", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithFallbackCtx(context.Background(), func() error {
return nil
}, func(err error) error {
return err
})
assert.Nil(t, err)
})
t.Run("doWithFallback with ctx timeout", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond)
defer cancel()
time.Sleep(time.Millisecond)
err := b.DoWithFallbackCtx(ctx, func() error {
return nil
}, func(err error) error {
return err
})
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("doWithFallback with ctx cancel", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
err := b.DoWithFallbackCtx(ctx, func() error {
return nil
}, func(err error) error {
return err
})
assert.ErrorIs(t, err, context.Canceled)
}
assert.NoError(t, b.DoWithFallbackCtx(context.Background(), func() error {
return nil
}, func(err error) error {
return err
}))
})
}
func TestCircuitBreaker_DoWithFallbackAcceptable(t *testing.T) {
t.Run("doWithFallbackAcceptable", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithFallbackAcceptable(func() error {
return nil
}, func(err error) error {
return err
}, func(err error) bool {
return true
})
assert.Nil(t, err)
})
t.Run("doWithFallbackAcceptable with ctx", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
err := b.DoWithFallbackAcceptableCtx(context.Background(), func() error {
return nil
}, func(err error) error {
return err
}, func(err error) bool {
return true
})
assert.Nil(t, err)
})
t.Run("doWithFallbackAcceptable with ctx timeout", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond)
defer cancel()
time.Sleep(time.Millisecond)
err := b.DoWithFallbackAcceptableCtx(ctx, func() error {
return nil
}, func(err error) error {
return err
}, func(err error) bool {
return true
})
assert.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("doWithFallbackAcceptable with ctx cancel", func(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 100; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cancel()
err := b.DoWithFallbackAcceptableCtx(ctx, func() error {
return nil
}, func(err error) error {
return err
}, func(err error) bool {
return true
})
assert.ErrorIs(t, err, context.Canceled)
}
assert.NoError(t, b.DoWithFallbackAcceptableCtx(context.Background(), func() error {
return nil
}, func(err error) error {
return err
}, func(err error) bool {
return true
}))
})
}
func TestLogReason(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 1000; i++ {
_ = b.Do(func() error {
return errors.New(strconv.Itoa(i))
})
}
errs := b.(*circuitBreaker).throttle.(loggedThrottle).errWin
assert.Equal(t, numHistoryReasons, errs.count)
}
func TestErrorWindow(t *testing.T) {
tests := []struct {
name string
reasons []string
}{
{
name: "no error",
},
{
name: "one error",
reasons: []string{"foo"},
},
{
name: "two errors",
reasons: []string{"foo", "bar"},
},
{
name: "five errors",
reasons: []string{"first", "second", "third", "fourth", "fifth"},
},
{
name: "six errors",
reasons: []string{"first", "second", "third", "fourth", "fifth", "sixth"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var ew errorWindow
for _, reason := range test.reasons {
ew.add(reason)
}
var reasons []string
if len(test.reasons) > numHistoryReasons {
reasons = test.reasons[len(test.reasons)-numHistoryReasons:]
} else {
reasons = test.reasons
}
for _, reason := range reasons {
assert.True(t, strings.Contains(ew.String(), reason), fmt.Sprintf("actual: %s", ew.String()))
}
})
}
}
func TestPromiseWithReason(t *testing.T) {
tests := []struct {
name string
reason string
expect string
}{
{
name: "success",
},
{
name: "success",
reason: "fail",
expect: "fail",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
promise := promiseWithReason{
promise: new(mockedPromise),
errWin: new(errorWindow),
}
if len(test.reason) == 0 {
promise.Accept()
} else {
promise.Reject(test.reason)
}
assert.True(t, strings.Contains(promise.errWin.String(), test.expect))
})
}
}
func BenchmarkGoogleBreaker(b *testing.B) {
br := NewBreaker()
for i := 0; i < b.N; i++ {
_ = br.Do(func() error {
return nil
})
}
}
type mockedPromise struct{}
func (m *mockedPromise) Accept() {
}
func (m *mockedPromise) Reject() {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/nopbreaker.go | core/breaker/nopbreaker.go | package breaker
import "context"
const nopBreakerName = "nopBreaker"
type nopBreaker struct{}
// NopBreaker returns a breaker that never trigger breaker circuit.
func NopBreaker() Breaker {
return nopBreaker{}
}
func (b nopBreaker) Name() string {
return nopBreakerName
}
func (b nopBreaker) Allow() (Promise, error) {
return nopPromise{}, nil
}
func (b nopBreaker) AllowCtx(_ context.Context) (Promise, error) {
return nopPromise{}, nil
}
func (b nopBreaker) Do(req func() error) error {
return req()
}
func (b nopBreaker) DoCtx(_ context.Context, req func() error) error {
return req()
}
func (b nopBreaker) DoWithAcceptable(req func() error, _ Acceptable) error {
return req()
}
func (b nopBreaker) DoWithAcceptableCtx(_ context.Context, req func() error, _ Acceptable) error {
return req()
}
func (b nopBreaker) DoWithFallback(req func() error, _ Fallback) error {
return req()
}
func (b nopBreaker) DoWithFallbackCtx(_ context.Context, req func() error, _ Fallback) error {
return req()
}
func (b nopBreaker) DoWithFallbackAcceptable(req func() error, _ Fallback, _ Acceptable) error {
return req()
}
func (b nopBreaker) DoWithFallbackAcceptableCtx(_ context.Context, req func() error,
_ Fallback, _ Acceptable) error {
return req()
}
type nopPromise struct{}
func (p nopPromise) Accept() {
}
func (p nopPromise) Reject(_ string) {
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/breaker.go | core/breaker/breaker.go | package breaker
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/stringx"
)
const numHistoryReasons = 5
// ErrServiceUnavailable is returned when the Breaker state is open.
var ErrServiceUnavailable = errors.New("circuit breaker is open")
type (
// Acceptable is the func to check if the error can be accepted.
Acceptable func(err error) bool
// A Breaker represents a circuit breaker.
Breaker interface {
// Name returns the name of the Breaker.
Name() string
// Allow checks if the request is allowed.
// If allowed, a promise will be returned,
// otherwise ErrServiceUnavailable will be returned as the error.
// The caller needs to call promise.Accept() on success,
// or call promise.Reject() on failure.
Allow() (Promise, error)
// AllowCtx checks if the request is allowed when ctx isn't done.
AllowCtx(ctx context.Context) (Promise, error)
// Do runs the given request if the Breaker accepts it.
// Do returns an error instantly if the Breaker rejects the request.
// If a panic occurs in the request, the Breaker handles it as an error
// and causes the same panic again.
Do(req func() error) error
// DoCtx runs the given request if the Breaker accepts it when ctx isn't done.
DoCtx(ctx context.Context, req func() error) error
// DoWithAcceptable runs the given request if the Breaker accepts it.
// DoWithAcceptable returns an error instantly if the Breaker rejects the request.
// If a panic occurs in the request, the Breaker handles it as an error
// and causes the same panic again.
// acceptable checks if it's a successful call, even if the error is not nil.
DoWithAcceptable(req func() error, acceptable Acceptable) error
// DoWithAcceptableCtx runs the given request if the Breaker accepts it when ctx isn't done.
DoWithAcceptableCtx(ctx context.Context, req func() error, acceptable Acceptable) error
// DoWithFallback runs the given request if the Breaker accepts it.
// DoWithFallback runs the fallback if the Breaker rejects the request.
// If a panic occurs in the request, the Breaker handles it as an error
// and causes the same panic again.
DoWithFallback(req func() error, fallback Fallback) error
// DoWithFallbackCtx runs the given request if the Breaker accepts it when ctx isn't done.
DoWithFallbackCtx(ctx context.Context, req func() error, fallback Fallback) error
// DoWithFallbackAcceptable runs the given request if the Breaker accepts it.
// DoWithFallbackAcceptable runs the fallback if the Breaker rejects the request.
// If a panic occurs in the request, the Breaker handles it as an error
// and causes the same panic again.
// acceptable checks if it's a successful call, even if the error is not nil.
DoWithFallbackAcceptable(req func() error, fallback Fallback, acceptable Acceptable) error
// DoWithFallbackAcceptableCtx runs the given request if the Breaker accepts it when ctx isn't done.
DoWithFallbackAcceptableCtx(ctx context.Context, req func() error, fallback Fallback,
acceptable Acceptable) error
}
// Fallback is the func to be called if the request is rejected.
Fallback func(err error) error
// Option defines the method to customize a Breaker.
Option func(breaker *circuitBreaker)
// Promise interface defines the callbacks that returned by Breaker.Allow.
Promise interface {
// Accept tells the Breaker that the call is successful.
Accept()
// Reject tells the Breaker that the call is failed.
Reject(reason string)
}
internalPromise interface {
Accept()
Reject()
}
circuitBreaker struct {
name string
throttle
}
internalThrottle interface {
allow() (internalPromise, error)
doReq(req func() error, fallback Fallback, acceptable Acceptable) error
}
throttle interface {
allow() (Promise, error)
doReq(req func() error, fallback Fallback, acceptable Acceptable) error
}
)
// NewBreaker returns a Breaker object.
// opts can be used to customize the Breaker.
func NewBreaker(opts ...Option) Breaker {
var b circuitBreaker
for _, opt := range opts {
opt(&b)
}
if len(b.name) == 0 {
b.name = stringx.Rand()
}
b.throttle = newLoggedThrottle(b.name, newGoogleBreaker())
return &b
}
func (cb *circuitBreaker) Allow() (Promise, error) {
return cb.throttle.allow()
}
func (cb *circuitBreaker) AllowCtx(ctx context.Context) (Promise, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return cb.Allow()
}
}
func (cb *circuitBreaker) Do(req func() error) error {
return cb.throttle.doReq(req, nil, defaultAcceptable)
}
func (cb *circuitBreaker) DoCtx(ctx context.Context, req func() error) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return cb.Do(req)
}
}
func (cb *circuitBreaker) DoWithAcceptable(req func() error, acceptable Acceptable) error {
return cb.throttle.doReq(req, nil, acceptable)
}
func (cb *circuitBreaker) DoWithAcceptableCtx(ctx context.Context, req func() error,
acceptable Acceptable) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return cb.DoWithAcceptable(req, acceptable)
}
}
func (cb *circuitBreaker) DoWithFallback(req func() error, fallback Fallback) error {
return cb.throttle.doReq(req, fallback, defaultAcceptable)
}
func (cb *circuitBreaker) DoWithFallbackCtx(ctx context.Context, req func() error,
fallback Fallback) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return cb.DoWithFallback(req, fallback)
}
}
func (cb *circuitBreaker) DoWithFallbackAcceptable(req func() error, fallback Fallback,
acceptable Acceptable) error {
return cb.throttle.doReq(req, fallback, acceptable)
}
func (cb *circuitBreaker) DoWithFallbackAcceptableCtx(ctx context.Context, req func() error,
fallback Fallback, acceptable Acceptable) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
return cb.DoWithFallbackAcceptable(req, fallback, acceptable)
}
}
func (cb *circuitBreaker) Name() string {
return cb.name
}
// WithName returns a function to set the name of a Breaker.
func WithName(name string) Option {
return func(b *circuitBreaker) {
b.name = name
}
}
func defaultAcceptable(err error) bool {
return err == nil
}
type loggedThrottle struct {
name string
internalThrottle
errWin *errorWindow
}
func newLoggedThrottle(name string, t internalThrottle) loggedThrottle {
return loggedThrottle{
name: name,
internalThrottle: t,
errWin: new(errorWindow),
}
}
func (lt loggedThrottle) allow() (Promise, error) {
promise, err := lt.internalThrottle.allow()
return promiseWithReason{
promise: promise,
errWin: lt.errWin,
}, lt.logError(err)
}
func (lt loggedThrottle) doReq(req func() error, fallback Fallback, acceptable Acceptable) error {
return lt.logError(lt.internalThrottle.doReq(req, fallback, func(err error) bool {
accept := acceptable(err)
if !accept && err != nil {
lt.errWin.add(err.Error())
}
return accept
}))
}
func (lt loggedThrottle) logError(err error) error {
if errors.Is(err, ErrServiceUnavailable) {
// if circuit open, not possible to have empty error window
stat.Report(fmt.Sprintf(
"proc(%s/%d), callee: %s, breaker is open and requests dropped\nlast errors:\n%s",
proc.ProcessName(), proc.Pid(), lt.name, lt.errWin))
}
return err
}
type errorWindow struct {
reasons [numHistoryReasons]string
index int
count int
lock sync.Mutex
}
func (ew *errorWindow) add(reason string) {
ew.lock.Lock()
ew.reasons[ew.index] = fmt.Sprintf("%s %s", time.Now().Format(time.TimeOnly), reason)
ew.index = (ew.index + 1) % numHistoryReasons
ew.count = min(ew.count+1, numHistoryReasons)
ew.lock.Unlock()
}
func (ew *errorWindow) String() string {
reasons := make([]string, 0, ew.count)
ew.lock.Lock()
// reverse order
for i := ew.index - 1; i >= ew.index-ew.count; i-- {
reasons = append(reasons, ew.reasons[(i+numHistoryReasons)%numHistoryReasons])
}
ew.lock.Unlock()
return strings.Join(reasons, "\n")
}
type promiseWithReason struct {
promise internalPromise
errWin *errorWindow
}
func (p promiseWithReason) Accept() {
p.promise.Accept()
}
func (p promiseWithReason) Reject(reason string) {
p.errWin.add(reason)
p.promise.Reject()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/breaker/googlebreaker_test.go | core/breaker/googlebreaker_test.go | package breaker
import (
"errors"
"math/rand"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/syncx"
)
const (
testBuckets = 10
testInterval = time.Millisecond * 10
)
func init() {
stat.SetReporter(nil)
}
func getGoogleBreaker() *googleBreaker {
st := collection.NewRollingWindow[int64, *bucket](func() *bucket {
return new(bucket)
}, testBuckets, testInterval)
return &googleBreaker{
stat: st,
k: 5,
proba: mathx.NewProba(),
lastPass: syncx.NewAtomicDuration(),
}
}
func markSuccessWithDuration(b *googleBreaker, count int, sleep time.Duration) {
for i := 0; i < count; i++ {
b.markSuccess()
time.Sleep(sleep)
}
}
func markFailedWithDuration(b *googleBreaker, count int, sleep time.Duration) {
for i := 0; i < count; i++ {
b.markFailure()
time.Sleep(sleep)
}
}
func TestGoogleBreakerClose(t *testing.T) {
b := getGoogleBreaker()
markSuccess(b, 80)
assert.Nil(t, b.accept())
markSuccess(b, 120)
assert.Nil(t, b.accept())
}
func TestGoogleBreakerOpen(t *testing.T) {
b := getGoogleBreaker()
markSuccess(b, 10)
assert.Nil(t, b.accept())
markFailed(b, 100000)
time.Sleep(testInterval * 2)
verify(t, func() bool {
return b.accept() != nil
})
}
func TestGoogleBreakerRecover(t *testing.T) {
st := collection.NewRollingWindow[int64, *bucket](func() *bucket {
return new(bucket)
}, testBuckets*2, testInterval)
b := &googleBreaker{
stat: st,
k: k,
proba: mathx.NewProba(),
lastPass: syncx.NewAtomicDuration(),
}
for i := 0; i < testBuckets; i++ {
for j := 0; j < 100; j++ {
b.stat.Add(1)
}
time.Sleep(testInterval)
}
for i := 0; i < testBuckets; i++ {
for j := 0; j < 100; j++ {
b.stat.Add(0)
}
time.Sleep(testInterval)
}
verify(t, func() bool {
return b.accept() == nil
})
}
func TestGoogleBreakerFallback(t *testing.T) {
b := getGoogleBreaker()
markSuccess(b, 1)
assert.Nil(t, b.accept())
markFailed(b, 10000)
time.Sleep(testInterval * 2)
verify(t, func() bool {
return b.doReq(func() error {
return errors.New("any")
}, func(err error) error {
return nil
}, defaultAcceptable) == nil
})
}
func TestGoogleBreakerReject(t *testing.T) {
b := getGoogleBreaker()
markSuccess(b, 100)
assert.Nil(t, b.accept())
markFailed(b, 10000)
time.Sleep(testInterval)
assert.Equal(t, ErrServiceUnavailable, b.doReq(func() error {
return ErrServiceUnavailable
}, nil, defaultAcceptable))
}
func TestGoogleBreakerMoreFallingBuckets(t *testing.T) {
t.Parallel()
t.Run("more falling buckets", func(t *testing.T) {
b := getGoogleBreaker()
func() {
stopChan := time.After(testInterval * 6)
for {
time.Sleep(time.Millisecond)
select {
case <-stopChan:
return
default:
assert.Error(t, b.doReq(func() error {
return errors.New("foo")
}, func(err error) error {
return err
}, func(err error) bool {
return err == nil
}))
}
}
}()
var count int
for i := 0; i < 100; i++ {
if errors.Is(b.doReq(func() error {
return ErrServiceUnavailable
}, nil, defaultAcceptable), ErrServiceUnavailable) {
count++
}
}
assert.True(t, count > 90)
})
}
func TestGoogleBreakerAcceptable(t *testing.T) {
b := getGoogleBreaker()
errAcceptable := errors.New("any")
assert.Equal(t, errAcceptable, b.doReq(func() error {
return errAcceptable
}, nil, func(err error) bool {
return errors.Is(err, errAcceptable)
}))
}
func TestGoogleBreakerNotAcceptable(t *testing.T) {
b := getGoogleBreaker()
errAcceptable := errors.New("any")
assert.Equal(t, errAcceptable, b.doReq(func() error {
return errAcceptable
}, nil, func(err error) bool {
return !errors.Is(err, errAcceptable)
}))
}
func TestGoogleBreakerPanic(t *testing.T) {
b := getGoogleBreaker()
assert.Panics(t, func() {
_ = b.doReq(func() error {
panic("fail")
}, nil, defaultAcceptable)
})
}
func TestGoogleBreakerHalfOpen(t *testing.T) {
b := getGoogleBreaker()
assert.Nil(t, b.accept())
t.Run("accept single failed/accept", func(t *testing.T) {
markFailed(b, 10000)
time.Sleep(testInterval * 2)
verify(t, func() bool {
return b.accept() != nil
})
})
t.Run("accept single failed/allow", func(t *testing.T) {
markFailed(b, 10000)
time.Sleep(testInterval * 2)
verify(t, func() bool {
_, err := b.allow()
return err != nil
})
})
time.Sleep(testInterval * testBuckets)
t.Run("accept single succeed", func(t *testing.T) {
assert.Nil(t, b.accept())
markSuccess(b, 10000)
verify(t, func() bool {
return b.accept() == nil
})
})
}
func TestGoogleBreakerSelfProtection(t *testing.T) {
t.Run("total request < 100", func(t *testing.T) {
b := getGoogleBreaker()
markFailed(b, 4)
time.Sleep(testInterval)
assert.Nil(t, b.accept())
})
t.Run("total request > 100, total < 2 * success", func(t *testing.T) {
b := getGoogleBreaker()
size := rand.Intn(10000)
accepts := size + 1
markSuccess(b, accepts)
markFailed(b, size-accepts)
assert.Nil(t, b.accept())
})
}
func TestGoogleBreakerHistory(t *testing.T) {
sleep := testInterval
t.Run("accepts == total", func(t *testing.T) {
b := getGoogleBreaker()
markSuccessWithDuration(b, 10, sleep/2)
result := b.history()
assert.Equal(t, int64(10), result.accepts)
assert.Equal(t, int64(10), result.total)
})
t.Run("fail == total", func(t *testing.T) {
b := getGoogleBreaker()
markFailedWithDuration(b, 10, sleep/2)
result := b.history()
assert.Equal(t, int64(0), result.accepts)
assert.Equal(t, int64(10), result.total)
})
t.Run("accepts = 1/2 * total, fail = 1/2 * total", func(t *testing.T) {
b := getGoogleBreaker()
markFailedWithDuration(b, 5, sleep/2)
markSuccessWithDuration(b, 5, sleep/2)
result := b.history()
assert.Equal(t, int64(5), result.accepts)
assert.Equal(t, int64(10), result.total)
})
t.Run("auto reset rolling counter", func(t *testing.T) {
b := getGoogleBreaker()
time.Sleep(testInterval * testBuckets)
result := b.history()
assert.Equal(t, int64(0), result.accepts)
assert.Equal(t, int64(0), result.total)
})
}
func BenchmarkGoogleBreakerAllow(b *testing.B) {
breaker := getGoogleBreaker()
b.ResetTimer()
for i := 0; i <= b.N; i++ {
_ = breaker.accept()
if i%2 == 0 {
breaker.markSuccess()
} else {
breaker.markFailure()
}
}
}
func BenchmarkGoogleBreakerDoReq(b *testing.B) {
breaker := getGoogleBreaker()
b.ResetTimer()
for i := 0; i <= b.N; i++ {
_ = breaker.doReq(func() error {
return nil
}, nil, defaultAcceptable)
}
}
func markSuccess(b *googleBreaker, count int) {
for i := 0; i < count; i++ {
p, err := b.allow()
if err != nil {
break
}
p.Accept()
}
}
func markFailed(b *googleBreaker, count int) {
for i := 0; i < count; i++ {
p, err := b.allow()
if err == nil {
p.Reject()
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/hash/hash.go | core/hash/hash.go | package hash
import (
"crypto/md5"
"encoding/hex"
"github.com/spaolacci/murmur3"
)
// Hash returns the hash value of data.
func Hash(data []byte) uint64 {
return murmur3.Sum64(data)
}
// Md5 returns the md5 bytes of data.
func Md5(data []byte) []byte {
digest := md5.New()
digest.Write(data)
return digest.Sum(nil)
}
// Md5Hex returns the md5 hex string of data.
// This function is optimized for better performance than fmt.Sprintf.
func Md5Hex(data []byte) string {
return hex.EncodeToString(Md5(data))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/hash/hash_test.go | core/hash/hash_test.go | package hash
import (
"crypto/md5"
"fmt"
"hash/fnv"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
)
const (
text = "hello, world!\n"
md5Digest = "910c8bc73110b0cd1bc5d2bcae782511"
)
func TestMd5(t *testing.T) {
actual := fmt.Sprintf("%x", Md5([]byte(text)))
assert.Equal(t, md5Digest, actual)
}
func TestMd5Hex(t *testing.T) {
actual := Md5Hex([]byte(text))
assert.Equal(t, md5Digest, actual)
}
func BenchmarkHashFnv(b *testing.B) {
for i := 0; i < b.N; i++ {
h := fnv.New32()
new(big.Int).SetBytes(h.Sum([]byte(text))).Int64()
}
}
func BenchmarkHashMd5(b *testing.B) {
for i := 0; i < b.N; i++ {
h := md5.New()
bytes := h.Sum([]byte(text))
new(big.Int).SetBytes(bytes).Int64()
}
}
func BenchmarkMurmur3(b *testing.B) {
for i := 0; i < b.N; i++ {
Hash([]byte(text))
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/hash/consistenthash.go | core/hash/consistenthash.go | package hash
import (
"fmt"
"sort"
"strconv"
"sync"
"github.com/zeromicro/go-zero/core/lang"
)
const (
// TopWeight is the top weight that one entry might set.
TopWeight = 100
minReplicas = 100
prime = 16777619
)
type (
// Func defines the hash method.
Func func(data []byte) uint64
// A ConsistentHash is a ring hash implementation.
ConsistentHash struct {
hashFunc Func
replicas int
keys []uint64
ring map[uint64][]any
nodes map[string]lang.PlaceholderType
lock sync.RWMutex
}
)
// NewConsistentHash returns a ConsistentHash.
func NewConsistentHash() *ConsistentHash {
return NewCustomConsistentHash(minReplicas, Hash)
}
// NewCustomConsistentHash returns a ConsistentHash with given replicas and hash func.
func NewCustomConsistentHash(replicas int, fn Func) *ConsistentHash {
if replicas < minReplicas {
replicas = minReplicas
}
if fn == nil {
fn = Hash
}
return &ConsistentHash{
hashFunc: fn,
replicas: replicas,
ring: make(map[uint64][]any),
nodes: make(map[string]lang.PlaceholderType),
}
}
// Add adds the node with the number of h.replicas,
// the later call will overwrite the replicas of the former calls.
func (h *ConsistentHash) Add(node any) {
h.AddWithReplicas(node, h.replicas)
}
// AddWithReplicas adds the node with the number of replicas,
// replicas will be truncated to h.replicas if it's larger than h.replicas,
// the later call will overwrite the replicas of the former calls.
func (h *ConsistentHash) AddWithReplicas(node any, replicas int) {
h.Remove(node)
if replicas > h.replicas {
replicas = h.replicas
}
nodeRepr := repr(node)
h.lock.Lock()
defer h.lock.Unlock()
h.addNode(nodeRepr)
for i := 0; i < replicas; i++ {
hash := h.hashFunc([]byte(nodeRepr + strconv.Itoa(i)))
h.keys = append(h.keys, hash)
h.ring[hash] = append(h.ring[hash], node)
}
sort.Slice(h.keys, func(i, j int) bool {
return h.keys[i] < h.keys[j]
})
}
// AddWithWeight adds the node with weight, the weight can be 1 to 100, indicates the percent,
// the later call will overwrite the replicas of the former calls.
func (h *ConsistentHash) AddWithWeight(node any, weight int) {
// don't need to make sure weight not larger than TopWeight,
// because AddWithReplicas makes sure replicas cannot be larger than h.replicas
replicas := h.replicas * weight / TopWeight
h.AddWithReplicas(node, replicas)
}
// Get returns the corresponding node from h based on the given v.
func (h *ConsistentHash) Get(v any) (any, bool) {
h.lock.RLock()
defer h.lock.RUnlock()
if len(h.ring) == 0 {
return nil, false
}
hash := h.hashFunc([]byte(repr(v)))
index := sort.Search(len(h.keys), func(i int) bool {
return h.keys[i] >= hash
}) % len(h.keys)
nodes := h.ring[h.keys[index]]
switch len(nodes) {
case 0:
return nil, false
case 1:
return nodes[0], true
default:
innerIndex := h.hashFunc([]byte(innerRepr(v)))
pos := int(innerIndex % uint64(len(nodes)))
return nodes[pos], true
}
}
// Remove removes the given node from h.
func (h *ConsistentHash) Remove(node any) {
nodeRepr := repr(node)
h.lock.Lock()
defer h.lock.Unlock()
if !h.containsNode(nodeRepr) {
return
}
for i := 0; i < h.replicas; i++ {
hash := h.hashFunc([]byte(nodeRepr + strconv.Itoa(i)))
index := sort.Search(len(h.keys), func(i int) bool {
return h.keys[i] >= hash
})
if index < len(h.keys) && h.keys[index] == hash {
h.keys = append(h.keys[:index], h.keys[index+1:]...)
}
h.removeRingNode(hash, nodeRepr)
}
h.removeNode(nodeRepr)
}
func (h *ConsistentHash) removeRingNode(hash uint64, nodeRepr string) {
if nodes, ok := h.ring[hash]; ok {
newNodes := nodes[:0]
for _, x := range nodes {
if repr(x) != nodeRepr {
newNodes = append(newNodes, x)
}
}
if len(newNodes) > 0 {
h.ring[hash] = newNodes
} else {
delete(h.ring, hash)
}
}
}
func (h *ConsistentHash) addNode(nodeRepr string) {
h.nodes[nodeRepr] = lang.Placeholder
}
func (h *ConsistentHash) containsNode(nodeRepr string) bool {
_, ok := h.nodes[nodeRepr]
return ok
}
func (h *ConsistentHash) removeNode(nodeRepr string) {
delete(h.nodes, nodeRepr)
}
func innerRepr(node any) string {
return fmt.Sprintf("%d:%v", prime, node)
}
func repr(node any) string {
return lang.Repr(node)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/hash/consistenthash_test.go | core/hash/consistenthash_test.go | package hash
import (
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/mathx"
)
const (
keySize = 20
requestSize = 1000
)
func BenchmarkConsistentHashGet(b *testing.B) {
ch := NewConsistentHash()
for i := 0; i < keySize; i++ {
ch.Add("localhost:" + strconv.Itoa(i))
}
for i := 0; i < b.N; i++ {
ch.Get(i)
}
}
func TestConsistentHash(t *testing.T) {
ch := NewCustomConsistentHash(0, nil)
val, ok := ch.Get("any")
assert.False(t, ok)
assert.Nil(t, val)
for i := 0; i < keySize; i++ {
ch.AddWithReplicas("localhost:"+strconv.Itoa(i), minReplicas<<1)
}
keys := make(map[string]int)
for i := 0; i < requestSize; i++ {
key, ok := ch.Get(requestSize + i)
assert.True(t, ok)
keys[key.(string)]++
}
mi := make(map[any]int, len(keys))
for k, v := range keys {
mi[k] = v
}
entropy := mathx.CalcEntropy(mi)
assert.True(t, entropy > .95)
}
func TestConsistentHashIncrementalTransfer(t *testing.T) {
prefix := "anything"
create := func() *ConsistentHash {
ch := NewConsistentHash()
for i := 0; i < keySize; i++ {
ch.Add(prefix + strconv.Itoa(i))
}
return ch
}
originCh := create()
keys := make(map[int]string, requestSize)
for i := 0; i < requestSize; i++ {
key, ok := originCh.Get(requestSize + i)
assert.True(t, ok)
assert.NotNil(t, key)
keys[i] = key.(string)
}
node := fmt.Sprintf("%s%d", prefix, keySize)
for i := 0; i < 10; i++ {
laterCh := create()
laterCh.AddWithWeight(node, 10*(i+1))
for j := 0; j < requestSize; j++ {
key, ok := laterCh.Get(requestSize + j)
assert.True(t, ok)
assert.NotNil(t, key)
value := key.(string)
assert.True(t, value == keys[j] || value == node)
}
}
}
func TestConsistentHashTransferOnFailure(t *testing.T) {
index := 41
ratioNotExists := getTransferRatioOnFailure(t, index)
assert.True(t, ratioNotExists == 0, fmt.Sprintf("%d: %f", index, ratioNotExists))
index = 13
ratio := getTransferRatioOnFailure(t, index)
assert.True(t, ratio < 2.5/keySize, fmt.Sprintf("%d: %f", index, ratio))
}
func TestConsistentHashLeastTransferOnFailure(t *testing.T) {
prefix := "localhost:"
index := 13
keys, newKeys := getKeysBeforeAndAfterFailure(t, prefix, index)
for k, v := range keys {
newV := newKeys[k]
if v != prefix+strconv.Itoa(index) {
assert.Equal(t, v, newV)
}
}
}
func TestConsistentHash_Remove(t *testing.T) {
ch := NewConsistentHash()
ch.Add("first")
ch.Add("second")
ch.Remove("first")
for i := 0; i < 100; i++ {
val, ok := ch.Get(i)
assert.True(t, ok)
assert.Equal(t, "second", val)
}
}
func TestConsistentHash_RemoveInterface(t *testing.T) {
const key = "any"
ch := NewConsistentHash()
node1 := newMockNode(key, 1)
node2 := newMockNode(key, 2)
ch.AddWithWeight(node1, 80)
ch.AddWithWeight(node2, 50)
assert.Equal(t, 1, len(ch.nodes))
node, ok := ch.Get(1)
assert.True(t, ok)
assert.Equal(t, key, node.(*mockNode).addr)
assert.Equal(t, 2, node.(*mockNode).id)
}
func getKeysBeforeAndAfterFailure(t *testing.T, prefix string, index int) (map[int]string, map[int]string) {
ch := NewConsistentHash()
for i := 0; i < keySize; i++ {
ch.Add(prefix + strconv.Itoa(i))
}
keys := make(map[int]string, requestSize)
for i := 0; i < requestSize; i++ {
key, ok := ch.Get(requestSize + i)
assert.True(t, ok)
assert.NotNil(t, key)
keys[i] = key.(string)
}
remove := fmt.Sprintf("%s%d", prefix, index)
ch.Remove(remove)
newKeys := make(map[int]string, requestSize)
for i := 0; i < requestSize; i++ {
key, ok := ch.Get(requestSize + i)
assert.True(t, ok)
assert.NotNil(t, key)
assert.NotEqual(t, remove, key)
newKeys[i] = key.(string)
}
return keys, newKeys
}
func getTransferRatioOnFailure(t *testing.T, index int) float32 {
keys, newKeys := getKeysBeforeAndAfterFailure(t, "localhost:", index)
var transferred int
for k, v := range newKeys {
if v != keys[k] {
transferred++
}
}
return float32(transferred) / float32(requestSize)
}
type mockNode struct {
addr string
id int
}
func newMockNode(addr string, id int) *mockNode {
return &mockNode{
addr: addr,
id: id,
}
}
func (n *mockNode) String() string {
return n.addr
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/limit/periodlimit_test.go | core/limit/periodlimit_test.go | package limit
import (
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
)
func TestPeriodLimit_Take(t *testing.T) {
testPeriodLimit(t)
}
func TestPeriodLimit_TakeWithAlign(t *testing.T) {
testPeriodLimit(t, Align())
}
func TestPeriodLimit_RedisUnavailable(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
const (
seconds = 1
quota = 5
)
l := NewPeriodLimit(seconds, quota, redis.New(s.Addr()), "periodlimit")
s.Close()
val, err := l.Take("first")
assert.NotNil(t, err)
assert.Equal(t, 0, val)
}
func testPeriodLimit(t *testing.T, opts ...PeriodOption) {
store := redistest.CreateRedis(t)
const (
seconds = 1
total = 100
quota = 5
)
l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
var allowed, hitQuota, overQuota int
for i := 0; i < total; i++ {
val, err := l.Take("first")
if err != nil {
t.Error(err)
}
switch val {
case Allowed:
allowed++
case HitQuota:
hitQuota++
case OverQuota:
overQuota++
default:
t.Error("unknown status")
}
}
assert.Equal(t, quota-1, allowed)
assert.Equal(t, 1, hitQuota)
assert.Equal(t, total-quota, overQuota)
}
func TestQuotaFull(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
l := NewPeriodLimit(1, 1, redis.New(s.Addr()), "periodlimit")
val, err := l.Take("first")
assert.Nil(t, err)
assert.Equal(t, HitQuota, val)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/limit/periodlimit.go | core/limit/periodlimit.go | package limit
import (
"context"
_ "embed"
"errors"
"strconv"
"time"
"github.com/zeromicro/go-zero/core/stores/redis"
)
const (
// Unknown means not initialized state.
Unknown = iota
// Allowed means allowed state.
Allowed
// HitQuota means this request exactly hit the quota.
HitQuota
// OverQuota means passed the quota.
OverQuota
internalOverQuota = 0
internalAllowed = 1
internalHitQuota = 2
)
var (
// ErrUnknownCode is an error that represents unknown status code.
ErrUnknownCode = errors.New("unknown status code")
//go:embed periodscript.lua
periodLuaScript string
periodScript = redis.NewScript(periodLuaScript)
)
type (
// PeriodOption defines the method to customize a PeriodLimit.
PeriodOption func(l *PeriodLimit)
// A PeriodLimit is used to limit requests during a period of time.
PeriodLimit struct {
period int
quota int
limitStore *redis.Redis
keyPrefix string
align bool
}
)
// NewPeriodLimit returns a PeriodLimit with given parameters.
func NewPeriodLimit(period, quota int, limitStore *redis.Redis, keyPrefix string,
opts ...PeriodOption) *PeriodLimit {
limiter := &PeriodLimit{
period: period,
quota: quota,
limitStore: limitStore,
keyPrefix: keyPrefix,
}
for _, opt := range opts {
opt(limiter)
}
return limiter
}
// Take requests a permit, it returns the permit state.
func (h *PeriodLimit) Take(key string) (int, error) {
return h.TakeCtx(context.Background(), key)
}
// TakeCtx requests a permit with context, it returns the permit state.
func (h *PeriodLimit) TakeCtx(ctx context.Context, key string) (int, error) {
resp, err := h.limitStore.ScriptRunCtx(ctx, periodScript, []string{h.keyPrefix + key}, []string{
strconv.Itoa(h.quota),
strconv.Itoa(h.calcExpireSeconds()),
})
if err != nil {
return Unknown, err
}
code, ok := resp.(int64)
if !ok {
return Unknown, ErrUnknownCode
}
switch code {
case internalOverQuota:
return OverQuota, nil
case internalAllowed:
return Allowed, nil
case internalHitQuota:
return HitQuota, nil
default:
return Unknown, ErrUnknownCode
}
}
func (h *PeriodLimit) calcExpireSeconds() int {
if h.align {
now := time.Now()
_, offset := now.Zone()
unix := now.Unix() + int64(offset)
return h.period - int(unix%int64(h.period))
}
return h.period
}
// Align returns a func to customize a PeriodLimit with alignment.
// For example, if we want to limit end users with 5 sms verification messages every day,
// we need to align with the local timezone and the start of the day.
func Align() PeriodOption {
return func(l *PeriodLimit) {
l.align = true
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/limit/tokenlimit_test.go | core/limit/tokenlimit_test.go | package limit
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
)
func init() {
logx.Disable()
}
func TestTokenLimit_WithCtx(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
const (
total = 100
rate = 5
burst = 10
)
l := NewTokenLimiter(rate, burst, redis.New(s.Addr()), "tokenlimit")
defer s.Close()
ctx, cancel := context.WithCancel(context.Background())
ok := l.AllowCtx(ctx)
assert.True(t, ok)
cancel()
for i := 0; i < total; i++ {
ok := l.AllowCtx(ctx)
assert.False(t, ok)
assert.False(t, l.monitorStarted)
}
}
func TestTokenLimit_Rescue(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
const (
total = 100
rate = 5
burst = 10
)
l := NewTokenLimiter(rate, burst, redis.New(s.Addr()), "tokenlimit")
s.Close()
var allowed int
for i := 0; i < total; i++ {
time.Sleep(time.Second / time.Duration(total))
if i == total>>1 {
assert.Nil(t, s.Restart())
}
if l.Allow() {
allowed++
}
// make sure start monitor more than once doesn't matter
l.startMonitor()
}
assert.True(t, allowed >= burst+rate)
}
func TestTokenLimit_Take(t *testing.T) {
store := redistest.CreateRedis(t)
const (
total = 100
rate = 5
burst = 10
)
l := NewTokenLimiter(rate, burst, store, "tokenlimit")
var allowed int
for i := 0; i < total; i++ {
time.Sleep(time.Second / time.Duration(total))
if l.Allow() {
allowed++
}
}
assert.True(t, allowed >= burst+rate)
}
func TestTokenLimit_TakeBurst(t *testing.T) {
store := redistest.CreateRedis(t)
const (
total = 100
rate = 5
burst = 10
)
l := NewTokenLimiter(rate, burst, store, "tokenlimit")
var allowed int
for i := 0; i < total; i++ {
if l.Allow() {
allowed++
}
}
assert.True(t, allowed >= burst)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/limit/tokenlimit.go | core/limit/tokenlimit.go | package limit
import (
"context"
_ "embed"
"errors"
"fmt"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
xrate "golang.org/x/time/rate"
)
const (
tokenFormat = "{%s}.tokens"
timestampFormat = "{%s}.ts"
pingInterval = time.Millisecond * 100
)
var (
//go:embed tokenscript.lua
tokenLuaScript string
tokenScript = redis.NewScript(tokenLuaScript)
)
// A TokenLimiter controls how frequently events are allowed to happen with in one second.
type TokenLimiter struct {
rate int
burst int
store *redis.Redis
tokenKey string
timestampKey string
rescueLock sync.Mutex
redisAlive uint32
monitorStarted bool
rescueLimiter *xrate.Limiter
}
// NewTokenLimiter returns a new TokenLimiter that allows events up to rate and permits
// bursts of at most burst tokens.
func NewTokenLimiter(rate, burst int, store *redis.Redis, key string) *TokenLimiter {
tokenKey := fmt.Sprintf(tokenFormat, key)
timestampKey := fmt.Sprintf(timestampFormat, key)
return &TokenLimiter{
rate: rate,
burst: burst,
store: store,
tokenKey: tokenKey,
timestampKey: timestampKey,
redisAlive: 1,
rescueLimiter: xrate.NewLimiter(xrate.Every(time.Second/time.Duration(rate)), burst),
}
}
// Allow is shorthand for AllowN(time.Now(), 1).
func (lim *TokenLimiter) Allow() bool {
return lim.AllowN(time.Now(), 1)
}
// AllowCtx is shorthand for AllowNCtx(ctx,time.Now(), 1) with incoming context.
func (lim *TokenLimiter) AllowCtx(ctx context.Context) bool {
return lim.AllowNCtx(ctx, time.Now(), 1)
}
// AllowN reports whether n events may happen at time now.
// Use this method if you intend to drop / skip events that exceed the rate.
// Otherwise, use Reserve or Wait.
func (lim *TokenLimiter) AllowN(now time.Time, n int) bool {
return lim.reserveN(context.Background(), now, n)
}
// AllowNCtx reports whether n events may happen at time now with incoming context.
// Use this method if you intend to drop / skip events that exceed the rate.
// Otherwise, use Reserve or Wait.
func (lim *TokenLimiter) AllowNCtx(ctx context.Context, now time.Time, n int) bool {
return lim.reserveN(ctx, now, n)
}
func (lim *TokenLimiter) reserveN(ctx context.Context, now time.Time, n int) bool {
if atomic.LoadUint32(&lim.redisAlive) == 0 {
return lim.rescueLimiter.AllowN(now, n)
}
resp, err := lim.store.ScriptRunCtx(ctx,
tokenScript,
[]string{
lim.tokenKey,
lim.timestampKey,
},
[]string{
strconv.Itoa(lim.rate),
strconv.Itoa(lim.burst),
strconv.FormatInt(now.Unix(), 10),
strconv.Itoa(n),
})
// redis allowed == false
// Lua boolean false -> r Nil bulk reply
if errors.Is(err, redis.Nil) {
return false
}
if errorx.In(err, context.DeadlineExceeded, context.Canceled) {
logx.Errorf("fail to use rate limiter: %s", err)
return false
}
if err != nil {
logx.Errorf("fail to use rate limiter: %s, use in-process limiter for rescue", err)
lim.startMonitor()
return lim.rescueLimiter.AllowN(now, n)
}
code, ok := resp.(int64)
if !ok {
logx.Errorf("fail to eval redis script: %v, use in-process limiter for rescue", resp)
lim.startMonitor()
return lim.rescueLimiter.AllowN(now, n)
}
// redis allowed == true
// Lua boolean true -> r integer reply with value of 1
return code == 1
}
func (lim *TokenLimiter) startMonitor() {
lim.rescueLock.Lock()
defer lim.rescueLock.Unlock()
if lim.monitorStarted {
return
}
lim.monitorStarted = true
atomic.StoreUint32(&lim.redisAlive, 0)
go lim.waitForRedis()
}
func (lim *TokenLimiter) waitForRedis() {
ticker := time.NewTicker(pingInterval)
defer func() {
ticker.Stop()
lim.rescueLock.Lock()
lim.monitorStarted = false
lim.rescueLock.Unlock()
}()
for range ticker.C {
if lim.store.Ping() {
atomic.StoreUint32(&lim.redisAlive, 1)
return
}
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/random_test.go | core/stringx/random_test.go | package stringx
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestRand(t *testing.T) {
Seed(time.Now().UnixNano())
assert.True(t, len(Rand()) > 0)
assert.True(t, len(RandId()) > 0)
const size = 10
assert.True(t, len(Randn(size)) == size)
}
func BenchmarkRandString(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Randn(10)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/strings_test.go | core/stringx/strings_test.go | package stringx
import (
"path"
"testing"
"github.com/stretchr/testify/assert"
)
func TestContainsString(t *testing.T) {
cases := []struct {
slice []string
value string
expect bool
}{
{[]string{"1"}, "1", true},
{[]string{"1"}, "2", false},
{[]string{"1", "2"}, "1", true},
{[]string{"1", "2"}, "3", false},
{nil, "3", false},
{nil, "", false},
}
for _, each := range cases {
t.Run(path.Join(each.slice...), func(t *testing.T) {
actual := Contains(each.slice, each.value)
assert.Equal(t, each.expect, actual)
})
}
}
func TestNotEmpty(t *testing.T) {
cases := []struct {
args []string
expect bool
}{
{
args: []string{"a", "b", "c"},
expect: true,
},
{
args: []string{"a", "", "c"},
expect: false,
},
{
args: []string{"a"},
expect: true,
},
{
args: []string{""},
expect: false,
},
{
args: []string{},
expect: true,
},
}
for _, each := range cases {
t.Run(path.Join(each.args...), func(t *testing.T) {
assert.Equal(t, each.expect, NotEmpty(each.args...))
})
}
}
func TestFilter(t *testing.T) {
cases := []struct {
input string
ignores []rune
expect string
}{
{``, nil, ``},
{`abcd`, nil, `abcd`},
{`ab,cd,ef`, []rune{','}, `abcdef`},
{`ab, cd,ef`, []rune{',', ' '}, `abcdef`},
{`ab, cd, ef`, []rune{',', ' '}, `abcdef`},
{`ab, cd, ef, `, []rune{',', ' '}, `abcdef`},
}
for _, each := range cases {
t.Run(each.input, func(t *testing.T) {
actual := Filter(each.input, func(r rune) bool {
for _, x := range each.ignores {
if x == r {
return true
}
}
return false
})
assert.Equal(t, each.expect, actual)
})
}
}
func TestFirstN(t *testing.T) {
tests := []struct {
name string
input string
n int
ellipsis string
expect string
}{
{
name: "english string",
input: "anything that we use",
n: 8,
expect: "anything",
},
{
name: "english string with ellipsis",
input: "anything that we use",
n: 8,
ellipsis: "...",
expect: "anything...",
},
{
name: "english string more",
input: "anything that we use",
n: 80,
expect: "anything that we use",
},
{
name: "chinese string",
input: "我是中国人",
n: 2,
expect: "我是",
},
{
name: "chinese string with ellipsis",
input: "我是中国人",
n: 2,
ellipsis: "...",
expect: "我是...",
},
{
name: "chinese string",
input: "我是中国人",
n: 10,
expect: "我是中国人",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expect, FirstN(test.input, test.n, test.ellipsis))
})
}
}
func TestJoin(t *testing.T) {
tests := []struct {
name string
input []string
expect string
}{
{
name: "all blanks",
input: []string{"", ""},
expect: "",
},
{
name: "two values",
input: []string{"012", "abc"},
expect: "012.abc",
},
{
name: "last blank",
input: []string{"abc", ""},
expect: "abc",
},
{
name: "first blank",
input: []string{"", "abc"},
expect: "abc",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expect, Join('.', test.input...))
})
}
}
func TestRemove(t *testing.T) {
cases := []struct {
input []string
remove []string
expect []string
}{
{
input: []string{"a", "b", "a", "c"},
remove: []string{"a", "b"},
expect: []string{"c"},
},
{
input: []string{"b", "c"},
remove: []string{"a"},
expect: []string{"b", "c"},
},
{
input: []string{"b", "a", "c"},
remove: []string{"a"},
expect: []string{"b", "c"},
},
{
input: []string{},
remove: []string{"a"},
expect: []string{},
},
}
for _, each := range cases {
t.Run(path.Join(each.input...), func(t *testing.T) {
assert.ElementsMatch(t, each.expect, Remove(each.input, each.remove...))
})
}
}
func TestReverse(t *testing.T) {
cases := []struct {
input string
expect string
}{
{
input: "abcd",
expect: "dcba",
},
{
input: "",
expect: "",
},
{
input: "我爱中国",
expect: "国中爱我",
},
}
for _, each := range cases {
t.Run(each.input, func(t *testing.T) {
assert.Equal(t, each.expect, Reverse(each.input))
})
}
}
func TestSubstr(t *testing.T) {
cases := []struct {
input string
start int
stop int
err error
expect string
}{
{
input: "abcdefg",
start: 1,
stop: 4,
expect: "bcd",
},
{
input: "我爱中国3000遍,even more",
start: 1,
stop: 9,
expect: "爱中国3000遍",
},
{
input: "abcdefg",
start: -1,
stop: 4,
err: ErrInvalidStartPosition,
expect: "",
},
{
input: "abcdefg",
start: 100,
stop: 4,
err: ErrInvalidStartPosition,
expect: "",
},
{
input: "abcdefg",
start: 1,
stop: -1,
err: ErrInvalidStopPosition,
expect: "",
},
{
input: "abcdefg",
start: 1,
stop: 100,
err: ErrInvalidStopPosition,
expect: "",
},
}
for _, each := range cases {
t.Run(each.input, func(t *testing.T) {
val, err := Substr(each.input, each.start, each.stop)
assert.Equal(t, each.err, err)
if err == nil {
assert.Equal(t, each.expect, val)
}
})
}
}
func TestTakeOne(t *testing.T) {
cases := []struct {
valid string
or string
expect string
}{
{"", "", ""},
{"", "1", "1"},
{"1", "", "1"},
{"1", "2", "1"},
}
for _, each := range cases {
t.Run(each.valid, func(t *testing.T) {
actual := TakeOne(each.valid, each.or)
assert.Equal(t, each.expect, actual)
})
}
}
func TestTakeWithPriority(t *testing.T) {
tests := []struct {
fns []func() string
expect string
}{
{
fns: []func() string{
func() string {
return "first"
},
func() string {
return "second"
},
func() string {
return "third"
},
},
expect: "first",
},
{
fns: []func() string{
func() string {
return ""
},
func() string {
return "second"
},
func() string {
return "third"
},
},
expect: "second",
},
{
fns: []func() string{
func() string {
return ""
},
func() string {
return ""
},
func() string {
return "third"
},
},
expect: "third",
},
{
fns: []func() string{
func() string {
return ""
},
func() string {
return ""
},
func() string {
return ""
},
},
expect: "",
},
}
for _, test := range tests {
t.Run(RandId(), func(t *testing.T) {
val := TakeWithPriority(test.fns...)
assert.Equal(t, test.expect, val)
})
}
}
func TestToCamelCase(t *testing.T) {
tests := []struct {
input string
expect string
}{
{
input: "",
expect: "",
},
{
input: "A",
expect: "a",
},
{
input: "a",
expect: "a",
},
{
input: "hello_world",
expect: "hello_world",
},
{
input: "Hello_world",
expect: "hello_world",
},
{
input: "hello_World",
expect: "hello_World",
},
{
input: "helloWorld",
expect: "helloWorld",
},
{
input: "HelloWorld",
expect: "helloWorld",
},
{
input: "hello World",
expect: "hello World",
},
{
input: "Hello World",
expect: "hello World",
},
}
for _, test := range tests {
test := test
t.Run(test.input, func(t *testing.T) {
assert.Equal(t, test.expect, ToCamelCase(test.input))
})
}
}
func TestUnion(t *testing.T) {
first := []string{
"one",
"two",
"three",
}
second := []string{
"zero",
"two",
"three",
"four",
}
union := Union(first, second)
contains := func(v string) bool {
for _, each := range union {
if v == each {
return true
}
}
return false
}
assert.Equal(t, 5, len(union))
assert.True(t, contains("zero"))
assert.True(t, contains("one"))
assert.True(t, contains("two"))
assert.True(t, contains("three"))
assert.True(t, contains("four"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/replacer.go | core/stringx/replacer.go | package stringx
import (
"sort"
"strings"
)
// replace more than once to avoid overlapped keywords after replace.
// only try 2 times to avoid too many or infinite loops.
const replaceTimes = 2
type (
// Replacer interface wraps the Replace method.
Replacer interface {
Replace(text string) string
}
replacer struct {
*node
mapping map[string]string
}
)
// NewReplacer returns a Replacer.
func NewReplacer(mapping map[string]string) Replacer {
rep := &replacer{
node: new(node),
mapping: mapping,
}
for k := range mapping {
rep.add(k)
}
rep.build()
return rep
}
// Replace replaces text with given substitutes.
func (r *replacer) Replace(text string) string {
for i := 0; i < replaceTimes; i++ {
var replaced bool
if text, replaced = r.doReplace(text); !replaced {
return text
}
}
return text
}
func (r *replacer) doReplace(text string) (string, bool) {
chars := []rune(text)
scopes := r.find(chars)
if len(scopes) == 0 {
return text, false
}
sort.Slice(scopes, func(i, j int) bool {
if scopes[i].start < scopes[j].start {
return true
}
if scopes[i].start == scopes[j].start {
return scopes[i].stop > scopes[j].stop
}
return false
})
var buf strings.Builder
var index int
for i := 0; i < len(scopes); i++ {
scp := &scopes[i]
if scp.start < index {
continue
}
buf.WriteString(string(chars[index:scp.start]))
buf.WriteString(r.mapping[string(chars[scp.start:scp.stop])])
index = scp.stop
}
if index < len(chars) {
buf.WriteString(string(chars[index:]))
}
return buf.String(), true
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/trie.go | core/stringx/trie.go | package stringx
import "github.com/zeromicro/go-zero/core/lang"
const defaultMask = '*'
type (
// TrieOption defines the method to customize a Trie.
TrieOption func(trie *trieNode)
// A Trie is a tree implementation that used to find elements rapidly.
Trie interface {
Filter(text string) (string, []string, bool)
FindKeywords(text string) []string
}
trieNode struct {
node
mask rune
}
scope struct {
start int
stop int
}
)
// NewTrie returns a Trie.
func NewTrie(words []string, opts ...TrieOption) Trie {
n := new(trieNode)
for _, opt := range opts {
opt(n)
}
if n.mask == 0 {
n.mask = defaultMask
}
for _, word := range words {
n.add(word)
}
n.build()
return n
}
func (n *trieNode) Filter(text string) (sentence string, keywords []string, found bool) {
chars := []rune(text)
if len(chars) == 0 {
return text, nil, false
}
scopes := n.find(chars)
keywords = n.collectKeywords(chars, scopes)
for _, match := range scopes {
// we don't care about overlaps, not bringing a performance improvement
n.replaceWithAsterisk(chars, match.start, match.stop)
}
return string(chars), keywords, len(keywords) > 0
}
func (n *trieNode) FindKeywords(text string) []string {
chars := []rune(text)
if len(chars) == 0 {
return nil
}
scopes := n.find(chars)
return n.collectKeywords(chars, scopes)
}
func (n *trieNode) collectKeywords(chars []rune, scopes []scope) []string {
set := make(map[string]lang.PlaceholderType)
for _, v := range scopes {
set[string(chars[v.start:v.stop])] = lang.Placeholder
}
var i int
keywords := make([]string, len(set))
for k := range set {
keywords[i] = k
i++
}
return keywords
}
func (n *trieNode) replaceWithAsterisk(chars []rune, start, stop int) {
for i := start; i < stop; i++ {
chars[i] = n.mask
}
}
// WithMask customizes a Trie with keywords masked as given mask char.
func WithMask(mask rune) TrieOption {
return func(n *trieNode) {
n.mask = mask
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/node.go | core/stringx/node.go | package stringx
type node struct {
children map[rune]*node
fail *node
depth int
end bool
}
func (n *node) add(word string) {
chars := []rune(word)
if len(chars) == 0 {
return
}
nd := n
for i, char := range chars {
if nd.children == nil {
child := new(node)
child.depth = i + 1
nd.children = map[rune]*node{char: child}
nd = child
} else if child, ok := nd.children[char]; ok {
nd = child
} else {
child := new(node)
child.depth = i + 1
nd.children[char] = child
nd = child
}
}
nd.end = true
}
func (n *node) build() {
var nodes []*node
for _, child := range n.children {
child.fail = n
nodes = append(nodes, child)
}
for len(nodes) > 0 {
nd := nodes[0]
nodes = nodes[1:]
for key, child := range nd.children {
nodes = append(nodes, child)
cur := nd
for cur != nil {
if cur.fail == nil {
child.fail = n
break
}
if fail, ok := cur.fail.children[key]; ok {
child.fail = fail
break
}
cur = cur.fail
}
}
}
}
func (n *node) find(chars []rune) []scope {
var scopes []scope
size := len(chars)
cur := n
for i := 0; i < size; i++ {
child, ok := cur.children[chars[i]]
if ok {
cur = child
} else {
for cur != n {
cur = cur.fail
if child, ok = cur.children[chars[i]]; ok {
cur = child
break
}
}
if child == nil {
continue
}
}
for child != n {
if child.end {
scopes = append(scopes, scope{
start: i + 1 - child.depth,
stop: i + 1,
})
}
child = child.fail
}
}
return scopes
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/node_test.go | core/stringx/node_test.go | package stringx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFuzzNodeCase1(t *testing.T) {
keywords := []string{
"cs8Zh",
"G1OihlVuBz",
"K6azS2FBHjI",
"DQKvghI4",
"l7bA86Sze",
"tjBLZhCao",
"nEsXmVzP",
"cbRh8UE1nO3s",
"Wta3R2WcbGP",
"jpOIcA",
"TtkRr4k9hI",
"OKbSo0clAYTtk",
"uJs1WToEanlKV",
"05Y02iFD2",
"x2uJs1WToEanlK",
"ieaSWe",
"Kg",
"FD2bCKFazH",
}
scopes := []scope{
{62, 72},
{52, 65},
{21, 34},
{1, 10},
{19, 33},
{36, 42},
{42, 44},
{7, 17},
}
n := new(node)
for _, key := range keywords {
n.add(key)
}
n.build()
assert.ElementsMatch(t, scopes, n.find([]rune("Z05Y02iFD2bCKFazHtrx2uJs1WToEanlKVWKieaSWeKgmnUXV0ZjOKbSo0clAYTtkRr4k9hI")))
}
func TestFuzzNodeCase2(t *testing.T) {
keywords := []string{
"IP1NPsJKIvt",
"Iw7hQARwSTw",
"SmZIcA",
"OyxHPYkoQzFO",
"3suCnuSAS5d",
"HUMpbi",
"HPdvbGGpY",
"49qjMtR8bEt",
"a0zrrGKVTJ2",
"WbOBcszeo1FfZ",
"8tHUi5PJI",
"Oa2Di",
"6ZWa5nr1tU",
"o0LJRfmeXB9bF9",
"veF0ehKxH",
"Qp73r",
"B6Rmds4ELY8",
"uNpGybQZG",
"Ogm3JqicRZlA4n",
"FL6LVErKomc84H",
"qv2Pi0xJj3cR1",
"bPWLBg4",
"hYN8Q4M1sw",
"ExkTgNklmlIx",
"eVgHHDOxOUEj",
"5WPEVv0tR",
"CPjnOAqUZgV",
"oR3Ogtz",
"jwk1Zbg",
"DYqguyk8h",
"rieroDmpvYFK",
"MQ9hZnMjDqrNQe",
"EhM4KqkCBd",
"m9xalj6q",
"d5CTL5mzK",
"XJOoTvFtI8U",
"iFAwspJ",
"iGv8ErnRZIuSWX",
"i8C1BqsYX",
"vXN1KOaOgU",
"GHJFB",
"Y6OlAqbZxYG8",
"dzd4QscSih4u",
"SsLYMkKvB9APx",
"gi0huB3",
"CMICHDCSvSrgiACXVkN",
"MwOvyHbaxdaqpZpU",
"wOvyHbaxdaqpZpUbI",
"2TT5WEy",
"eoCq0T2MC",
"ZpUbI7",
"oCq0T2MCp",
"CpLFgLg0g",
"FgLg0gh",
"w5awC5HeoCq",
"1c",
}
scopes := []scope{
{0, 19},
{57, 73},
{58, 75},
{47, 54},
{29, 38},
{70, 76},
{30, 39},
{37, 46},
{40, 47},
{22, 33},
{92, 94},
}
n := new(node)
for _, key := range keywords {
n.add(key)
}
n.build()
assert.ElementsMatch(t, scopes, n.find([]rune("CMICHDCSvSrgiACXVkNF9lw5awC5HeoCq0T2MCpLFgLg0gh2TT5WEyINrMwOvyHbaxdaqpZpUbI7SpIY5yVWf33MuX7K1c")))
}
func TestFuzzNodeCase3(t *testing.T) {
keywords := []string{
"QAraACKOftI4",
"unRmd2EO0",
"s25OtuoU",
"aGlmn7KnbE4HCX",
"kuK6Uh",
"ckuK6Uh",
"uK6Uh",
"Iy",
"h",
"PMSSUNvyi",
"ahz0i",
"Lhs4XZ1e",
"shPp1Va7aQNVme",
"yIUckuK6Uh",
"pKjIyI",
"jIyIUckuK6Uh",
"UckuK6Uh",
"Uh",
"JPAULjQgHJ",
"Wp",
"sbkZxXurrI",
"pKjIyIUckuK6Uh",
}
scopes := []scope{
{9, 15},
{8, 15},
{5, 15},
{1, 7},
{10, 15},
{3, 15},
{0, 2},
{1, 15},
{7, 15},
{13, 15},
{4, 6},
{14, 15},
}
n := new(node)
for _, key := range keywords {
n.add(key)
}
n.build()
assert.ElementsMatch(t, scopes, n.find([]rune("WpKjIyIUckuK6Uh")))
}
func BenchmarkNodeFind(b *testing.B) {
b.ReportAllocs()
keywords := []string{
"A",
"AV",
"AV演员",
"无名氏",
"AV演员色情",
"日本AV女优",
}
trie := new(node)
for _, keyword := range keywords {
trie.add(keyword)
}
trie.build()
for i := 0; i < b.N; i++ {
trie.find([]rune("日本AV演员兼电视、电影演员。无名氏AV女优是xx出道, 日本AV女优们最精彩的表演是AV演员色情表演"))
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/replacer_fuzz_test.go | core/stringx/replacer_fuzz_test.go | package stringx
import (
"fmt"
"math/rand"
"strings"
"testing"
)
func FuzzReplacerReplace(f *testing.F) {
keywords := make(map[string]string)
for i := 0; i < 20; i++ {
keywords[Randn(rand.Intn(10)+5)] = Randn(rand.Intn(5) + 1)
}
rep := NewReplacer(keywords)
printableKeywords := func() string {
var buf strings.Builder
for k, v := range keywords {
fmt.Fprintf(&buf, "%q: %q,\n", k, v)
}
return buf.String()
}
f.Add(50)
f.Fuzz(func(t *testing.T, n int) {
text := Randn(rand.Intn(n%50+50) + 1)
defer func() {
if r := recover(); r != nil {
t.Errorf("mapping: %s\ntext: %s", printableKeywords(), text)
}
}()
val := rep.Replace(text)
keys := rep.(*replacer).node.find([]rune(val))
if len(keys) > 0 {
t.Errorf("mapping: %s\ntext: %s\nresult: %s\nmatch: %v",
printableKeywords(), text, val, keys)
}
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/strings.go | core/stringx/strings.go | package stringx
import (
"errors"
"slices"
"unicode"
"github.com/zeromicro/go-zero/core/lang"
)
var (
// ErrInvalidStartPosition is an error that indicates the start position is invalid.
ErrInvalidStartPosition = errors.New("start position is invalid")
// ErrInvalidStopPosition is an error that indicates the stop position is invalid.
ErrInvalidStopPosition = errors.New("stop position is invalid")
)
// Contains checks if str is in list.
// Deprecated: use slices.Contains instead.
func Contains(list []string, str string) bool {
return slices.Contains(list, str)
}
// Filter filters chars from s with given filter function.
func Filter(s string, filter func(r rune) bool) string {
var n int
chars := []rune(s)
for i, x := range chars {
if n < i {
chars[n] = x
}
if !filter(x) {
n++
}
}
return string(chars[:n])
}
// FirstN returns first n runes from s.
func FirstN(s string, n int, ellipsis ...string) string {
var i int
for j := range s {
if i == n {
ret := s[:j]
for _, each := range ellipsis {
ret += each
}
return ret
}
i++
}
return s
}
// HasEmpty checks if there are empty strings in args.
func HasEmpty(args ...string) bool {
for _, arg := range args {
if len(arg) == 0 {
return true
}
}
return false
}
// Join joins any number of elements into a single string, separating them with given sep.
// Empty elements are ignored. However, if the argument list is empty or all its elements are empty,
// Join returns an empty string.
func Join(sep byte, elem ...string) string {
var size int
for _, e := range elem {
size += len(e)
}
if size == 0 {
return ""
}
buf := make([]byte, 0, size+len(elem)-1)
for _, e := range elem {
if len(e) == 0 {
continue
}
if len(buf) > 0 {
buf = append(buf, sep)
}
buf = append(buf, e...)
}
return string(buf)
}
// NotEmpty checks if all strings are not empty in args.
func NotEmpty(args ...string) bool {
return !HasEmpty(args...)
}
// Remove removes given strs from strings.
func Remove(strings []string, strs ...string) []string {
out := append([]string(nil), strings...)
for _, str := range strs {
var n int
for _, v := range out {
if v != str {
out[n] = v
n++
}
}
out = out[:n]
}
return out
}
// Reverse reverses s.
func Reverse(s string) string {
runes := []rune(s)
slices.Reverse(runes)
return string(runes)
}
// Substr returns runes between start and stop [start, stop)
// regardless of the chars are ascii or utf8.
func Substr(str string, start, stop int) (string, error) {
rs := []rune(str)
length := len(rs)
if start < 0 || start > length {
return "", ErrInvalidStartPosition
}
if stop < 0 || stop > length {
return "", ErrInvalidStopPosition
}
return string(rs[start:stop]), nil
}
// TakeOne returns valid string if not empty or later one.
func TakeOne(valid, or string) string {
if len(valid) > 0 {
return valid
}
return or
}
// TakeWithPriority returns the first not empty result from fns.
func TakeWithPriority(fns ...func() string) string {
for _, fn := range fns {
val := fn()
if len(val) > 0 {
return val
}
}
return ""
}
// ToCamelCase returns the string that converts the first letter to lowercase.
func ToCamelCase(s string) string {
for i, v := range s {
return string(unicode.ToLower(v)) + s[i+1:]
}
return ""
}
// Union merges the strings in first and second.
func Union(first, second []string) []string {
set := make(map[string]lang.PlaceholderType)
for _, each := range first {
set[each] = lang.Placeholder
}
for _, each := range second {
set[each] = lang.Placeholder
}
merged := make([]string, 0, len(set))
for k := range set {
merged = append(merged, k)
}
return merged
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/trie_test.go | core/stringx/trie_test.go | package stringx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTrieSimple(t *testing.T) {
trie := NewTrie([]string{
"bc",
"cd",
})
output, keywords, found := trie.Filter("abcd")
assert.True(t, found)
assert.Equal(t, "a***", output)
assert.ElementsMatch(t, []string{"bc", "cd"}, keywords)
}
func TestTrie(t *testing.T) {
tests := []struct {
input string
output string
keywords []string
found bool
}{
{
input: "日本AV演员兼电视、电影演员。无名氏AV女优是xx出道, 日本AV女优们最精彩的表演是AV演员色情表演",
output: "日本****兼电视、电影演员。*****女优是xx出道, ******们最精彩的表演是******表演",
keywords: []string{
"AV演员",
"无名氏",
"AV",
"日本AV女优",
"AV演员色情",
},
found: true,
},
{
input: "完全和谐的文本完全和谐的文本",
output: "完全和谐的文本完全和谐的文本",
keywords: nil,
found: false,
},
{
input: "就一个字不对",
output: "就*个字不对",
keywords: []string{
"一",
},
found: true,
},
{
input: "就一对, AV",
output: "就*对, **",
keywords: []string{
"一",
"AV",
},
found: true,
},
{
input: "就一不对, AV",
output: "就**对, **",
keywords: []string{
"一",
"一不",
"AV",
},
found: true,
},
{
input: "就对, AV",
output: "就对, **",
keywords: []string{
"AV",
},
found: true,
},
{
input: "就对, 一不",
output: "就对, **",
keywords: []string{
"一",
"一不",
},
found: true,
},
{
input: "",
output: "",
keywords: nil,
found: false,
},
}
trie := NewTrie([]string{
"", // no hurts for empty keywords
"一",
"一不",
"AV",
"AV演员",
"无名氏",
"AV演员色情",
"日本AV女优",
})
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
output, keywords, ok := trie.Filter(test.input)
assert.Equal(t, test.found, ok)
assert.Equal(t, test.output, output)
assert.ElementsMatch(t, test.keywords, keywords)
keywords = trie.FindKeywords(test.input)
assert.ElementsMatch(t, test.keywords, keywords)
})
}
}
func TestTrieSingleWord(t *testing.T) {
trie := NewTrie([]string{
"闹",
}, WithMask('#'))
output, keywords, ok := trie.Filter("今晚真热闹")
assert.ElementsMatch(t, []string{"闹"}, keywords)
assert.True(t, ok)
assert.Equal(t, "今晚真热#", output)
}
func TestTrieOverlap(t *testing.T) {
trie := NewTrie([]string{
"一二三四五",
"二三四五六七八",
}, WithMask('#'))
output, keywords, ok := trie.Filter("零一二三四五六七八九十")
assert.ElementsMatch(t, []string{
"一二三四五",
"二三四五六七八",
}, keywords)
assert.True(t, ok)
assert.Equal(t, "零########九十", output)
}
func TestTrieNested(t *testing.T) {
trie := NewTrie([]string{
"一二三",
"一二三四五",
"一二三四五六七八",
}, WithMask('#'))
output, keywords, ok := trie.Filter("零一二三四五六七八九十")
assert.ElementsMatch(t, []string{
"一二三",
"一二三四五",
"一二三四五六七八",
}, keywords)
assert.True(t, ok)
assert.Equal(t, "零########九十", output)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/replacer_test.go | core/stringx/replacer_test.go | package stringx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestReplacer_Replace(t *testing.T) {
mapping := map[string]string{
"一二三四": "1234",
"二三": "23",
"二": "2",
}
assert.Equal(t, "零1234五", NewReplacer(mapping).Replace("零一二三四五"))
}
func TestReplacer_ReplaceJumpMatch(t *testing.T) {
mapping := map[string]string{
"abcdeg": "ABCDEG",
"cdef": "CDEF",
"cde": "CDE",
}
assert.Equal(t, "abCDEF", NewReplacer(mapping).Replace("abcdef"))
}
func TestReplacer_ReplaceOverlap(t *testing.T) {
mapping := map[string]string{
"3d": "34",
"bc": "23",
}
assert.Equal(t, "a234e", NewReplacer(mapping).Replace("abcde"))
}
func TestReplacer_ReplaceSingleChar(t *testing.T) {
mapping := map[string]string{
"二": "2",
}
assert.Equal(t, "零一2三四五", NewReplacer(mapping).Replace("零一二三四五"))
}
func TestReplacer_ReplaceExceedRange(t *testing.T) {
mapping := map[string]string{
"二三四五六": "23456",
}
assert.Equal(t, "零一二三四五", NewReplacer(mapping).Replace("零一二三四五"))
}
func TestReplacer_ReplacePartialMatch(t *testing.T) {
mapping := map[string]string{
"二三四七": "2347",
}
assert.Equal(t, "零一二三四五", NewReplacer(mapping).Replace("零一二三四五"))
}
func TestReplacer_ReplacePartialMatchEnds(t *testing.T) {
mapping := map[string]string{
"二三四七": "2347",
"三四": "34",
}
assert.Equal(t, "零一二34", NewReplacer(mapping).Replace("零一二三四"))
}
func TestReplacer_ReplaceMultiMatches(t *testing.T) {
mapping := map[string]string{
"二三": "23",
}
assert.Equal(t, "零一23四五一23四五", NewReplacer(mapping).Replace("零一二三四五一二三四五"))
}
func TestReplacer_ReplaceLongestMatching(t *testing.T) {
keywords := map[string]string{
"日本": "japan",
"日本的首都": "东京",
}
replacer := NewReplacer(keywords)
assert.Equal(t, "东京在japan", replacer.Replace("日本的首都在日本"))
}
func TestReplacer_ReplaceSuffixMatch(t *testing.T) {
// case1
{
keywords := map[string]string{
"abcde": "ABCDE",
"bcde": "BCDE",
"bcd": "BCD",
}
assert.Equal(t, "aBCDf", NewReplacer(keywords).Replace("abcdf"))
}
// case2
{
keywords := map[string]string{
"abcde": "ABCDE",
"bcde": "BCDE",
"cde": "CDE",
"c": "C",
"cd": "CD",
}
assert.Equal(t, "abCDf", NewReplacer(keywords).Replace("abcdf"))
}
}
func TestReplacer_ReplaceLongestOverlap(t *testing.T) {
keywords := map[string]string{
"456": "def",
"abcd": "1234",
}
replacer := NewReplacer(keywords)
assert.Equal(t, "123def7", replacer.Replace("abcd567"))
}
func TestReplacer_ReplaceLongestLonger(t *testing.T) {
mapping := map[string]string{
"c": "3",
}
assert.Equal(t, "3d", NewReplacer(mapping).Replace("cd"))
}
func TestReplacer_ReplaceJumpToFail(t *testing.T) {
mapping := map[string]string{
"bcdf": "1235",
"cde": "234",
}
assert.Equal(t, "ab234fg", NewReplacer(mapping).Replace("abcdefg"))
}
func TestReplacer_ReplaceJumpToFailDup(t *testing.T) {
mapping := map[string]string{
"bcdf": "1235",
"ccde": "2234",
}
assert.Equal(t, "ab2234fg", NewReplacer(mapping).Replace("abccdefg"))
}
func TestReplacer_ReplaceJumpToFailEnding(t *testing.T) {
mapping := map[string]string{
"bcdf": "1235",
"cdef": "2345",
}
assert.Equal(t, "ab2345", NewReplacer(mapping).Replace("abcdef"))
}
func TestReplacer_ReplaceEmpty(t *testing.T) {
mapping := map[string]string{
"bcdf": "1235",
"cdef": "2345",
}
assert.Equal(t, "", NewReplacer(mapping).Replace(""))
}
func TestFuzzReplacerCase1(t *testing.T) {
keywords := map[string]string{
"yQyJykiqoh": "xw",
"tgN70z": "Q2P",
"tXKhEn": "w1G8",
"5nfOW1XZO": "GN",
"f4Ov9i9nHD": "cT",
"1ov9Q": "Y",
"7IrC9n": "400i",
"JQLxonpHkOjv": "XI",
"DyHQ3c7": "Ygxux",
"ffyqJi": "u",
"UHuvXrbD8pni": "dN",
"LIDzNbUlTX": "g",
"yN9WZh2rkc8Q": "3U",
"Vhk11rz8CObceC": "jf",
"R0Rt4H2qChUQf": "7U5M",
"MGQzzPCVKjV9": "yYz",
"B5jUUl0u1XOY": "l4PZ",
"pdvp2qfLgG8X": "BM562",
"ZKl9qdApXJ2": "T",
"37jnugkSevU66": "aOHFX",
}
rep := NewReplacer(keywords)
text := "yjF8fyqJiiqrczOCVyoYbLvrMpnkj"
val := rep.Replace(text)
keys := rep.(*replacer).node.find([]rune(val))
if len(keys) > 0 {
t.Errorf("result: %s, match: %v", val, keys)
}
}
func TestFuzzReplacerCase2(t *testing.T) {
keywords := map[string]string{
"dmv2SGZvq9Yz": "TE",
"rCL5DRI9uFP8": "hvsc8",
"7pSA2jaomgg": "v",
"kWSQvjVOIAxR": "Oje",
"hgU5bYYkD3r6": "qCXu",
"0eh6uI": "MMlt",
"3USZSl85EKeMzw": "Pc",
"JONmQSuXa": "dX",
"EO1WIF": "G",
"uUmFJGVmacjF": "1N",
"DHpw7": "M",
"NYB2bm": "CPya",
"9FiNvBAHHNku5": "7FlDE",
"tJi3I4WxcY": "q5",
"sNJ8Z1ToBV0O": "tl",
"0iOg72QcPo": "RP",
"pSEqeL": "5KZ",
"GOyYqTgmvQ": "9",
"Qv4qCsj": "nl52E",
"wNQ5tOutYu5s8": "6iGa",
}
rep := NewReplacer(keywords)
text := "AoRxrdKWsGhFpXwVqMLWRL74OukwjBuBh0g7pSrk"
val := rep.Replace(text)
keys := rep.(*replacer).node.find([]rune(val))
if len(keys) > 0 {
t.Errorf("result: %s, match: %v", val, keys)
}
}
func TestReplacer_ReplaceLongestMatch(t *testing.T) {
replacer := NewReplacer(map[string]string{
"日本的首都": "东京",
"日本": "本日",
})
assert.Equal(t, "东京是东京", replacer.Replace("日本的首都是东京"))
}
func TestReplacer_ReplaceIndefinitely(t *testing.T) {
mapping := map[string]string{
"日本的首都": "东京",
"东京": "日本的首都",
}
assert.NotPanics(t, func() {
NewReplacer(mapping).Replace("日本的首都是东京")
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/random.go | core/stringx/random.go | package stringx
import (
crand "crypto/rand"
"fmt"
"math/rand"
"sync"
"time"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
letterIdxBits = 6 // 6 bits to represent a letter index
idLen = 8
defaultRandLen = 8
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = newLockedSource(time.Now().UnixNano())
type lockedSource struct {
source rand.Source
lock sync.Mutex
}
func newLockedSource(seed int64) *lockedSource {
return &lockedSource{
source: rand.NewSource(seed),
}
}
func (ls *lockedSource) Int63() int64 {
ls.lock.Lock()
defer ls.lock.Unlock()
return ls.source.Int63()
}
func (ls *lockedSource) Seed(seed int64) {
ls.lock.Lock()
defer ls.lock.Unlock()
ls.source.Seed(seed)
}
// Rand returns a random string.
func Rand() string {
return Randn(defaultRandLen)
}
// RandId returns a random id string.
func RandId() string {
b := make([]byte, idLen)
_, err := crand.Read(b)
if err != nil {
return Randn(idLen)
}
return fmt.Sprintf("%x%x%x%x", b[0:2], b[2:4], b[4:6], b[6:8])
}
// Randn returns a random string with length n.
func Randn(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// Seed sets the seed to seed.
func Seed(seed int64) {
src.Seed(seed)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stringx/node_fuzz_test.go | core/stringx/node_fuzz_test.go | package stringx
import (
"fmt"
"math/rand"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func FuzzNodeFind(f *testing.F) {
rand.NewSource(time.Now().UnixNano())
f.Add(10)
f.Fuzz(func(t *testing.T, keys int) {
str := Randn(rand.Intn(100) + 50)
keywords := make(map[string]struct{})
for i := 0; i < keys; i++ {
keyword := Randn(rand.Intn(10) + 5)
if !strings.Contains(str, keyword) {
keywords[keyword] = struct{}{}
}
}
size := len(str)
var scopes []scope
var n node
for i := 0; i < size%20; i++ {
start := rand.Intn(size)
stop := start + rand.Intn(20) + 1
if stop > size {
stop = size
}
if start == stop {
continue
}
keyword := str[start:stop]
if _, ok := keywords[keyword]; ok {
continue
}
keywords[keyword] = struct{}{}
var pos int
for pos <= len(str)-len(keyword) {
val := str[pos:]
p := strings.Index(val, keyword)
if p < 0 {
break
}
scopes = append(scopes, scope{
start: pos + p,
stop: pos + p + len(keyword),
})
pos += p + 1
}
}
for keyword := range keywords {
n.add(keyword)
}
n.build()
var buf strings.Builder
buf.WriteString("keywords:\n")
for key := range keywords {
fmt.Fprintf(&buf, "\t%q,\n", key)
}
buf.WriteString("scopes:\n")
for _, scp := range scopes {
fmt.Fprintf(&buf, "\t{%d, %d},\n", scp.start, scp.stop)
}
fmt.Fprintf(&buf, "text:\n\t%s\n", str)
defer func() {
if r := recover(); r != nil {
t.Error(buf.String())
}
}()
assert.ElementsMatchf(t, scopes, n.find([]rune(str)), buf.String())
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/delayexecutor.go | core/executors/delayexecutor.go | package executors
import (
"sync"
"time"
"github.com/zeromicro/go-zero/core/threading"
)
// A DelayExecutor delays a tasks on given delay interval.
type DelayExecutor struct {
fn func()
delay time.Duration
triggered bool
lock sync.Mutex
}
// NewDelayExecutor returns a DelayExecutor with given fn and delay.
func NewDelayExecutor(fn func(), delay time.Duration) *DelayExecutor {
return &DelayExecutor{
fn: fn,
delay: delay,
}
}
// Trigger triggers the task to be executed after given delay, safe to trigger more than once.
func (de *DelayExecutor) Trigger() {
de.lock.Lock()
defer de.lock.Unlock()
if de.triggered {
return
}
de.triggered = true
threading.GoSafe(func() {
timer := time.NewTimer(de.delay)
defer timer.Stop()
<-timer.C
// set triggered to false before calling fn to ensure no triggers are missed.
de.lock.Lock()
de.triggered = false
de.lock.Unlock()
de.fn()
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/chunkexecutor.go | core/executors/chunkexecutor.go | package executors
import "time"
const defaultChunkSize = 1024 * 1024 // 1M
type (
// ChunkOption defines the method to customize a ChunkExecutor.
ChunkOption func(options *chunkOptions)
// A ChunkExecutor is an executor to execute tasks when either requirement meets:
// 1. up to given chunk size
// 2. flush interval elapsed
ChunkExecutor struct {
executor *PeriodicalExecutor
container *chunkContainer
}
chunkOptions struct {
chunkSize int
flushInterval time.Duration
}
)
// NewChunkExecutor returns a ChunkExecutor.
func NewChunkExecutor(execute Execute, opts ...ChunkOption) *ChunkExecutor {
options := newChunkOptions()
for _, opt := range opts {
opt(&options)
}
container := &chunkContainer{
execute: execute,
maxChunkSize: options.chunkSize,
}
executor := &ChunkExecutor{
executor: NewPeriodicalExecutor(options.flushInterval, container),
container: container,
}
return executor
}
// Add adds task with given chunk size into ce.
func (ce *ChunkExecutor) Add(task any, size int) error {
ce.executor.Add(chunk{
val: task,
size: size,
})
return nil
}
// Flush forces ce to flush and execute tasks.
func (ce *ChunkExecutor) Flush() {
ce.executor.Flush()
}
// Wait waits the execution to be done.
func (ce *ChunkExecutor) Wait() {
ce.executor.Wait()
}
// WithChunkBytes customizes a ChunkExecutor with the given chunk size.
func WithChunkBytes(size int) ChunkOption {
return func(options *chunkOptions) {
options.chunkSize = size
}
}
// WithFlushInterval customizes a ChunkExecutor with the given flush interval.
func WithFlushInterval(duration time.Duration) ChunkOption {
return func(options *chunkOptions) {
options.flushInterval = duration
}
}
func newChunkOptions() chunkOptions {
return chunkOptions{
chunkSize: defaultChunkSize,
flushInterval: defaultFlushInterval,
}
}
type chunkContainer struct {
tasks []any
execute Execute
size int
maxChunkSize int
}
func (bc *chunkContainer) AddTask(task any) bool {
ck := task.(chunk)
bc.tasks = append(bc.tasks, ck.val)
bc.size += ck.size
return bc.size >= bc.maxChunkSize
}
func (bc *chunkContainer) Execute(tasks any) {
vals := tasks.([]any)
bc.execute(vals)
}
func (bc *chunkContainer) RemoveAll() any {
tasks := bc.tasks
bc.tasks = nil
bc.size = 0
return tasks
}
type chunk struct {
val any
size int
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/lessexecutor.go | core/executors/lessexecutor.go | package executors
import (
"time"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
)
// A LessExecutor is an executor to limit execution once within given time interval.
type LessExecutor struct {
threshold time.Duration
lastTime *syncx.AtomicDuration
}
// NewLessExecutor returns a LessExecutor with given threshold as time interval.
func NewLessExecutor(threshold time.Duration) *LessExecutor {
return &LessExecutor{
threshold: threshold,
lastTime: syncx.NewAtomicDuration(),
}
}
// DoOrDiscard executes or discards the task depends on if
// another task was executed within the time interval.
func (le *LessExecutor) DoOrDiscard(execute func()) bool {
now := timex.Now()
lastTime := le.lastTime.Load()
if lastTime == 0 || lastTime+le.threshold < now {
le.lastTime.Set(now)
execute()
return true
}
return false
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/chunkexecutor_test.go | core/executors/chunkexecutor_test.go | package executors
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestChunkExecutor(t *testing.T) {
var values []int
var lock sync.Mutex
executor := NewChunkExecutor(func(items []any) {
lock.Lock()
values = append(values, len(items))
lock.Unlock()
}, WithChunkBytes(10), WithFlushInterval(time.Minute))
for i := 0; i < 50; i++ {
executor.Add(1, 1)
time.Sleep(time.Millisecond)
}
lock.Lock()
assert.True(t, len(values) > 0)
// ignore last value
for i := 0; i < len(values); i++ {
assert.Equal(t, 10, values[i])
}
lock.Unlock()
}
func TestChunkExecutorFlushInterval(t *testing.T) {
const (
caches = 10
size = 5
)
var wait sync.WaitGroup
wait.Add(1)
executor := NewChunkExecutor(func(items []any) {
assert.Equal(t, size, len(items))
wait.Done()
}, WithChunkBytes(caches), WithFlushInterval(time.Millisecond*100))
for i := 0; i < size; i++ {
executor.Add(1, 1)
}
wait.Wait()
}
func TestChunkExecutorEmpty(t *testing.T) {
executor := NewChunkExecutor(func(items []any) {
assert.Fail(t, "should not called")
}, WithChunkBytes(10), WithFlushInterval(time.Millisecond))
time.Sleep(time.Millisecond * 100)
executor.Wait()
}
func TestChunkExecutorFlush(t *testing.T) {
const (
caches = 10
tasks = 5
)
var wait sync.WaitGroup
wait.Add(1)
be := NewChunkExecutor(func(items []any) {
assert.Equal(t, tasks, len(items))
wait.Done()
}, WithChunkBytes(caches), WithFlushInterval(time.Minute))
for i := 0; i < tasks; i++ {
be.Add(1, 1)
}
be.Flush()
wait.Wait()
}
func BenchmarkChunkExecutor(b *testing.B) {
b.ReportAllocs()
be := NewChunkExecutor(func(tasks []any) {
time.Sleep(time.Millisecond * time.Duration(len(tasks)))
})
for i := 0; i < b.N; i++ {
time.Sleep(time.Microsecond * 200)
be.Add(1, 1)
}
be.Flush()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/lessexecutor_test.go | core/executors/lessexecutor_test.go | package executors
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/timex"
)
func TestLessExecutor_DoOrDiscard(t *testing.T) {
executor := NewLessExecutor(time.Minute)
assert.True(t, executor.DoOrDiscard(func() {}))
assert.False(t, executor.DoOrDiscard(func() {}))
executor.lastTime.Set(timex.Now() - time.Minute - time.Second*30)
assert.True(t, executor.DoOrDiscard(func() {}))
assert.False(t, executor.DoOrDiscard(func() {}))
}
func BenchmarkLessExecutor(b *testing.B) {
exec := NewLessExecutor(time.Millisecond)
for i := 0; i < b.N; i++ {
exec.DoOrDiscard(func() {
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/periodicalexecutor_test.go | core/executors/periodicalexecutor_test.go | package executors
import (
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/timex"
)
const threshold = 10
type container struct {
interval time.Duration
tasks []int
execute func(tasks any)
}
func newContainer(interval time.Duration, execute func(tasks any)) *container {
return &container{
interval: interval,
execute: execute,
}
}
func (c *container) AddTask(task any) bool {
c.tasks = append(c.tasks, task.(int))
return len(c.tasks) > threshold
}
func (c *container) Execute(tasks any) {
if c.execute != nil {
c.execute(tasks)
} else {
time.Sleep(c.interval)
}
}
func (c *container) RemoveAll() any {
tasks := c.tasks
c.tasks = nil
return tasks
}
func TestPeriodicalExecutor_Sync(t *testing.T) {
var done int32
exec := NewPeriodicalExecutor(time.Second, newContainer(time.Millisecond*500, nil))
exec.Sync(func() {
atomic.AddInt32(&done, 1)
})
assert.Equal(t, int32(1), atomic.LoadInt32(&done))
}
func TestPeriodicalExecutor_QuitGoroutine(t *testing.T) {
ticker := timex.NewFakeTicker()
exec := NewPeriodicalExecutor(time.Millisecond, newContainer(time.Millisecond, nil))
exec.newTicker = func(d time.Duration) timex.Ticker {
return ticker
}
routines := runtime.NumGoroutine()
exec.Add(1)
ticker.Tick()
ticker.Wait(time.Millisecond * idleRound * 2)
ticker.Tick()
ticker.Wait(time.Millisecond * idleRound)
assert.Equal(t, routines, runtime.NumGoroutine())
proc.Shutdown()
}
func TestPeriodicalExecutor_Bulk(t *testing.T) {
ticker := timex.NewFakeTicker()
var vals []int
// avoid data race
var lock sync.Mutex
exec := NewPeriodicalExecutor(time.Millisecond, newContainer(time.Millisecond, func(tasks any) {
t := tasks.([]int)
for _, each := range t {
lock.Lock()
vals = append(vals, each)
lock.Unlock()
}
}))
exec.newTicker = func(d time.Duration) timex.Ticker {
return ticker
}
for i := 0; i < threshold*10; i++ {
if i%threshold == 5 {
time.Sleep(time.Millisecond * idleRound * 2)
}
exec.Add(i)
}
ticker.Tick()
ticker.Wait(time.Millisecond * idleRound * 2)
ticker.Tick()
ticker.Tick()
ticker.Wait(time.Millisecond * idleRound)
var expect []int
for i := 0; i < threshold*10; i++ {
expect = append(expect, i)
}
lock.Lock()
assert.EqualValues(t, expect, vals)
lock.Unlock()
}
func TestPeriodicalExecutor_Panic(t *testing.T) {
// avoid data race
var lock sync.Mutex
ticker := timex.NewFakeTicker()
var (
executedTasks []int
expected []int
)
executor := NewPeriodicalExecutor(time.Millisecond, newContainer(time.Millisecond, func(tasks any) {
tt := tasks.([]int)
lock.Lock()
executedTasks = append(executedTasks, tt...)
lock.Unlock()
if tt[0] == 0 {
panic("test")
}
}))
executor.newTicker = func(duration time.Duration) timex.Ticker {
return ticker
}
for i := 0; i < 30; i++ {
executor.Add(i)
expected = append(expected, i)
}
ticker.Tick()
ticker.Tick()
time.Sleep(time.Millisecond)
lock.Lock()
assert.Equal(t, expected, executedTasks)
lock.Unlock()
}
func TestPeriodicalExecutor_FlushPanic(t *testing.T) {
var (
executedTasks []int
expected []int
lock sync.Mutex
)
executor := NewPeriodicalExecutor(time.Millisecond, newContainer(time.Millisecond, func(tasks any) {
tt := tasks.([]int)
lock.Lock()
executedTasks = append(executedTasks, tt...)
lock.Unlock()
if tt[0] == 0 {
panic("flush panic")
}
}))
for i := 0; i < 8; i++ {
executor.Add(i)
expected = append(expected, i)
}
executor.Flush()
lock.Lock()
assert.Equal(t, expected, executedTasks)
lock.Unlock()
}
func TestPeriodicalExecutor_Wait(t *testing.T) {
var lock sync.Mutex
executor := NewBulkExecutor(func(tasks []any) {
lock.Lock()
defer lock.Unlock()
time.Sleep(10 * time.Millisecond)
}, WithBulkTasks(1), WithBulkInterval(time.Second))
for i := 0; i < 10; i++ {
executor.Add(1)
}
executor.Flush()
executor.Wait()
}
func TestPeriodicalExecutor_WaitFast(t *testing.T) {
const total = 3
var cnt int
var lock sync.Mutex
executor := NewBulkExecutor(func(tasks []any) {
defer func() {
cnt++
}()
lock.Lock()
defer lock.Unlock()
time.Sleep(10 * time.Millisecond)
}, WithBulkTasks(1), WithBulkInterval(10*time.Millisecond))
for i := 0; i < total; i++ {
executor.Add(2)
}
executor.Flush()
executor.Wait()
assert.Equal(t, total, cnt)
}
func TestPeriodicalExecutor_Deadlock(t *testing.T) {
executor := NewBulkExecutor(func(tasks []any) {
}, WithBulkTasks(1), WithBulkInterval(time.Millisecond))
for i := 0; i < 1e5; i++ {
executor.Add(1)
}
}
func TestPeriodicalExecutor_hasTasks(t *testing.T) {
exec := NewPeriodicalExecutor(time.Millisecond, newContainer(time.Millisecond, nil))
assert.False(t, exec.hasTasks(nil))
assert.True(t, exec.hasTasks(1))
}
// go test -benchtime 10s -bench .
func BenchmarkExecutor(b *testing.B) {
b.ReportAllocs()
executor := NewPeriodicalExecutor(time.Second, newContainer(time.Millisecond*500, nil))
for i := 0; i < b.N; i++ {
executor.Add(1)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/vars.go | core/executors/vars.go | package executors
import "time"
const defaultFlushInterval = time.Second
// Execute defines the method to execute tasks.
type Execute func(tasks []any)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/bulkexecutor_test.go | core/executors/bulkexecutor_test.go | package executors
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestBulkExecutor(t *testing.T) {
var values []int
var lock sync.Mutex
executor := NewBulkExecutor(func(items []any) {
lock.Lock()
values = append(values, len(items))
lock.Unlock()
}, WithBulkTasks(10), WithBulkInterval(time.Minute))
for i := 0; i < 50; i++ {
executor.Add(1)
time.Sleep(time.Millisecond)
}
lock.Lock()
assert.True(t, len(values) > 0)
// ignore last value
for i := 0; i < len(values); i++ {
assert.Equal(t, 10, values[i])
}
lock.Unlock()
}
func TestBulkExecutorFlushInterval(t *testing.T) {
const (
caches = 10
size = 5
)
var wait sync.WaitGroup
wait.Add(1)
executor := NewBulkExecutor(func(items []any) {
assert.Equal(t, size, len(items))
wait.Done()
}, WithBulkTasks(caches), WithBulkInterval(time.Millisecond*100))
for i := 0; i < size; i++ {
executor.Add(1)
}
wait.Wait()
}
func TestBulkExecutorEmpty(t *testing.T) {
NewBulkExecutor(func(items []any) {
assert.Fail(t, "should not called")
}, WithBulkTasks(10), WithBulkInterval(time.Millisecond))
time.Sleep(time.Millisecond * 100)
}
func TestBulkExecutorFlush(t *testing.T) {
const (
caches = 10
tasks = 5
)
var wait sync.WaitGroup
wait.Add(1)
be := NewBulkExecutor(func(items []any) {
assert.Equal(t, tasks, len(items))
wait.Done()
}, WithBulkTasks(caches), WithBulkInterval(time.Minute))
for i := 0; i < tasks; i++ {
be.Add(1)
}
be.Flush()
wait.Wait()
}
func TestBulkExecutorFlushSlowTasks(t *testing.T) {
const total = 1500
lock := new(sync.Mutex)
result := make([]any, 0, 10000)
exec := NewBulkExecutor(func(tasks []any) {
time.Sleep(time.Millisecond * 100)
lock.Lock()
defer lock.Unlock()
result = append(result, tasks...)
}, WithBulkTasks(1000))
for i := 0; i < total; i++ {
assert.Nil(t, exec.Add(i))
}
exec.Flush()
exec.Wait()
assert.Equal(t, total, len(result))
}
func BenchmarkBulkExecutor(b *testing.B) {
b.ReportAllocs()
be := NewBulkExecutor(func(tasks []any) {
time.Sleep(time.Millisecond * time.Duration(len(tasks)))
})
for i := 0; i < b.N; i++ {
time.Sleep(time.Microsecond * 200)
be.Add(1)
}
be.Flush()
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/bulkexecutor.go | core/executors/bulkexecutor.go | package executors
import "time"
const defaultBulkTasks = 1000
type (
// BulkOption defines the method to customize a BulkExecutor.
BulkOption func(options *bulkOptions)
// A BulkExecutor is an executor that can execute tasks on either requirement meets:
// 1. up to given size of tasks
// 2. flush interval time elapsed
BulkExecutor struct {
executor *PeriodicalExecutor
container *bulkContainer
}
bulkOptions struct {
cachedTasks int
flushInterval time.Duration
}
)
// NewBulkExecutor returns a BulkExecutor.
func NewBulkExecutor(execute Execute, opts ...BulkOption) *BulkExecutor {
options := newBulkOptions()
for _, opt := range opts {
opt(&options)
}
container := &bulkContainer{
execute: execute,
maxTasks: options.cachedTasks,
}
executor := &BulkExecutor{
executor: NewPeriodicalExecutor(options.flushInterval, container),
container: container,
}
return executor
}
// Add adds task into be.
func (be *BulkExecutor) Add(task any) error {
be.executor.Add(task)
return nil
}
// Flush forces be to flush and execute tasks.
func (be *BulkExecutor) Flush() {
be.executor.Flush()
}
// Wait waits be to done with the task execution.
func (be *BulkExecutor) Wait() {
be.executor.Wait()
}
// WithBulkTasks customizes a BulkExecutor with given tasks limit.
func WithBulkTasks(tasks int) BulkOption {
return func(options *bulkOptions) {
options.cachedTasks = tasks
}
}
// WithBulkInterval customizes a BulkExecutor with given flush interval.
func WithBulkInterval(duration time.Duration) BulkOption {
return func(options *bulkOptions) {
options.flushInterval = duration
}
}
func newBulkOptions() bulkOptions {
return bulkOptions{
cachedTasks: defaultBulkTasks,
flushInterval: defaultFlushInterval,
}
}
type bulkContainer struct {
tasks []any
execute Execute
maxTasks int
}
func (bc *bulkContainer) AddTask(task any) bool {
bc.tasks = append(bc.tasks, task)
return len(bc.tasks) >= bc.maxTasks
}
func (bc *bulkContainer) Execute(tasks any) {
vals := tasks.([]any)
bc.execute(vals)
}
func (bc *bulkContainer) RemoveAll() any {
tasks := bc.tasks
bc.tasks = nil
return tasks
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/delayexecutor_test.go | core/executors/delayexecutor_test.go | package executors
import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestDelayExecutor(t *testing.T) {
var count int32
ex := NewDelayExecutor(func() {
atomic.AddInt32(&count, 1)
}, time.Millisecond*10)
for i := 0; i < 100; i++ {
ex.Trigger()
}
time.Sleep(time.Millisecond * 100)
assert.Equal(t, int32(1), atomic.LoadInt32(&count))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/executors/periodicalexecutor.go | core/executors/periodicalexecutor.go | package executors
import (
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/lang"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/threading"
"github.com/zeromicro/go-zero/core/timex"
)
const idleRound = 10
type (
// TaskContainer interface defines a type that can be used as the underlying
// container that used to do periodical executions.
TaskContainer interface {
// AddTask adds the task into the container.
// Returns true if the container needs to be flushed after the addition.
AddTask(task any) bool
// Execute handles the collected tasks by the container when flushing.
Execute(tasks any)
// RemoveAll removes the contained tasks, and return them.
RemoveAll() any
}
// A PeriodicalExecutor is an executor that periodically execute tasks.
PeriodicalExecutor struct {
commander chan any
interval time.Duration
container TaskContainer
waitGroup sync.WaitGroup
// avoid race condition on waitGroup when calling wg.Add/Done/Wait(...)
wgBarrier syncx.Barrier
confirmChan chan lang.PlaceholderType
inflight int32
guarded bool
newTicker func(duration time.Duration) timex.Ticker
lock sync.Mutex
}
)
// NewPeriodicalExecutor returns a PeriodicalExecutor with given interval and container.
func NewPeriodicalExecutor(interval time.Duration, container TaskContainer) *PeriodicalExecutor {
executor := &PeriodicalExecutor{
// buffer 1 to let the caller go quickly
commander: make(chan any, 1),
interval: interval,
container: container,
confirmChan: make(chan lang.PlaceholderType),
newTicker: func(d time.Duration) timex.Ticker {
return timex.NewTicker(d)
},
}
proc.AddShutdownListener(func() {
executor.Flush()
})
return executor
}
// Add adds tasks into pe.
func (pe *PeriodicalExecutor) Add(task any) {
if vals, ok := pe.addAndCheck(task); ok {
pe.commander <- vals
<-pe.confirmChan
}
}
// Flush forces pe to execute tasks.
func (pe *PeriodicalExecutor) Flush() bool {
pe.enterExecution()
return pe.executeTasks(func() any {
pe.lock.Lock()
defer pe.lock.Unlock()
return pe.container.RemoveAll()
}())
}
// Sync lets caller run fn thread-safe with pe, especially for the underlying container.
func (pe *PeriodicalExecutor) Sync(fn func()) {
pe.lock.Lock()
defer pe.lock.Unlock()
fn()
}
// Wait waits the execution to be done.
func (pe *PeriodicalExecutor) Wait() {
pe.Flush()
pe.wgBarrier.Guard(func() {
pe.waitGroup.Wait()
})
}
func (pe *PeriodicalExecutor) addAndCheck(task any) (any, bool) {
pe.lock.Lock()
defer func() {
if !pe.guarded {
pe.guarded = true
// defer to unlock quickly
defer pe.backgroundFlush()
}
pe.lock.Unlock()
}()
if pe.container.AddTask(task) {
atomic.AddInt32(&pe.inflight, 1)
return pe.container.RemoveAll(), true
}
return nil, false
}
func (pe *PeriodicalExecutor) backgroundFlush() {
go func() {
// flush before quit goroutine to avoid missing tasks
defer pe.Flush()
ticker := pe.newTicker(pe.interval)
defer ticker.Stop()
var commanded bool
last := timex.Now()
for {
select {
case vals := <-pe.commander:
commanded = true
atomic.AddInt32(&pe.inflight, -1)
pe.enterExecution()
pe.confirmChan <- lang.Placeholder
pe.executeTasks(vals)
last = timex.Now()
case <-ticker.Chan():
if commanded {
commanded = false
} else if pe.Flush() {
last = timex.Now()
} else if pe.shallQuit(last) {
return
}
}
}
}()
}
func (pe *PeriodicalExecutor) doneExecution() {
pe.waitGroup.Done()
}
func (pe *PeriodicalExecutor) enterExecution() {
pe.wgBarrier.Guard(func() {
pe.waitGroup.Add(1)
})
}
func (pe *PeriodicalExecutor) executeTasks(tasks any) bool {
defer pe.doneExecution()
ok := pe.hasTasks(tasks)
if ok {
threading.RunSafe(func() {
pe.container.Execute(tasks)
})
}
return ok
}
func (pe *PeriodicalExecutor) hasTasks(tasks any) bool {
if tasks == nil {
return false
}
val := reflect.ValueOf(tasks)
switch val.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
return val.Len() > 0
default:
// unknown type, let caller execute it
return true
}
}
func (pe *PeriodicalExecutor) shallQuit(last time.Duration) (stop bool) {
if timex.Since(last) <= pe.interval*idleRound {
return
}
// checking pe.inflight and setting pe.guarded should be locked together
pe.lock.Lock()
if atomic.LoadInt32(&pe.inflight) == 0 {
pe.guarded = false
stop = true
}
pe.lock.Unlock()
return
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/atomicerror.go | core/errorx/atomicerror.go | package errorx
import "sync/atomic"
// AtomicError defines an atomic error.
type AtomicError struct {
err atomic.Value // error
}
// Set sets the error.
func (ae *AtomicError) Set(err error) {
if err != nil {
ae.err.Store(err)
}
}
// Load returns the error.
func (ae *AtomicError) Load() error {
if v := ae.err.Load(); v != nil {
return v.(error)
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/callchain_test.go | core/errorx/callchain_test.go | package errorx
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestChain(t *testing.T) {
errDummy := errors.New("dummy")
assert.Nil(t, Chain(func() error {
return nil
}, func() error {
return nil
}))
assert.Equal(t, errDummy, Chain(func() error {
return errDummy
}, func() error {
return nil
}))
assert.Equal(t, errDummy, Chain(func() error {
return nil
}, func() error {
return errDummy
}))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/wrap_test.go | core/errorx/wrap_test.go | package errorx
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWrap(t *testing.T) {
assert.Nil(t, Wrap(nil, "test"))
assert.Equal(t, "foo: bar", Wrap(errors.New("bar"), "foo").Error())
err := errors.New("foo")
assert.True(t, errors.Is(Wrap(err, "bar"), err))
}
func TestWrapf(t *testing.T) {
assert.Nil(t, Wrapf(nil, "%s", "test"))
assert.Equal(t, "foo bar: quz", Wrapf(errors.New("quz"), "foo %s", "bar").Error())
err := errors.New("foo")
assert.True(t, errors.Is(Wrapf(err, "foo %s", "bar"), err))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/callchain.go | core/errorx/callchain.go | package errorx
// Chain runs funs one by one until an error occurred.
func Chain(fns ...func() error) error {
for _, fn := range fns {
if err := fn(); err != nil {
return err
}
}
return nil
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/check.go | core/errorx/check.go | package errorx
import "errors"
// In checks if the given err is one of errs.
func In(err error, errs ...error) bool {
for _, each := range errs {
if errors.Is(err, each) {
return true
}
}
return false
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/atomicerror_test.go | core/errorx/atomicerror_test.go | package errorx
import (
"errors"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
var errDummy = errors.New("hello")
func TestAtomicError(t *testing.T) {
var err AtomicError
err.Set(errDummy)
assert.Equal(t, errDummy, err.Load())
}
func TestAtomicErrorSetNil(t *testing.T) {
var (
errNil error
err AtomicError
)
err.Set(errNil)
assert.Equal(t, errNil, err.Load())
}
func TestAtomicErrorNil(t *testing.T) {
var err AtomicError
assert.Nil(t, err.Load())
}
func BenchmarkAtomicError(b *testing.B) {
var aerr AtomicError
wg := sync.WaitGroup{}
b.Run("Load", func(b *testing.B) {
var done uint32
go func() {
for {
if atomic.LoadUint32(&done) != 0 {
break
}
wg.Add(1)
go func() {
aerr.Set(errDummy)
wg.Done()
}()
}
}()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = aerr.Load()
}
b.StopTimer()
atomic.StoreUint32(&done, 1)
wg.Wait()
})
b.Run("Set", func(b *testing.B) {
var done uint32
go func() {
for {
if atomic.LoadUint32(&done) != 0 {
break
}
wg.Add(1)
go func() {
_ = aerr.Load()
wg.Done()
}()
}
}()
b.ResetTimer()
for i := 0; i < b.N; i++ {
aerr.Set(errDummy)
}
b.StopTimer()
atomic.StoreUint32(&done, 1)
wg.Wait()
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/batcherror.go | core/errorx/batcherror.go | package errorx
import (
"errors"
"sync"
)
// BatchError is an error that can hold multiple errors.
type BatchError struct {
errs []error
lock sync.RWMutex
}
// Add adds one or more non-nil errors to the BatchError instance.
func (be *BatchError) Add(errs ...error) {
be.lock.Lock()
defer be.lock.Unlock()
for _, err := range errs {
if err != nil {
be.errs = append(be.errs, err)
}
}
}
// Err returns an error that represents all accumulated errors.
// It returns nil if there are no errors.
func (be *BatchError) Err() error {
be.lock.RLock()
defer be.lock.RUnlock()
// If there are no non-nil errors, errors.Join(...) returns nil.
return errors.Join(be.errs...)
}
// NotNil checks if there is at least one error inside the BatchError.
func (be *BatchError) NotNil() bool {
be.lock.RLock()
defer be.lock.RUnlock()
return len(be.errs) > 0
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/wrap.go | core/errorx/wrap.go | package errorx
import "fmt"
// Wrap returns an error that wraps err with given message.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", message, err)
}
// Wrapf returns an error that wraps err with given format and args.
func Wrapf(err error, format string, args ...any) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), err)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/check_test.go | core/errorx/check_test.go | package errorx
import (
"errors"
"testing"
)
func TestIn(t *testing.T) {
err1 := errors.New("error 1")
err2 := errors.New("error 2")
err3 := errors.New("error 3")
tests := []struct {
name string
err error
errs []error
want bool
}{
{
name: "Error matches one of the errors in the list",
err: err1,
errs: []error{err1, err2},
want: true,
},
{
name: "Error does not match any errors in the list",
err: err3,
errs: []error{err1, err2},
want: false,
},
{
name: "Empty error list",
err: err1,
errs: []error{},
want: false,
},
{
name: "Nil error with non-nil list",
err: nil,
errs: []error{err1, err2},
want: false,
},
{
name: "Non-nil error with nil in list",
err: err1,
errs: []error{nil, err2},
want: false,
},
{
name: "Error matches nil error in the list",
err: nil,
errs: []error{nil, err2},
want: true,
},
{
name: "Nil error with empty list",
err: nil,
errs: []error{},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := In(tt.err, tt.errs...); got != tt.want {
t.Errorf("In() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/errorx/batcherror_test.go | core/errorx/batcherror_test.go | package errorx
import (
"errors"
"fmt"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
const (
err1 = "first error"
err2 = "second error"
)
func TestBatchErrorNil(t *testing.T) {
var batch BatchError
assert.Nil(t, batch.Err())
assert.False(t, batch.NotNil())
batch.Add(nil)
assert.Nil(t, batch.Err())
assert.False(t, batch.NotNil())
}
func TestBatchErrorNilFromFunc(t *testing.T) {
err := func() error {
var be BatchError
return be.Err()
}()
assert.True(t, err == nil)
}
func TestBatchErrorOneError(t *testing.T) {
var batch BatchError
batch.Add(errors.New(err1))
assert.NotNil(t, batch.Err())
assert.Equal(t, err1, batch.Err().Error())
assert.True(t, batch.NotNil())
}
func TestBatchErrorWithErrors(t *testing.T) {
var batch BatchError
batch.Add(errors.New(err1))
batch.Add(errors.New(err2))
assert.NotNil(t, batch.Err())
assert.Equal(t, fmt.Sprintf("%s\n%s", err1, err2), batch.Err().Error())
assert.True(t, batch.NotNil())
}
func TestBatchErrorConcurrentAdd(t *testing.T) {
const count = 10000
var batch BatchError
var wg sync.WaitGroup
wg.Add(count)
for i := 0; i < count; i++ {
go func() {
defer wg.Done()
batch.Add(errors.New(err1))
}()
}
wg.Wait()
assert.NotNil(t, batch.Err())
assert.Equal(t, count, len(batch.errs))
assert.True(t, batch.NotNil())
}
func TestBatchError_Unwrap(t *testing.T) {
t.Run("nil", func(t *testing.T) {
var be BatchError
assert.Nil(t, be.Err())
assert.True(t, errors.Is(be.Err(), nil))
})
t.Run("one error", func(t *testing.T) {
var errFoo = errors.New("foo")
var errBar = errors.New("bar")
var be BatchError
be.Add(errFoo)
assert.True(t, errors.Is(be.Err(), errFoo))
assert.False(t, errors.Is(be.Err(), errBar))
})
t.Run("two errors", func(t *testing.T) {
var errFoo = errors.New("foo")
var errBar = errors.New("bar")
var errBaz = errors.New("baz")
var be BatchError
be.Add(errFoo)
be.Add(errBar)
assert.True(t, errors.Is(be.Err(), errFoo))
assert.True(t, errors.Is(be.Err(), errBar))
assert.False(t, errors.Is(be.Err(), errBaz))
})
}
func TestBatchError_Add(t *testing.T) {
var be BatchError
// Test adding nil errors
be.Add(nil, nil)
assert.False(t, be.NotNil(), "Expected BatchError to be empty after adding nil errors")
// Test adding non-nil errors
err1 := errors.New("error 1")
err2 := errors.New("error 2")
be.Add(err1, err2)
assert.True(t, be.NotNil(), "Expected BatchError to be non-empty after adding errors")
// Test adding a mix of nil and non-nil errors
err3 := errors.New("error 3")
be.Add(nil, err3, nil)
assert.True(t, be.NotNil(), "Expected BatchError to be non-empty after adding a mix of nil and non-nil errors")
}
func TestBatchError_Err(t *testing.T) {
var be BatchError
// Test Err() on empty BatchError
assert.Nil(t, be.Err(), "Expected nil error for empty BatchError")
// Test Err() with multiple errors
err1 := errors.New("error 1")
err2 := errors.New("error 2")
be.Add(err1, err2)
combinedErr := be.Err()
assert.NotNil(t, combinedErr, "Expected nil error for BatchError with multiple errors")
// Check if the combined error contains both error messages
errString := combinedErr.Error()
assert.Truef(t, errors.Is(combinedErr, err1), "Combined error doesn't contain first error: %s", errString)
assert.Truef(t, errors.Is(combinedErr, err2), "Combined error doesn't contain second error: %s", errString)
}
func TestBatchError_NotNil(t *testing.T) {
var be BatchError
// Test NotNil() on empty BatchError
assert.Nil(t, be.Err(), "Expected nil error for empty BatchError")
// Test NotNil() after adding an error
be.Add(errors.New("test error"))
assert.NotNil(t, be.Err(), "Expected non-nil error after adding an error")
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/postgres/postgresql.go | core/stores/postgres/postgresql.go | package postgres
import (
// imports the driver, don't remove this comment, golint requires.
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
const postgresDriverName = "pgx"
// New returns a postgres connection.
func New(datasource string, opts ...sqlx.SqlOption) sqlx.SqlConn {
return sqlx.NewSqlConn(postgresDriverName, datasource, opts...)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/postgres/postgresql_test.go | core/stores/postgres/postgresql_test.go | package postgres
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPostgreSql(t *testing.T) {
assert.NotNil(t, New("postgre"))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/builder/builder.go | core/stores/builder/builder.go | package builder
import (
"fmt"
"reflect"
"strings"
)
const dbTag = "db"
// RawFieldNames converts golang struct field into slice string.
func RawFieldNames(in any, postgreSql ...bool) []string {
out := make([]string, 0)
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
var pg bool
if len(postgreSql) > 0 {
pg = postgreSql[0]
}
// we only accept structs
if v.Kind() != reflect.Struct {
panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
}
typ := v.Type()
for i := 0; i < v.NumField(); i++ {
// gets us a StructField
fi := typ.Field(i)
tagv := fi.Tag.Get(dbTag)
switch tagv {
case "-":
continue
case "":
if pg {
out = append(out, fi.Name)
} else {
out = append(out, fmt.Sprintf("`%s`", fi.Name))
}
default:
// get tag name with the tag option, e.g.:
// `db:"id"`
// `db:"id,type=char,length=16"`
// `db:",type=char,length=16"`
// `db:"-,type=char,length=16"`
if strings.Contains(tagv, ",") {
tagv = strings.TrimSpace(strings.Split(tagv, ",")[0])
}
if tagv == "-" {
continue
}
if len(tagv) == 0 {
tagv = fi.Name
}
if pg {
out = append(out, tagv)
} else {
out = append(out, fmt.Sprintf("`%s`", tagv))
}
}
}
return out
}
// PostgreSqlJoin concatenates the given elements into a string.
func PostgreSqlJoin(elems []string) string {
b := new(strings.Builder)
for index, e := range elems {
b.WriteString(fmt.Sprintf("%s = $%d, ", e, index+2))
}
if b.Len() == 0 {
return b.String()
}
return b.String()[0 : b.Len()-2]
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/builder/builder_test.go | core/stores/builder/builder_test.go | package builder
import (
"testing"
"github.com/stretchr/testify/assert"
)
type mockedUser struct {
ID string `db:"id" json:"id,omitempty"`
UserName string `db:"user_name" json:"userName,omitempty"`
Sex int `db:"sex" json:"sex,omitempty"`
UUID string `db:"uuid" uuid:"uuid,omitempty"`
Age int `db:"age" json:"age"`
}
func TestFieldNames(t *testing.T) {
t.Run("new", func(t *testing.T) {
var u mockedUser
out := RawFieldNames(&u)
expected := []string{"`id`", "`user_name`", "`sex`", "`uuid`", "`age`"}
assert.Equal(t, expected, out)
})
}
type mockedUserWithOptions struct {
ID string `db:"id" json:"id,omitempty"`
UserName string `db:"user_name,type=varchar,length=255" json:"userName,omitempty"`
Sex int `db:"sex" json:"sex,omitempty"`
UUID string `db:",type=varchar,length=16" uuid:"uuid,omitempty"`
Age int `db:"age" json:"age"`
}
func TestFieldNamesWithTagOptions(t *testing.T) {
t.Run("new", func(t *testing.T) {
var u mockedUserWithOptions
out := RawFieldNames(&u)
expected := []string{"`id`", "`user_name`", "`sex`", "`UUID`", "`age`"}
assert.Equal(t, expected, out)
})
}
type mockedUserWithDashTag struct {
ID string `db:"id" json:"id,omitempty"`
UserName string `db:"user_name" json:"userName,omitempty"`
Mobile string `db:"-" json:"mobile,omitempty"`
}
func TestFieldNamesWithDashTag(t *testing.T) {
t.Run("new", func(t *testing.T) {
var u mockedUserWithDashTag
out := RawFieldNames(&u)
expected := []string{"`id`", "`user_name`"}
assert.Equal(t, expected, out)
})
}
type mockedUserWithDashTagAndOptions struct {
ID string `db:"id" json:"id,omitempty"`
UserName string `db:"user_name,type=varchar,length=255" json:"userName,omitempty"`
Mobile string `db:"-,type=varchar,length=255" json:"mobile,omitempty"`
}
func TestFieldNamesWithDashTagAndOptions(t *testing.T) {
t.Run("new", func(t *testing.T) {
var u mockedUserWithDashTagAndOptions
out := RawFieldNames(&u)
expected := []string{"`id`", "`user_name`"}
assert.Equal(t, expected, out)
})
}
func TestPostgreSqlJoin(t *testing.T) {
// Test with empty input array
var input []string
var expectedOutput string
assert.Equal(t, expectedOutput, PostgreSqlJoin(input))
// Test with single element input array
input = []string{"foo"}
expectedOutput = "foo = $2"
assert.Equal(t, expectedOutput, PostgreSqlJoin(input))
// Test with multiple elements input array
input = []string{"foo", "bar", "baz"}
expectedOutput = "foo = $2, bar = $3, baz = $4"
assert.Equal(t, expectedOutput, PostgreSqlJoin(input))
}
type testStruct struct {
Foo string `db:"foo"`
Bar int `db:"bar"`
Baz bool `db:"-"`
}
func TestRawFieldNames(t *testing.T) {
// Test with a struct without tags
in := struct {
Foo string
Bar int
}{}
expectedOutput := []string{"`Foo`", "`Bar`"}
assert.ElementsMatch(t, expectedOutput, RawFieldNames(in))
// Test pg without db tag
expectedOutput = []string{"Foo", "Bar"}
assert.ElementsMatch(t, expectedOutput, RawFieldNames(in, true))
// Test with a struct with tags
input := testStruct{}
expectedOutput = []string{"`foo`", "`bar`"}
assert.ElementsMatch(t, expectedOutput, RawFieldNames(input))
// Test with nil input (pointer)
var nilInput *testStruct
assert.Panics(t, func() {
RawFieldNames(nilInput)
}, "RawFieldNames should panic with nil input")
// Test with non-struct input
inputInt := 42
assert.Panics(t, func() {
RawFieldNames(inputInt)
}, "RawFieldNames should panic with non-struct input")
// Test with PostgreSQL flag
input = testStruct{}
expectedOutput = []string{"foo", "bar"}
assert.ElementsMatch(t, expectedOutput, RawFieldNames(input, true))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cacheopt_test.go | core/stores/cache/cacheopt_test.go | package cache
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestCacheOptions(t *testing.T) {
t.Run("default options", func(t *testing.T) {
o := newOptions()
assert.Equal(t, defaultExpiry, o.Expiry)
assert.Equal(t, defaultNotFoundExpiry, o.NotFoundExpiry)
})
t.Run("with expiry", func(t *testing.T) {
o := newOptions(WithExpiry(time.Second))
assert.Equal(t, time.Second, o.Expiry)
assert.Equal(t, defaultNotFoundExpiry, o.NotFoundExpiry)
})
t.Run("with not found expiry", func(t *testing.T) {
o := newOptions(WithNotFoundExpiry(time.Second))
assert.Equal(t, defaultExpiry, o.Expiry)
assert.Equal(t, time.Second, o.NotFoundExpiry)
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cacheconf.go | core/stores/cache/cacheconf.go | package cache
// CacheConf is an alias of ClusterConf.
type CacheConf = ClusterConf
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cache.go | core/stores/cache/cache.go | package cache
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/hash"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/syncx"
)
type (
// Cache interface is used to define the cache implementation.
Cache interface {
// Del deletes cached values with keys.
Del(keys ...string) error
// DelCtx deletes cached values with keys.
DelCtx(ctx context.Context, keys ...string) error
// Get gets the cache with key and fills into v.
Get(key string, val any) error
// GetCtx gets the cache with key and fills into v.
GetCtx(ctx context.Context, key string, val any) error
// IsNotFound checks if the given error is the defined errNotFound.
IsNotFound(err error) bool
// Set sets the cache with key and v, using c.expiry.
Set(key string, val any) error
// SetCtx sets the cache with key and v, using c.expiry.
SetCtx(ctx context.Context, key string, val any) error
// SetWithExpire sets the cache with key and v, using given expire.
SetWithExpire(key string, val any, expire time.Duration) error
// SetWithExpireCtx sets the cache with key and v, using given expire.
SetWithExpireCtx(ctx context.Context, key string, val any, expire time.Duration) error
// Take takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
Take(val any, key string, query func(val any) error) error
// TakeCtx takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
TakeCtx(ctx context.Context, val any, key string, query func(val any) error) error
// TakeWithExpire takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
TakeWithExpire(val any, key string, query func(val any, expire time.Duration) error) error
// TakeWithExpireCtx takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
TakeWithExpireCtx(ctx context.Context, val any, key string,
query func(val any, expire time.Duration) error) error
}
cacheCluster struct {
dispatcher *hash.ConsistentHash
errNotFound error
}
)
// New returns a Cache.
func New(c ClusterConf, barrier syncx.SingleFlight, st *Stat, errNotFound error,
opts ...Option) Cache {
if len(c) == 0 || TotalWeights(c) <= 0 {
log.Fatal("no cache nodes")
}
if len(c) == 1 {
return NewNode(redis.MustNewRedis(c[0].RedisConf), barrier, st, errNotFound, opts...)
}
dispatcher := hash.NewConsistentHash()
for _, node := range c {
cn := NewNode(redis.MustNewRedis(node.RedisConf), barrier, st, errNotFound, opts...)
dispatcher.AddWithWeight(cn, node.Weight)
}
return cacheCluster{
dispatcher: dispatcher,
errNotFound: errNotFound,
}
}
// Del deletes cached values with keys.
func (cc cacheCluster) Del(keys ...string) error {
return cc.DelCtx(context.Background(), keys...)
}
// DelCtx deletes cached values with keys.
func (cc cacheCluster) DelCtx(ctx context.Context, keys ...string) error {
switch len(keys) {
case 0:
return nil
case 1:
key := keys[0]
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).DelCtx(ctx, key)
default:
var be errorx.BatchError
nodes := make(map[any][]string)
for _, key := range keys {
c, ok := cc.dispatcher.Get(key)
if !ok {
be.Add(fmt.Errorf("key %q not found", key))
continue
}
nodes[c] = append(nodes[c], key)
}
for c, ks := range nodes {
if err := c.(Cache).DelCtx(ctx, ks...); err != nil {
be.Add(err)
}
}
return be.Err()
}
}
// Get gets the cache with key and fills into v.
func (cc cacheCluster) Get(key string, val any) error {
return cc.GetCtx(context.Background(), key, val)
}
// GetCtx gets the cache with key and fills into v.
func (cc cacheCluster) GetCtx(ctx context.Context, key string, val any) error {
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).GetCtx(ctx, key, val)
}
// IsNotFound checks if the given error is the defined errNotFound.
func (cc cacheCluster) IsNotFound(err error) bool {
return errors.Is(err, cc.errNotFound)
}
// Set sets the cache with key and v, using c.expiry.
func (cc cacheCluster) Set(key string, val any) error {
return cc.SetCtx(context.Background(), key, val)
}
// SetCtx sets the cache with key and v, using c.expiry.
func (cc cacheCluster) SetCtx(ctx context.Context, key string, val any) error {
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).SetCtx(ctx, key, val)
}
// SetWithExpire sets the cache with key and v, using given expire.
func (cc cacheCluster) SetWithExpire(key string, val any, expire time.Duration) error {
return cc.SetWithExpireCtx(context.Background(), key, val, expire)
}
// SetWithExpireCtx sets the cache with key and v, using given expire.
func (cc cacheCluster) SetWithExpireCtx(ctx context.Context, key string, val any, expire time.Duration) error {
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).SetWithExpireCtx(ctx, key, val, expire)
}
// Take takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
func (cc cacheCluster) Take(val any, key string, query func(val any) error) error {
return cc.TakeCtx(context.Background(), val, key, query)
}
// TakeCtx takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
func (cc cacheCluster) TakeCtx(ctx context.Context, val any, key string, query func(val any) error) error {
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).TakeCtx(ctx, val, key, query)
}
// TakeWithExpire takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
func (cc cacheCluster) TakeWithExpire(val any, key string, query func(val any, expire time.Duration) error) error {
return cc.TakeWithExpireCtx(context.Background(), val, key, query)
}
// TakeWithExpireCtx takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
func (cc cacheCluster) TakeWithExpireCtx(ctx context.Context, val any, key string, query func(val any, expire time.Duration) error) error {
c, ok := cc.dispatcher.Get(key)
if !ok {
return cc.errNotFound
}
return c.(Cache).TakeWithExpireCtx(ctx, val, key, query)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cache_test.go | core/stores/cache/cache_test.go | package cache
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/hash"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
"github.com/zeromicro/go-zero/core/syncx"
)
var _ Cache = (*mockedNode)(nil)
type mockedNode struct {
vals map[string][]byte
errNotFound error
}
func (mc *mockedNode) Del(keys ...string) error {
return mc.DelCtx(context.Background(), keys...)
}
func (mc *mockedNode) DelCtx(_ context.Context, keys ...string) error {
var be errorx.BatchError
for _, key := range keys {
if _, ok := mc.vals[key]; !ok {
be.Add(mc.errNotFound)
} else {
delete(mc.vals, key)
}
}
return be.Err()
}
func (mc *mockedNode) Get(key string, val any) error {
return mc.GetCtx(context.Background(), key, val)
}
func (mc *mockedNode) GetCtx(ctx context.Context, key string, val any) error {
bs, ok := mc.vals[key]
if ok {
return json.Unmarshal(bs, val)
}
return mc.errNotFound
}
func (mc *mockedNode) IsNotFound(err error) bool {
return errors.Is(err, mc.errNotFound)
}
func (mc *mockedNode) Set(key string, val any) error {
return mc.SetCtx(context.Background(), key, val)
}
func (mc *mockedNode) SetCtx(ctx context.Context, key string, val any) error {
data, err := json.Marshal(val)
if err != nil {
return err
}
mc.vals[key] = data
return nil
}
func (mc *mockedNode) SetWithExpire(key string, val any, expire time.Duration) error {
return mc.SetWithExpireCtx(context.Background(), key, val, expire)
}
func (mc *mockedNode) SetWithExpireCtx(ctx context.Context, key string, val any, expire time.Duration) error {
return mc.Set(key, val)
}
func (mc *mockedNode) Take(val any, key string, query func(val any) error) error {
return mc.TakeCtx(context.Background(), val, key, query)
}
func (mc *mockedNode) TakeCtx(ctx context.Context, val any, key string, query func(val any) error) error {
if _, ok := mc.vals[key]; ok {
return mc.GetCtx(ctx, key, val)
}
if err := query(val); err != nil {
return err
}
return mc.SetCtx(ctx, key, val)
}
func (mc *mockedNode) TakeWithExpire(val any, key string, query func(val any, expire time.Duration) error) error {
return mc.TakeWithExpireCtx(context.Background(), val, key, query)
}
func (mc *mockedNode) TakeWithExpireCtx(ctx context.Context, val any, key string, query func(val any, expire time.Duration) error) error {
return mc.Take(val, key, func(val any) error {
return query(val, 0)
})
}
func TestCache_SetDel(t *testing.T) {
t.Run("test set del", func(t *testing.T) {
const total = 1000
r1 := redistest.CreateRedis(t)
r2 := redistest.CreateRedis(t)
conf := ClusterConf{
{
RedisConf: redis.RedisConf{
Host: r1.Addr,
Type: redis.NodeType,
},
Weight: 100,
},
{
RedisConf: redis.RedisConf{
Host: r2.Addr,
Type: redis.NodeType,
},
Weight: 100,
},
}
c := New(conf, syncx.NewSingleFlight(), NewStat("mock"), errPlaceholder)
for i := 0; i < total; i++ {
if i%2 == 0 {
assert.Nil(t, c.Set(fmt.Sprintf("key/%d", i), i))
} else {
assert.Nil(t, c.SetWithExpire(fmt.Sprintf("key/%d", i), i, 0))
}
}
for i := 0; i < total; i++ {
var val int
assert.Nil(t, c.Get(fmt.Sprintf("key/%d", i), &val))
assert.Equal(t, i, val)
}
assert.Nil(t, c.Del())
for i := 0; i < total; i++ {
assert.Nil(t, c.Del(fmt.Sprintf("key/%d", i)))
}
assert.Nil(t, c.Del("a", "b", "c"))
for i := 0; i < total; i++ {
var val int
assert.True(t, c.IsNotFound(c.Get(fmt.Sprintf("key/%d", i), &val)))
assert.Equal(t, 0, val)
}
})
t.Run("test set del error", func(t *testing.T) {
r1, err := miniredis.Run()
assert.NoError(t, err)
defer r1.Close()
r2, err := miniredis.Run()
assert.NoError(t, err)
defer r2.Close()
conf := ClusterConf{
{
RedisConf: redis.RedisConf{
Host: r1.Addr(),
Type: redis.NodeType,
},
Weight: 100,
},
{
RedisConf: redis.RedisConf{
Host: r2.Addr(),
Type: redis.NodeType,
},
Weight: 100,
},
}
c := New(conf, syncx.NewSingleFlight(), NewStat("mock"), errPlaceholder)
r1.SetError("mock error")
r2.SetError("mock error")
assert.NoError(t, c.Del("a", "b", "c"))
})
}
func TestCache_OneNode(t *testing.T) {
const total = 1000
r := redistest.CreateRedis(t)
conf := ClusterConf{
{
RedisConf: redis.RedisConf{
Host: r.Addr,
Type: redis.NodeType,
},
Weight: 100,
},
}
c := New(conf, syncx.NewSingleFlight(), NewStat("mock"), errPlaceholder)
for i := 0; i < total; i++ {
if i%2 == 0 {
assert.Nil(t, c.Set(fmt.Sprintf("key/%d", i), i))
} else {
assert.Nil(t, c.SetWithExpire(fmt.Sprintf("key/%d", i), i, 0))
}
}
for i := 0; i < total; i++ {
var val int
assert.Nil(t, c.Get(fmt.Sprintf("key/%d", i), &val))
assert.Equal(t, i, val)
}
assert.Nil(t, c.Del())
for i := 0; i < total; i++ {
assert.Nil(t, c.Del(fmt.Sprintf("key/%d", i)))
}
for i := 0; i < total; i++ {
var val int
assert.True(t, c.IsNotFound(c.Get(fmt.Sprintf("key/%d", i), &val)))
assert.Equal(t, 0, val)
}
}
func TestCache_Balance(t *testing.T) {
const (
numNodes = 100
total = 10000
)
dispatcher := hash.NewConsistentHash()
maps := make([]map[string][]byte, numNodes)
for i := 0; i < numNodes; i++ {
maps[i] = map[string][]byte{
strconv.Itoa(i): []byte(strconv.Itoa(i)),
}
}
for i := 0; i < numNodes; i++ {
dispatcher.AddWithWeight(&mockedNode{
vals: maps[i],
errNotFound: errPlaceholder,
}, 100)
}
c := cacheCluster{
dispatcher: dispatcher,
errNotFound: errPlaceholder,
}
for i := 0; i < total; i++ {
assert.Nil(t, c.Set(strconv.Itoa(i), i))
}
counts := make(map[int]int)
for i, m := range maps {
counts[i] = len(m)
}
entropy := calcEntropy(counts, total)
assert.True(t, len(counts) > 1)
assert.True(t, entropy > .95, fmt.Sprintf("entropy should be greater than 0.95, but got %.2f", entropy))
for i := 0; i < total; i++ {
var val int
assert.Nil(t, c.Get(strconv.Itoa(i), &val))
assert.Equal(t, i, val)
}
for i := 0; i < total/10; i++ {
assert.Nil(t, c.Del(strconv.Itoa(i*10), strconv.Itoa(i*10+1), strconv.Itoa(i*10+2)))
assert.Nil(t, c.Del(strconv.Itoa(i*10+9)))
}
var count int
for i := 0; i < total/10; i++ {
var val int
if i%2 == 0 {
assert.Nil(t, c.Take(&val, strconv.Itoa(i*10), func(val any) error {
*val.(*int) = i
count++
return nil
}))
} else {
assert.Nil(t, c.TakeWithExpire(&val, strconv.Itoa(i*10), func(val any, expire time.Duration) error {
*val.(*int) = i
count++
return nil
}))
}
assert.Equal(t, i, val)
}
assert.Equal(t, total/10, count)
}
func TestCacheNoNode(t *testing.T) {
dispatcher := hash.NewConsistentHash()
c := cacheCluster{
dispatcher: dispatcher,
errNotFound: errPlaceholder,
}
assert.NotNil(t, c.Del("foo"))
assert.NotNil(t, c.Del("foo", "bar", "any"))
assert.NotNil(t, c.Get("foo", nil))
assert.NotNil(t, c.Set("foo", nil))
assert.NotNil(t, c.SetWithExpire("foo", nil, time.Second))
assert.NotNil(t, c.Take(nil, "foo", func(val any) error {
return nil
}))
assert.NotNil(t, c.TakeWithExpire(nil, "foo", func(val any, duration time.Duration) error {
return nil
}))
}
func calcEntropy(m map[int]int, total int) float64 {
var entropy float64
for _, val := range m {
proba := float64(val) / float64(total)
entropy -= proba * math.Log2(proba)
}
return entropy / math.Log2(float64(len(m)))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/config.go | core/stores/cache/config.go | package cache
import "github.com/zeromicro/go-zero/core/stores/redis"
type (
// A ClusterConf is the config of a redis cluster that used as cache.
ClusterConf []NodeConf
// A NodeConf is the config of a redis node that used as cache.
NodeConf struct {
redis.RedisConf
Weight int `json:",default=100"`
}
)
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cachestat_test.go | core/stores/cache/cachestat_test.go | package cache
import (
"testing"
"github.com/zeromicro/go-zero/core/timex"
)
func TestCacheStat_statLoop(t *testing.T) {
t.Run("stat loop total 0", func(t *testing.T) {
var stat Stat
ticker := timex.NewFakeTicker()
go stat.statLoop(ticker)
ticker.Tick()
ticker.Tick()
ticker.Stop()
})
t.Run("stat loop total not 0", func(t *testing.T) {
var stat Stat
stat.IncrementTotal()
ticker := timex.NewFakeTicker()
go stat.statLoop(ticker)
ticker.Tick()
ticker.Tick()
ticker.Stop()
})
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/util.go | core/stores/cache/util.go | package cache
import "strings"
const keySeparator = ","
// TotalWeights returns the total weights of given nodes.
func TotalWeights(c []NodeConf) int {
var weights int
for _, node := range c {
if node.Weight < 0 {
node.Weight = 0
}
weights += node.Weight
}
return weights
}
func formatKeys(keys []string) string {
return strings.Join(keys, keySeparator)
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cleaner_test.go | core/stores/cache/cleaner_test.go | package cache
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/timex"
)
func TestNextDelay(t *testing.T) {
tests := []struct {
name string
input time.Duration
output time.Duration
ok bool
}{
{
name: "second",
input: time.Second,
output: time.Second * 5,
ok: true,
},
{
name: "5 seconds",
input: time.Second * 5,
output: time.Minute,
ok: true,
},
{
name: "minute",
input: time.Minute,
output: time.Minute * 5,
ok: true,
},
{
name: "5 minutes",
input: time.Minute * 5,
output: time.Hour,
ok: true,
},
{
name: "hour",
input: time.Hour,
output: 0,
ok: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
old := timingWheel.Load()
ticker := timex.NewFakeTicker()
tw, err := collection.NewTimingWheelWithTicker(
time.Millisecond, timingWheelSlots, func(key, value any) {
clean(key, value)
}, ticker)
timingWheel.Store(tw)
assert.NoError(t, err)
t.Cleanup(func() {
timingWheel.Store(old)
})
next, ok := nextDelay(test.input)
assert.Equal(t, test.ok, ok)
assert.Equal(t, test.output, next)
proc.Shutdown()
})
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cacheopt.go | core/stores/cache/cacheopt.go | package cache
import "time"
const (
defaultExpiry = time.Hour * 24 * 7
defaultNotFoundExpiry = time.Minute
)
type (
// Options is used to store the cache options.
Options struct {
Expiry time.Duration
NotFoundExpiry time.Duration
}
// Option defines the method to customize an Options.
Option func(o *Options)
)
func newOptions(opts ...Option) Options {
var o Options
for _, opt := range opts {
opt(&o)
}
if o.Expiry <= 0 {
o.Expiry = defaultExpiry
}
if o.NotFoundExpiry <= 0 {
o.NotFoundExpiry = defaultNotFoundExpiry
}
return o
}
// WithExpiry returns a func to customize an Options with given expiry.
func WithExpiry(expiry time.Duration) Option {
return func(o *Options) {
o.Expiry = expiry
}
}
// WithNotFoundExpiry returns a func to customize an Options with given not found expiry.
func WithNotFoundExpiry(expiry time.Duration) Option {
return func(o *Options) {
o.NotFoundExpiry = expiry
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cachenode_test.go | core/stores/cache/cachenode_test.go | package cache
import (
"errors"
"fmt"
"math/rand"
"runtime"
"strconv"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/redis/redistest"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
)
var errTestNotFound = errors.New("not found")
func init() {
logx.Disable()
stat.SetReporter(nil)
}
func TestCacheNode_DelCache(t *testing.T) {
t.Run("del cache", func(t *testing.T) {
r, err := miniredis.Run()
assert.NoError(t, err)
defer r.Close()
store := redis.New(r.Addr(), redis.Cluster())
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
assert.Nil(t, cn.Del())
assert.Nil(t, cn.Del([]string{}...))
assert.Nil(t, cn.Del(make([]string, 0)...))
cn.Set("first", "one")
assert.Nil(t, cn.Del("first"))
cn.Set("first", "one")
cn.Set("second", "two")
assert.Nil(t, cn.Del("first", "second"))
})
t.Run("del cache with errors", func(t *testing.T) {
old := timingWheel.Load()
ticker := timex.NewFakeTicker()
tw, err := collection.NewTimingWheelWithTicker(
time.Millisecond, timingWheelSlots, func(key, value any) {
clean(key, value)
}, ticker)
timingWheel.Store(tw)
assert.NoError(t, err)
t.Cleanup(func() {
timingWheel.Store(old)
})
r, err := miniredis.Run()
assert.NoError(t, err)
defer r.Close()
r.SetError("mock error")
node := NewNode(redis.New(r.Addr(), redis.Cluster()), syncx.NewSingleFlight(),
NewStat("any"), errTestNotFound)
assert.NoError(t, node.Del("foo", "bar"))
ticker.Tick()
runtime.Gosched()
})
}
func TestCacheNode_DelCacheWithErrors(t *testing.T) {
store := redistest.CreateRedis(t)
store.Type = redis.ClusterType
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
assert.Nil(t, cn.Del("third", "fourth"))
}
func TestCacheNode_InvalidCache(t *testing.T) {
s, err := miniredis.Run()
assert.Nil(t, err)
defer s.Close()
cn := cacheNode{
rds: redis.New(s.Addr()),
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
s.Set("any", "value")
var str string
assert.NotNil(t, cn.Get("any", &str))
assert.Equal(t, "", str)
_, err = s.Get("any")
assert.Equal(t, miniredis.ErrKeyNotFound, err)
}
func TestCacheNode_SetWithExpire(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errors.New("any"),
}
assert.NotNil(t, cn.SetWithExpire("key", make(chan int), time.Second))
}
func TestCacheNode_Take(t *testing.T) {
store := redistest.CreateRedis(t)
cn := NewNode(store, syncx.NewSingleFlight(), NewStat("any"), errTestNotFound,
WithExpiry(time.Second), WithNotFoundExpiry(time.Second))
var str string
err := cn.Take(&str, "any", func(v any) error {
*v.(*string) = "value"
return nil
})
assert.Nil(t, err)
assert.Equal(t, "value", str)
assert.Nil(t, cn.Get("any", &str))
val, err := store.Get("any")
assert.Nil(t, err)
assert.Equal(t, `"value"`, val)
}
func TestCacheNode_TakeBadRedis(t *testing.T) {
r, err := miniredis.Run()
assert.NoError(t, err)
defer r.Close()
r.SetError("mock error")
cn := NewNode(redis.New(r.Addr()), syncx.NewSingleFlight(), NewStat("any"),
errTestNotFound, WithExpiry(time.Second), WithNotFoundExpiry(time.Second))
var str string
assert.Error(t, cn.Take(&str, "any", func(v any) error {
*v.(*string) = "value"
return nil
}))
}
func TestCacheNode_TakeNotFound(t *testing.T) {
t.Run("not found", func(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
var str string
err := cn.Take(&str, "any", func(v any) error {
return errTestNotFound
})
assert.True(t, cn.IsNotFound(err))
assert.True(t, cn.IsNotFound(cn.Get("any", &str)))
val, err := store.Get("any")
assert.Nil(t, err)
assert.Equal(t, `*`, val)
store.Set("any", "*")
err = cn.Take(&str, "any", func(v any) error {
return nil
})
assert.True(t, cn.IsNotFound(err))
assert.True(t, cn.IsNotFound(cn.Get("any", &str)))
store.Del("any")
errDummy := errors.New("dummy")
err = cn.Take(&str, "any", func(v any) error {
return errDummy
})
assert.Equal(t, errDummy, err)
})
t.Run("not found with redis error", func(t *testing.T) {
r, err := miniredis.Run()
assert.NoError(t, err)
defer r.Close()
store, err := redis.NewRedis(redis.RedisConf{
Host: r.Addr(),
Type: redis.NodeType,
})
assert.NoError(t, err)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
var str string
err = cn.Take(&str, "any", func(v any) error {
r.SetError("mock error")
return errTestNotFound
})
assert.True(t, cn.IsNotFound(err))
})
}
func TestCacheNode_TakeCtxWithRedisError(t *testing.T) {
t.Run("not found with redis error", func(t *testing.T) {
r, err := miniredis.Run()
assert.NoError(t, err)
defer r.Close()
store, err := redis.NewRedis(redis.RedisConf{
Host: r.Addr(),
Type: redis.NodeType,
})
assert.NoError(t, err)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
var str string
err = cn.Take(&str, "any", func(v any) error {
str = "foo"
r.SetError("mock error")
return nil
})
assert.NoError(t, err)
})
}
func TestCacheNode_TakeNotFoundButChangedByOthers(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errTestNotFound,
}
var str string
err := cn.Take(&str, "any", func(v any) error {
store.Set("any", "foo")
return errTestNotFound
})
assert.True(t, cn.IsNotFound(err))
val, err := store.Get("any")
if assert.NoError(t, err) {
assert.Equal(t, "foo", val)
}
assert.True(t, cn.IsNotFound(cn.Get("any", &str)))
}
func TestCacheNode_TakeWithExpire(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errors.New("any"),
}
var str string
err := cn.TakeWithExpire(&str, "any", func(v any, expire time.Duration) error {
*v.(*string) = "value"
return nil
})
assert.Nil(t, err)
assert.Equal(t, "value", str)
assert.Nil(t, cn.Get("any", &str))
val, err := store.Get("any")
assert.Nil(t, err)
assert.Equal(t, `"value"`, val)
}
func TestCacheNode_String(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errors.New("any"),
}
assert.Equal(t, store.Addr, cn.String())
}
func TestCacheValueWithBigInt(t *testing.T) {
store := redistest.CreateRedis(t)
cn := cacheNode{
rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSingleFlight(),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: NewStat("any"),
errNotFound: errors.New("any"),
}
const (
key = "key"
value int64 = 323427211229009810
)
assert.Nil(t, cn.Set(key, value))
var val any
assert.Nil(t, cn.Get(key, &val))
assert.Equal(t, strconv.FormatInt(value, 10), fmt.Sprintf("%v", val))
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cachenode.go | core/stores/cache/cachenode.go | package cache
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"sync"
"time"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/syncx"
)
const (
notFoundPlaceholder = "*"
// make the expiry unstable to avoid lots of cached items expire at the same time
// make the unstable expiry to be [0.95, 1.05] * seconds
expiryDeviation = 0.05
)
// indicates there is no such value associate with the key
var errPlaceholder = errors.New("placeholder")
type cacheNode struct {
rds *redis.Redis
expiry time.Duration
notFoundExpiry time.Duration
barrier syncx.SingleFlight
r *rand.Rand
lock *sync.Mutex
unstableExpiry mathx.Unstable
stat *Stat
errNotFound error
}
// NewNode returns a cacheNode.
// rds is the underlying redis node or cluster.
// barrier is the barrier that maybe shared with other cache nodes on cache cluster.
// st is used to stat the cache.
// errNotFound defines the error that returned on cache not found.
// opts are the options that customize the cacheNode.
func NewNode(rds *redis.Redis, barrier syncx.SingleFlight, st *Stat,
errNotFound error, opts ...Option) Cache {
o := newOptions(opts...)
return cacheNode{
rds: rds,
expiry: o.Expiry,
notFoundExpiry: o.NotFoundExpiry,
barrier: barrier,
r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation),
stat: st,
errNotFound: errNotFound,
}
}
// Del deletes cached values with keys.
func (c cacheNode) Del(keys ...string) error {
return c.DelCtx(context.Background(), keys...)
}
// DelCtx deletes cached values with keys.
func (c cacheNode) DelCtx(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
logger := logx.WithContext(ctx)
if len(keys) > 1 && c.rds.Type == redis.ClusterType {
for _, key := range keys {
if _, err := c.rds.DelCtx(ctx, key); err != nil {
logger.Errorf("failed to clear cache with key: %q, error: %v", key, err)
c.asyncRetryDelCache(key)
}
}
} else if _, err := c.rds.DelCtx(ctx, keys...); err != nil {
logger.Errorf("failed to clear cache with keys: %q, error: %v", formatKeys(keys), err)
c.asyncRetryDelCache(keys...)
}
return nil
}
// Get gets the cache with key and fills into v.
func (c cacheNode) Get(key string, val any) error {
return c.GetCtx(context.Background(), key, val)
}
// GetCtx gets the cache with key and fills into v.
func (c cacheNode) GetCtx(ctx context.Context, key string, val any) error {
err := c.doGetCache(ctx, key, val)
if errors.Is(err, errPlaceholder) {
return c.errNotFound
}
return err
}
// IsNotFound checks if the given error is the defined errNotFound.
func (c cacheNode) IsNotFound(err error) bool {
return errors.Is(err, c.errNotFound)
}
// Set sets the cache with key and v, using c.expiry.
func (c cacheNode) Set(key string, val any) error {
return c.SetCtx(context.Background(), key, val)
}
// SetCtx sets the cache with key and v, using c.expiry.
func (c cacheNode) SetCtx(ctx context.Context, key string, val any) error {
return c.SetWithExpireCtx(ctx, key, val, c.aroundDuration(c.expiry))
}
// SetWithExpire sets the cache with key and v, using given expire.
func (c cacheNode) SetWithExpire(key string, val any, expire time.Duration) error {
return c.SetWithExpireCtx(context.Background(), key, val, expire)
}
// SetWithExpireCtx sets the cache with key and v, using given expire.
func (c cacheNode) SetWithExpireCtx(ctx context.Context, key string, val any,
expire time.Duration) error {
data, err := jsonx.Marshal(val)
if err != nil {
return err
}
return c.rds.SetexCtx(ctx, key, string(data), int(math.Ceil(expire.Seconds())))
}
// String returns a string that represents the cacheNode.
func (c cacheNode) String() string {
return c.rds.Addr
}
// Take takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
func (c cacheNode) Take(val any, key string, query func(val any) error) error {
return c.TakeCtx(context.Background(), val, key, query)
}
// TakeCtx takes the result from cache first, if not found,
// query from DB and set cache using c.expiry, then return the result.
func (c cacheNode) TakeCtx(ctx context.Context, val any, key string,
query func(val any) error) error {
return c.doTake(ctx, val, key, query, func(v any) error {
return c.SetCtx(ctx, key, v)
})
}
// TakeWithExpire takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
func (c cacheNode) TakeWithExpire(val any, key string, query func(val any,
expire time.Duration) error) error {
return c.TakeWithExpireCtx(context.Background(), val, key, query)
}
// TakeWithExpireCtx takes the result from cache first, if not found,
// query from DB and set cache using given expire, then return the result.
func (c cacheNode) TakeWithExpireCtx(ctx context.Context, val any, key string,
query func(val any, expire time.Duration) error) error {
expire := c.aroundDuration(c.expiry)
return c.doTake(ctx, val, key, func(v any) error {
return query(v, expire)
}, func(v any) error {
return c.SetWithExpireCtx(ctx, key, v, expire)
})
}
func (c cacheNode) aroundDuration(duration time.Duration) time.Duration {
return c.unstableExpiry.AroundDuration(duration)
}
func (c cacheNode) asyncRetryDelCache(keys ...string) {
AddCleanTask(func() error {
_, err := c.rds.Del(keys...)
return err
}, keys...)
}
func (c cacheNode) doGetCache(ctx context.Context, key string, v any) error {
c.stat.IncrementTotal()
data, err := c.rds.GetCtx(ctx, key)
if err != nil {
c.stat.IncrementMiss()
return err
}
if len(data) == 0 {
c.stat.IncrementMiss()
return c.errNotFound
}
c.stat.IncrementHit()
if data == notFoundPlaceholder {
return errPlaceholder
}
return c.processCache(ctx, key, data, v)
}
func (c cacheNode) doTake(ctx context.Context, v any, key string,
query func(v any) error, cacheVal func(v any) error) error {
logger := logx.WithContext(ctx)
val, fresh, err := c.barrier.DoEx(key, func() (any, error) {
if err := c.doGetCache(ctx, key, v); err != nil {
if errors.Is(err, errPlaceholder) {
return nil, c.errNotFound
} else if !errors.Is(err, c.errNotFound) {
// why we just return the error instead of query from db,
// because we don't allow the disaster pass to the dbs.
// fail fast, in case we bring down the dbs.
return nil, err
}
if err = query(v); errors.Is(err, c.errNotFound) {
if err = c.setCacheWithNotFound(ctx, key); err != nil {
logger.Error(err)
}
return nil, c.errNotFound
} else if err != nil {
c.stat.IncrementDbFails()
return nil, err
}
if err = cacheVal(v); err != nil {
logger.Error(err)
}
}
return jsonx.Marshal(v)
})
if err != nil {
return err
}
if fresh {
return nil
}
// got the result from previous ongoing query.
// why not call IncrementTotal at the beginning of this function?
// because a shared error is returned, and we don't want to count.
// for example, if the db is down, the query will be failed, we count
// the shared errors with one db failure.
c.stat.IncrementTotal()
c.stat.IncrementHit()
return jsonx.Unmarshal(val.([]byte), v)
}
func (c cacheNode) processCache(ctx context.Context, key, data string, v any) error {
err := jsonx.Unmarshal([]byte(data), v)
if err == nil {
return nil
}
report := fmt.Sprintf("unmarshal cache, node: %s, key: %s, value: %s, error: %v",
c.rds.Addr, key, data, err)
logger := logx.WithContext(ctx)
logger.Error(report)
stat.Report(report)
if _, e := c.rds.DelCtx(ctx, key); e != nil {
logger.Errorf("delete invalid cache, node: %s, key: %s, value: %s, error: %v",
c.rds.Addr, key, data, e)
}
// returns errNotFound to reload the value by the given queryFn
return c.errNotFound
}
func (c cacheNode) setCacheWithNotFound(ctx context.Context, key string) error {
seconds := int(math.Ceil(c.aroundDuration(c.notFoundExpiry).Seconds()))
_, err := c.rds.SetnxExCtx(ctx, key, notFoundPlaceholder, seconds)
return err
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
zeromicro/go-zero | https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/core/stores/cache/cachestat.go | core/stores/cache/cachestat.go | package cache
import (
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/timex"
)
const statInterval = time.Minute
// A Stat is used to stat the cache.
type Stat struct {
name string
// export the fields to let the unit tests working,
// reside in internal package, doesn't matter.
Total uint64
Hit uint64
Miss uint64
DbFails uint64
}
// NewStat returns a Stat.
func NewStat(name string) *Stat {
ret := &Stat{
name: name,
}
go func() {
ticker := timex.NewTicker(statInterval)
defer ticker.Stop()
ret.statLoop(ticker)
}()
return ret
}
// IncrementTotal increments the total count.
func (s *Stat) IncrementTotal() {
atomic.AddUint64(&s.Total, 1)
}
// IncrementHit increments the hit count.
func (s *Stat) IncrementHit() {
atomic.AddUint64(&s.Hit, 1)
}
// IncrementMiss increments the miss count.
func (s *Stat) IncrementMiss() {
atomic.AddUint64(&s.Miss, 1)
}
// IncrementDbFails increments the db fail count.
func (s *Stat) IncrementDbFails() {
atomic.AddUint64(&s.DbFails, 1)
}
func (s *Stat) statLoop(ticker timex.Ticker) {
for range ticker.Chan() {
total := atomic.SwapUint64(&s.Total, 0)
if total == 0 {
continue
}
hit := atomic.SwapUint64(&s.Hit, 0)
percent := 100 * float32(hit) / float32(total)
miss := atomic.SwapUint64(&s.Miss, 0)
dbf := atomic.SwapUint64(&s.DbFails, 0)
logx.Statf("dbcache(%s) - qpm: %d, hit_ratio: %.1f%%, hit: %d, miss: %d, db_fails: %d",
s.name, total, percent, hit, miss, dbf)
}
}
| go | MIT | 8e7e5695eb2095917864b5d6615dab4c90bde3ac | 2026-01-07T08:36:18.042207Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.