ledisdb/server/script.go

436 lines
8.1 KiB
Go
Raw Normal View History

2014-09-02 13:55:12 +04:00
package server
import (
"encoding/hex"
2017-04-15 16:51:03 +03:00
"errors"
2014-09-02 13:55:12 +04:00
"fmt"
2015-05-04 17:42:28 +03:00
"io"
2017-04-15 16:51:03 +03:00
"strings"
2015-05-04 17:42:28 +03:00
"sync"
2023-02-15 10:41:45 +03:00
"git.internal/re/ledisdb/ledis"
2014-09-24 08:34:21 +04:00
"github.com/siddontang/go/hack"
2014-09-24 09:29:27 +04:00
"github.com/siddontang/go/num"
2020-04-24 09:10:03 +03:00
lua "github.com/yuin/gopher-lua"
2017-04-15 16:51:03 +03:00
luajson "github.com/glendc/gopher-json"
2014-09-02 13:55:12 +04:00
)
//ledis <-> lua type conversion, same as http://redis.io/commands/eval
type luaWriter struct {
2017-04-15 16:51:03 +03:00
l *lua.LState
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeError(err error) {
panic(err)
}
func (w *luaWriter) writeStatus(status string) {
2017-04-15 16:51:03 +03:00
table := w.l.NewTable()
table.Append(lua.LString("ok"))
table.Append(lua.LString(status))
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
w.l.Push(table)
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeInteger(n int64) {
2017-04-15 16:51:03 +03:00
w.l.Push(w.toLuaInteger(n))
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeBulk(b []byte) {
2017-04-15 16:51:03 +03:00
w.l.Push(w.toLuaBulk(b))
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeArray(lst []interface{}) {
2017-04-15 16:51:03 +03:00
w.l.Push(w.toLuaArray(lst))
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeSliceArray(lst [][]byte) {
2017-04-15 16:51:03 +03:00
w.l.Push(w.toLuaSliceArray(lst))
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeFVPairArray(lst []ledis.FVPair) {
if lst == nil {
2017-04-15 16:51:03 +03:00
w.l.Push(lua.LFalse)
2014-09-02 13:55:12 +04:00
return
}
2017-04-15 16:51:03 +03:00
table := w.l.CreateTable(len(lst)*2, 0)
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
for _, v := range lst {
table.Append(lua.LString(hack.String(v.Field)))
table.Append(lua.LString(hack.String(v.Value)))
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
w.l.Push(table)
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeScorePairArray(lst []ledis.ScorePair, withScores bool) {
if lst == nil {
2017-04-15 16:51:03 +03:00
w.l.Push(lua.LFalse)
2014-09-02 13:55:12 +04:00
return
}
2017-04-15 16:51:03 +03:00
var table *lua.LTable
2014-09-02 13:55:12 +04:00
if withScores {
2017-04-15 16:51:03 +03:00
table = w.l.CreateTable(len(lst)*2, 0)
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
for _, v := range lst {
table.Append(lua.LString(hack.String(v.Member)))
table.Append(lua.LString(num.FormatInt64ToSlice(v.Score)))
2014-09-02 13:55:12 +04:00
}
} else {
2017-04-15 16:51:03 +03:00
table = w.l.CreateTable(len(lst), 0)
for _, v := range lst {
table.Append(lua.LString(hack.String(v.Member)))
2014-09-02 13:55:12 +04:00
}
}
2017-04-15 16:51:03 +03:00
w.l.Push(table)
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) writeBulkFrom(n int64, rb io.Reader) {
2017-04-15 16:51:03 +03:00
w.writeError(errors.New("unsupport"))
2014-09-02 13:55:12 +04:00
}
func (w *luaWriter) flush() {
2017-04-15 16:51:03 +03:00
}
func (w *luaWriter) toLuaInteger(n int64) lua.LValue {
return lua.LNumber(n)
}
func (w *luaWriter) toLuaBulk(b []byte) lua.LValue {
if b == nil {
return lua.LFalse
}
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
return lua.LString(hack.String(b))
}
func (w *luaWriter) toLuaSliceArray(lst [][]byte) lua.LValue {
if lst == nil {
return lua.LFalse
}
table := w.l.CreateTable(len(lst), 0)
for _, v := range lst {
if v == nil {
table.Append(lua.LFalse)
} else {
table.Append(lua.LString((hack.String(v))))
}
}
return table
}
func (w *luaWriter) toLuaArray(lst []interface{}) lua.LValue {
if lst == nil {
return lua.LFalse
}
table := w.l.CreateTable(len(lst), 0)
for i := range lst {
switch v := lst[i].(type) {
case []interface{}:
table.Append(w.toLuaArray(v))
case [][]byte:
table.Append(w.toLuaSliceArray(v))
case []byte:
table.Append(w.toLuaBulk(v))
case nil:
table.Append(w.toLuaBulk(nil))
case int64:
table.Append(w.toLuaInteger(v))
default:
panic("invalid array type")
}
}
return table
2014-09-02 13:55:12 +04:00
}
type script struct {
sync.Mutex
app *App
2017-04-15 16:51:03 +03:00
l *lua.LState
2014-09-02 13:55:12 +04:00
c *client
chunks map[string]struct{}
}
func (app *App) openScript() {
s := new(script)
s.app = app
s.chunks = make(map[string]struct{})
app.script = s
2014-09-02 13:55:12 +04:00
l := lua.NewState()
2017-04-15 16:51:03 +03:00
for _, pair := range []struct {
n string
f lua.LGFunction
}{
{lua.LoadLibName, lua.OpenPackage}, // Must be first
{lua.BaseLibName, lua.OpenBase},
{lua.MathLibName, lua.OpenMath},
{lua.StringLibName, lua.OpenString},
{lua.TabLibName, lua.OpenTable},
{luajson.CJsonLibName, luajson.OpenCJSON},
// TODO (gopher-lua): support libs:
// + CMsgpackLib?! (which funcs?)
// + StructLib?! (which funcs?)
} {
l.Push(l.NewFunction(pair.f))
l.Push(lua.LString(pair.n))
l.Call(1, 0)
}
l.Register("error", luaErrorHandler)
2014-09-02 13:55:12 +04:00
s.l = l
s.c = newClient(app)
s.c.db = nil
w := new(luaWriter)
w.l = l
s.c.resp = w
2017-04-15 16:51:03 +03:00
setLuaDBGlobalVar(l, "ledis")
setLuaDBGlobalVar(l, "redis")
setMapState(l, s)
}
func (app *App) closeScript() {
app.script.l.Close()
delMapState(app.script.l)
app.script = nil
}
2017-04-15 16:51:03 +03:00
var mapState = map[*lua.LState]*script{}
var stateLock sync.Mutex
2017-04-15 16:51:03 +03:00
func setLuaDBGlobalVar(l *lua.LState, name string) {
mt := l.NewTypeMetatable(name)
l.SetGlobal(name, mt)
// static attributes
l.SetField(mt, "call", l.NewFunction(luaCall))
l.SetField(mt, "pcall", l.NewFunction(luaPCall))
l.SetField(mt, "sha1hex", l.NewFunction(luaSha1Hex))
l.SetField(mt, "error_reply", l.NewFunction(luaErrorReply))
l.SetField(mt, "status_reply", l.NewFunction(luaStatusReply))
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
func setMapState(l *lua.LState, s *script) {
2014-09-02 13:55:12 +04:00
stateLock.Lock()
defer stateLock.Unlock()
mapState[l] = s
}
2017-04-15 16:51:03 +03:00
func getMapState(l *lua.LState) *script {
2014-09-02 13:55:12 +04:00
stateLock.Lock()
defer stateLock.Unlock()
return mapState[l]
}
2017-04-15 16:51:03 +03:00
func delMapState(l *lua.LState) {
2014-09-02 13:55:12 +04:00
stateLock.Lock()
defer stateLock.Unlock()
delete(mapState, l)
}
2017-04-15 16:51:03 +03:00
func luaErrorHandler(l *lua.LState) int {
msg := l.ToString(1)
2017-04-15 16:51:03 +03:00
panic(errors.New(msg))
}
2017-04-15 16:51:03 +03:00
func luaCall(l *lua.LState) int {
2014-09-02 13:55:12 +04:00
return luaCallGenericCommand(l)
}
2017-04-15 16:51:03 +03:00
func luaPCall(l *lua.LState) (n int) {
2014-09-02 13:55:12 +04:00
defer func() {
if e := recover(); e != nil {
luaPushError(l, fmt.Sprintf("%v", e))
n = 1
}
return
}()
return luaCallGenericCommand(l)
}
2017-04-15 16:51:03 +03:00
func luaErrorReply(l *lua.LState) int {
2014-09-02 13:55:12 +04:00
return luaReturnSingleFieldTable(l, "err")
}
2017-04-15 16:51:03 +03:00
func luaStatusReply(l *lua.LState) int {
2014-09-02 13:55:12 +04:00
return luaReturnSingleFieldTable(l, "ok")
}
2017-04-15 16:51:03 +03:00
func luaReturnSingleFieldTable(l *lua.LState, filed string) int {
if l.GetTop() != 1 || l.Get(-1).Type() != lua.LTString {
2014-09-02 13:55:12 +04:00
luaPushError(l, "wrong number or type of arguments")
return 1
}
2017-04-15 16:51:03 +03:00
table := l.NewTable()
table.Append(lua.LString(filed))
l.Push(table)
2014-09-02 13:55:12 +04:00
return 1
}
2017-04-15 16:51:03 +03:00
func luaSha1Hex(l *lua.LState) int {
if argc := l.GetTop(); argc != 1 {
2014-09-02 13:55:12 +04:00
luaPushError(l, "wrong number of arguments")
return 1
}
s := l.ToString(1)
2014-09-24 08:34:21 +04:00
s = hex.EncodeToString(hack.Slice(s))
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
l.Push(lua.LString(s))
2014-09-02 13:55:12 +04:00
return 1
}
2017-04-15 16:51:03 +03:00
func luaPushError(l *lua.LState, msg string) {
table := l.NewTable()
table.Append(lua.LString("err"))
table.Append(lua.LString(msg))
l.Push(table)
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
func luaCallGenericCommand(l *lua.LState) int {
2014-09-02 13:55:12 +04:00
s := getMapState(l)
if s == nil {
panic("Invalid lua call")
} else if s.c.db == nil {
panic("Invalid lua call, not prepared")
}
c := s.c
argc := l.GetTop()
if argc < 1 {
panic("Please specify at least one argument for ledis.call()")
}
c.cmd = l.ToString(1)
c.args = make([][]byte, argc-1)
for i := 2; i <= argc; i++ {
2017-04-15 16:51:03 +03:00
switch l.Get(i).Type() {
case lua.LTNumber:
2014-09-02 13:55:12 +04:00
c.args[i-2] = []byte(fmt.Sprintf("%.17g", l.ToNumber(i)))
2017-04-15 16:51:03 +03:00
case lua.LTString:
2014-09-02 13:55:12 +04:00
c.args[i-2] = []byte(l.ToString(i))
default:
panic("Lua ledis() command arguments must be strings or integers")
}
}
c.perform()
return 1
}
2017-04-15 16:51:03 +03:00
func luaSetGlobalArray(l *lua.LState, name string, ay [][]byte) {
table := l.NewTable()
2014-09-02 13:55:12 +04:00
for i := 0; i < len(ay); i++ {
2017-04-15 16:51:03 +03:00
table.Append(lua.LString(hack.String(ay[i])))
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
l.SetGlobal(name, table)
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
func luaReplyToLedisReply(l *lua.LState) interface{} {
return luaValueToLedisValue(l.Get(-1))
}
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
func luaValueToLedisValue(v lua.LValue) interface{} {
switch top := v.(type) {
case lua.LString:
return hack.Slice(top.String())
case lua.LBool:
if top == lua.LTrue {
2014-09-02 13:55:12 +04:00
return int64(1)
}
2017-04-15 16:51:03 +03:00
return nil
case lua.LNumber:
return int64(top)
case *lua.LTable:
// flatten all key, values, for easier access later
flatTable := make([]lua.LValue, 0)
var err error
top.ForEach(func(key, value lua.LValue) {
if err != nil {
return
}
if key.Type() == lua.LTString {
err = fmt.Errorf("only array-tables are supported: %q", top.String())
return
}
flatTable = append(flatTable, key, value)
})
if err != nil {
return err
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
length := len(flatTable)
if length == 0 {
return nil
}
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
if length <= 4 {
// ok => status Reply
// err => error Reply
if flatTable[1].Type() == lua.LTString {
switch strings.ToLower(flatTable[1].String()) {
case "ok":
if length == 4 {
return flatTable[3].String()
}
return "ok"
case "err":
if length == 4 {
return errors.New(flatTable[3].String())
}
return errors.New("err")
default:
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
}
}
2014-09-02 13:55:12 +04:00
2017-04-15 16:51:03 +03:00
ay := make([]interface{}, 0)
for i := 0; i < length; i += 2 {
// cut at first nil value
value := flatTable[i+1]
if value.Type() == lua.LTNil {
break
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
ay = append(ay, luaValueToLedisValue(value))
2014-09-02 13:55:12 +04:00
}
2017-04-15 16:51:03 +03:00
return ay
2014-09-02 13:55:12 +04:00
default:
return nil
}
}