From cd74dda723b011407ed12d09c472156fc438f1a5 Mon Sep 17 00:00:00 2001 From: Alexander Yastrebov Date: Fri, 5 Apr 2024 18:24:08 +0200 Subject: [PATCH] script: allow storing lua tables into state bag (#3005) Signed-off-by: Alexander Yastrebov --- docs/reference/scripts.md | 4 ++-- script/script.go | 4 ++++ script/script_test.go | 18 +++++++++++------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/reference/scripts.md b/docs/reference/scripts.md index 7ad16be06c..2e5b7d09b8 100644 --- a/docs/reference/scripts.md +++ b/docs/reference/scripts.md @@ -180,8 +180,8 @@ Path("/api/:id") -> lua("function request(ctx, params); print(ctx.path_param.id) ## StateBag -The state bag can be used to pass values from one filter to another in the same -chain. It is shared by all filters in one request. +The state bag can be used to pass string, number and table values from one filter to another in the same +chain. It is shared by all filters in one request (lua table values are only available to lua filters). ```lua function request(ctx, params) -- the value of "mykey" will be available to all filters in the chain now: diff --git a/script/script.go b/script/script.go index b9e272bd9b..7aac13ff07 100644 --- a/script/script.go +++ b/script/script.go @@ -609,6 +609,8 @@ func getStateBag(f filters.FilterContext) func(*lua.LState) int { s.Push(lua.LNumber(res)) case float64: s.Push(lua.LNumber(res)) + case *lua.LTable: + s.Push(res) // load *lua.LTable as is default: return 0 } @@ -626,6 +628,8 @@ func setStateBag(f filters.FilterContext) func(*lua.LState) int { res = string(val.(lua.LString)) case lua.LTNumber: res = float64(val.(lua.LNumber)) + case lua.LTTable: + res = val // store *lua.LTable as is default: // TODO(sszuecs): https://github.com/zalando/skipper/issues/1487 // s.RaiseError("unsupported state bag value type %v, need a string or a number", val.Type()) diff --git a/script/script_test.go b/script/script_test.go index eb01664bad..b946f0c090 100644 --- a/script/script_test.go +++ b/script/script_test.go @@ -822,18 +822,22 @@ func ExampleGetMissingStateBag() { // nil } -const SetUnsupportedStateBag = ` +const SetStateBagTable = ` function request(ctx, params) - ctx.state_bag.unsupported = {} - print("ok") -end` + ctx.state_bag.table = {foo="bar"} +end + +function response(ctx, params) + print(ctx.state_bag.table.foo) +end +` -func ExampleSetUnsupportedStateBag() { +func ExampleSetStateBagTable() { runExample(&testContext{ - script: SetUnsupportedStateBag, + script: SetStateBagTable, }) // Output: - // ok + // bar } func newFilter(opts LuaOptions, script string, params ...string) (filters.Filter, error) {