funcs_misc.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright 2022-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package function
  15. import (
  16. "crypto/md5"
  17. "crypto/sha1"
  18. "crypto/sha256"
  19. "crypto/sha512"
  20. b64 "encoding/base64"
  21. "encoding/json"
  22. "fmt"
  23. "io"
  24. "math"
  25. "reflect"
  26. "strconv"
  27. "strings"
  28. "time"
  29. "github.com/google/uuid"
  30. "github.com/lf-edge/ekuiper/internal/conf"
  31. "github.com/lf-edge/ekuiper/internal/keyedstate"
  32. "github.com/lf-edge/ekuiper/pkg/api"
  33. "github.com/lf-edge/ekuiper/pkg/ast"
  34. "github.com/lf-edge/ekuiper/pkg/cast"
  35. )
  36. func registerMiscFunc() {
  37. builtins["cast"] = builtinFunc{
  38. fType: ast.FuncTypeScalar,
  39. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  40. value := args[0]
  41. newType := args[1]
  42. return cast.ToType(value, newType)
  43. },
  44. val: func(_ api.FunctionContext, args []ast.Expr) error {
  45. if err := ValidateLen(2, len(args)); err != nil {
  46. return err
  47. }
  48. a := args[1]
  49. if ast.IsNumericArg(a) || ast.IsTimeArg(a) || ast.IsBooleanArg(a) {
  50. return ProduceErrInfo(0, "string")
  51. }
  52. if av, ok := a.(*ast.StringLiteral); ok {
  53. if !(av.Val == "bigint" || av.Val == "float" || av.Val == "string" || av.Val == "boolean" || av.Val == "datetime") {
  54. return fmt.Errorf("Expect one of following value for the 2nd parameter: bigint, float, string, boolean, datetime.")
  55. }
  56. }
  57. return nil
  58. },
  59. check: returnNilIfHasAnyNil,
  60. }
  61. builtins["convert_tz"] = builtinFunc{
  62. fType: ast.FuncTypeScalar,
  63. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  64. arg0, err := cast.InterfaceToTime(args[0], "")
  65. if err != nil {
  66. return err, false
  67. }
  68. arg1 := cast.ToStringAlways(args[1])
  69. loc, err := time.LoadLocation(arg1)
  70. if err != nil {
  71. return err, false
  72. }
  73. return arg0.In(loc), true
  74. },
  75. val: func(_ api.FunctionContext, args []ast.Expr) error {
  76. if err := ValidateLen(2, len(args)); err != nil {
  77. return err
  78. }
  79. if ast.IsNumericArg(args[0]) || ast.IsStringArg(args[0]) || ast.IsBooleanArg(args[0]) {
  80. return ProduceErrInfo(0, "datetime")
  81. }
  82. if ast.IsNumericArg(args[1]) || ast.IsTimeArg(args[1]) || ast.IsBooleanArg(args[1]) {
  83. return ProduceErrInfo(1, "string")
  84. }
  85. return nil
  86. },
  87. check: returnNilIfHasAnyNil,
  88. }
  89. builtins["to_seconds"] = builtinFunc{
  90. fType: ast.FuncTypeScalar,
  91. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  92. t, err := cast.InterfaceToTime(args[0], "")
  93. if err != nil {
  94. return err, false
  95. }
  96. return t.Unix(), true
  97. },
  98. val: ValidateOneArg,
  99. check: returnNilIfHasAnyNil,
  100. }
  101. builtins["to_json"] = builtinFunc{
  102. fType: ast.FuncTypeScalar,
  103. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  104. rr, err := json.Marshal(args[0])
  105. if err != nil {
  106. return fmt.Errorf("fail to convert %v to json", args[0]), false
  107. }
  108. return string(rr), true
  109. },
  110. val: ValidateOneArg,
  111. check: returnNilIfHasAnyNil,
  112. }
  113. builtins["parse_json"] = builtinFunc{
  114. fType: ast.FuncTypeScalar,
  115. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  116. if args[0] == nil || args[0] == "null" {
  117. return nil, true
  118. }
  119. text, err := cast.ToString(args[0], cast.CONVERT_SAMEKIND)
  120. if err != nil {
  121. return fmt.Errorf("fail to convert %v to string", args[0]), false
  122. }
  123. var data interface{}
  124. err = json.Unmarshal(cast.StringToBytes(text), &data)
  125. if err != nil {
  126. return fmt.Errorf("fail to parse json: %v", err), false
  127. }
  128. return data, true
  129. },
  130. val: ValidateOneStrArg,
  131. }
  132. builtins["chr"] = builtinFunc{
  133. fType: ast.FuncTypeScalar,
  134. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  135. if v, ok := args[0].(int); ok {
  136. return rune(v), true
  137. } else if v, ok := args[0].(float64); ok {
  138. temp := int(v)
  139. return rune(temp), true
  140. } else if v, ok := args[0].(string); ok {
  141. if len(v) > 1 {
  142. return fmt.Errorf("Parameter length cannot larger than 1."), false
  143. }
  144. r := []rune(v)
  145. return r[0], true
  146. } else {
  147. return fmt.Errorf("Only bigint, float and string type can be convert to char type."), false
  148. }
  149. },
  150. val: func(_ api.FunctionContext, args []ast.Expr) error {
  151. if err := ValidateLen(1, len(args)); err != nil {
  152. return err
  153. }
  154. if ast.IsFloatArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  155. return ProduceErrInfo(0, "int")
  156. }
  157. return nil
  158. },
  159. check: returnNilIfHasAnyNil,
  160. }
  161. builtins["encode"] = builtinFunc{
  162. fType: ast.FuncTypeScalar,
  163. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  164. if v, ok := args[1].(string); ok {
  165. if strings.EqualFold(v, "base64") {
  166. if v1, ok1 := args[0].(string); ok1 {
  167. return b64.StdEncoding.EncodeToString([]byte(v1)), true
  168. } else {
  169. return fmt.Errorf("Only string type can be encoded."), false
  170. }
  171. } else {
  172. return fmt.Errorf("Only base64 encoding is supported."), false
  173. }
  174. }
  175. return nil, false
  176. },
  177. val: func(_ api.FunctionContext, args []ast.Expr) error {
  178. if err := ValidateLen(2, len(args)); err != nil {
  179. return err
  180. }
  181. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  182. return ProduceErrInfo(0, "string")
  183. }
  184. a := args[1]
  185. if !ast.IsStringArg(a) {
  186. return ProduceErrInfo(1, "string")
  187. }
  188. if av, ok := a.(*ast.StringLiteral); ok {
  189. if av.Val != "base64" {
  190. return fmt.Errorf("Only base64 is supported for the 2nd parameter.")
  191. }
  192. }
  193. return nil
  194. },
  195. check: returnNilIfHasAnyNil,
  196. }
  197. builtins["decode"] = builtinFunc{
  198. fType: ast.FuncTypeScalar,
  199. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  200. if v, ok := args[1].(string); ok {
  201. if strings.EqualFold(v, "base64") {
  202. if v1, ok1 := args[0].(string); ok1 {
  203. r, e := b64.StdEncoding.DecodeString(v1)
  204. if e != nil {
  205. return fmt.Errorf("fail to decode base64 string: %v", e), false
  206. }
  207. return r, true
  208. } else {
  209. return fmt.Errorf("Only string type can be decoded."), false
  210. }
  211. } else {
  212. return fmt.Errorf("Only base64 decoding is supported."), false
  213. }
  214. }
  215. return nil, false
  216. },
  217. val: func(_ api.FunctionContext, args []ast.Expr) error {
  218. if err := ValidateLen(2, len(args)); err != nil {
  219. return err
  220. }
  221. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  222. return ProduceErrInfo(0, "string")
  223. }
  224. a := args[1]
  225. if !ast.IsStringArg(a) {
  226. return ProduceErrInfo(1, "string")
  227. }
  228. if av, ok := a.(*ast.StringLiteral); ok {
  229. if av.Val != "base64" {
  230. return fmt.Errorf("Only base64 is supported for the 2nd parameter.")
  231. }
  232. }
  233. return nil
  234. },
  235. check: returnNilIfHasAnyNil,
  236. }
  237. builtins["trunc"] = builtinFunc{
  238. fType: ast.FuncTypeScalar,
  239. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  240. var v0 float64
  241. if v1, ok := args[0].(int); ok {
  242. v0 = float64(v1)
  243. } else if v1, ok := args[0].(float64); ok {
  244. v0 = v1
  245. } else {
  246. return fmt.Errorf("Only int and float type can be truncated."), false
  247. }
  248. if v2, ok := args[1].(int); ok {
  249. return toFixed(v0, v2), true
  250. } else {
  251. return fmt.Errorf("The 2nd parameter must be int value."), false
  252. }
  253. },
  254. val: func(_ api.FunctionContext, args []ast.Expr) error {
  255. if err := ValidateLen(2, len(args)); err != nil {
  256. return err
  257. }
  258. if ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) || ast.IsStringArg(args[0]) {
  259. return ProduceErrInfo(0, "number - float or int")
  260. }
  261. if ast.IsFloatArg(args[1]) || ast.IsTimeArg(args[1]) || ast.IsBooleanArg(args[1]) || ast.IsStringArg(args[1]) {
  262. return ProduceErrInfo(1, "int")
  263. }
  264. return nil
  265. },
  266. check: returnNilIfHasAnyNil,
  267. }
  268. builtins["md5"] = builtinFunc{
  269. fType: ast.FuncTypeScalar,
  270. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  271. arg0 := cast.ToStringAlways(args[0])
  272. h := md5.New()
  273. _, err := io.WriteString(h, arg0)
  274. if err != nil {
  275. return err, false
  276. }
  277. return fmt.Sprintf("%x", h.Sum(nil)), true
  278. },
  279. val: ValidateOneStrArg,
  280. check: returnNilIfHasAnyNil,
  281. }
  282. builtins["sha1"] = builtinFunc{
  283. fType: ast.FuncTypeScalar,
  284. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  285. arg0 := cast.ToStringAlways(args[0])
  286. h := sha1.New()
  287. _, err := io.WriteString(h, arg0)
  288. if err != nil {
  289. return err, false
  290. }
  291. return fmt.Sprintf("%x", h.Sum(nil)), true
  292. },
  293. val: ValidateOneStrArg,
  294. check: returnNilIfHasAnyNil,
  295. }
  296. builtins["sha256"] = builtinFunc{
  297. fType: ast.FuncTypeScalar,
  298. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  299. arg0 := cast.ToStringAlways(args[0])
  300. h := sha256.New()
  301. _, err := io.WriteString(h, arg0)
  302. if err != nil {
  303. return err, false
  304. }
  305. return fmt.Sprintf("%x", h.Sum(nil)), true
  306. },
  307. val: ValidateOneStrArg,
  308. check: returnNilIfHasAnyNil,
  309. }
  310. builtins["sha384"] = builtinFunc{
  311. fType: ast.FuncTypeScalar,
  312. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  313. arg0 := cast.ToStringAlways(args[0])
  314. h := sha512.New384()
  315. _, err := io.WriteString(h, arg0)
  316. if err != nil {
  317. return err, false
  318. }
  319. return fmt.Sprintf("%x", h.Sum(nil)), true
  320. },
  321. val: ValidateOneStrArg,
  322. check: returnNilIfHasAnyNil,
  323. }
  324. builtins["sha512"] = builtinFunc{
  325. fType: ast.FuncTypeScalar,
  326. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  327. arg0 := cast.ToStringAlways(args[0])
  328. h := sha512.New()
  329. _, err := io.WriteString(h, arg0)
  330. if err != nil {
  331. return err, false
  332. }
  333. return fmt.Sprintf("%x", h.Sum(nil)), true
  334. },
  335. val: ValidateOneStrArg,
  336. check: returnNilIfHasAnyNil,
  337. }
  338. builtinStatfulFuncs["compress"] = func() api.Function {
  339. conf.Log.Infof("initializing compress function")
  340. return &compressFunc{}
  341. }
  342. builtinStatfulFuncs["decompress"] = func() api.Function {
  343. conf.Log.Infof("initializing decompress function")
  344. return &decompressFunc{}
  345. }
  346. builtins["isnull"] = builtinFunc{
  347. fType: ast.FuncTypeScalar,
  348. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  349. if args[0] == nil {
  350. return true, true
  351. } else {
  352. v := reflect.ValueOf(args[0])
  353. switch v.Kind() {
  354. case reflect.Slice, reflect.Map:
  355. return v.IsNil(), true
  356. default:
  357. return false, true
  358. }
  359. }
  360. },
  361. val: ValidateOneArg,
  362. }
  363. builtins["coalesce"] = builtinFunc{
  364. fType: ast.FuncTypeScalar,
  365. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  366. for _, arg := range args {
  367. if arg != nil {
  368. return arg, true
  369. }
  370. }
  371. return nil, true
  372. },
  373. val: func(_ api.FunctionContext, args []ast.Expr) error {
  374. if len(args) == 0 {
  375. return fmt.Errorf("The arguments should be at least one.")
  376. }
  377. return nil
  378. },
  379. }
  380. builtins["newuuid"] = builtinFunc{
  381. fType: ast.FuncTypeScalar,
  382. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  383. if newUUID, err := uuid.NewUUID(); err != nil {
  384. return err, false
  385. } else {
  386. return newUUID.String(), true
  387. }
  388. },
  389. val: ValidateNoArg,
  390. }
  391. builtins["tstamp"] = builtinFunc{
  392. fType: ast.FuncTypeScalar,
  393. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  394. return conf.GetNowInMilli(), true
  395. },
  396. val: ValidateNoArg,
  397. }
  398. builtins["mqtt"] = builtinFunc{
  399. fType: ast.FuncTypeScalar,
  400. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  401. if v, ok := args[0].(string); ok {
  402. return v, true
  403. }
  404. return nil, false
  405. },
  406. val: func(_ api.FunctionContext, args []ast.Expr) error {
  407. if err := ValidateLen(1, len(args)); err != nil {
  408. return err
  409. }
  410. if ast.IsIntegerArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) || ast.IsStringArg(args[0]) || ast.IsFloatArg(args[0]) {
  411. return ProduceErrInfo(0, "meta reference")
  412. }
  413. if p, ok := args[0].(*ast.MetaRef); ok {
  414. name := strings.ToLower(p.Name)
  415. if name != "topic" && name != "messageid" {
  416. return fmt.Errorf("Parameter of mqtt function can be only topic or messageid.")
  417. }
  418. }
  419. return nil
  420. },
  421. check: returnNilIfHasAnyNil,
  422. }
  423. builtins["rule_id"] = builtinFunc{
  424. fType: ast.FuncTypeScalar,
  425. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  426. return ctx.GetRuleId(), true
  427. },
  428. val: ValidateNoArg,
  429. }
  430. builtins["meta"] = builtinFunc{
  431. fType: ast.FuncTypeScalar,
  432. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  433. return args[0], true
  434. },
  435. val: func(_ api.FunctionContext, args []ast.Expr) error {
  436. if err := ValidateLen(1, len(args)); err != nil {
  437. return err
  438. }
  439. if _, ok := args[0].(*ast.MetaRef); ok {
  440. return nil
  441. }
  442. expr := args[0]
  443. for {
  444. if be, ok := expr.(*ast.BinaryExpr); ok {
  445. if _, ok := be.LHS.(*ast.MetaRef); ok && be.OP == ast.ARROW {
  446. return nil
  447. }
  448. expr = be.LHS
  449. } else {
  450. break
  451. }
  452. }
  453. return ProduceErrInfo(0, "meta reference")
  454. },
  455. }
  456. builtins["cardinality"] = builtinFunc{
  457. fType: ast.FuncTypeScalar,
  458. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  459. val := reflect.ValueOf(args[0])
  460. if val.Kind() == reflect.Slice {
  461. return val.Len(), true
  462. }
  463. return 0, true
  464. },
  465. val: ValidateOneArg,
  466. check: return0IfHasAnyNil,
  467. }
  468. builtins["json_path_query"] = builtinFunc{
  469. fType: ast.FuncTypeScalar,
  470. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  471. result, err := jsonCall(ctx, args)
  472. if err != nil {
  473. return err, false
  474. }
  475. return result, true
  476. },
  477. val: ValidateJsonFunc,
  478. }
  479. builtins["json_path_query_first"] = builtinFunc{
  480. fType: ast.FuncTypeScalar,
  481. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  482. result, err := jsonCall(ctx, args)
  483. if err != nil {
  484. return err, false
  485. }
  486. if arr, ok := result.([]interface{}); ok {
  487. return arr[0], true
  488. } else {
  489. return fmt.Errorf("query result (%v) is not an array", result), false
  490. }
  491. },
  492. val: ValidateJsonFunc,
  493. }
  494. builtins["json_path_exists"] = builtinFunc{
  495. fType: ast.FuncTypeScalar,
  496. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  497. result, err := jsonCall(ctx, args)
  498. if err != nil {
  499. return false, true
  500. }
  501. if result == nil {
  502. return false, true
  503. }
  504. e := true
  505. switch reflect.TypeOf(result).Kind() {
  506. case reflect.Slice, reflect.Array:
  507. e = reflect.ValueOf(result).Len() > 0
  508. default:
  509. e = result != nil
  510. }
  511. return e, true
  512. },
  513. val: ValidateJsonFunc,
  514. }
  515. builtins["window_start"] = builtinFunc{
  516. fType: ast.FuncTypeScalar,
  517. exec: nil, // directly return in the valuer
  518. val: ValidateNoArg,
  519. }
  520. builtins["window_end"] = builtinFunc{
  521. fType: ast.FuncTypeScalar,
  522. exec: nil, // directly return in the valuer
  523. val: ValidateNoArg,
  524. }
  525. builtins["event_time"] = builtinFunc{
  526. fType: ast.FuncTypeScalar,
  527. exec: nil, // directly return in the valuer
  528. val: ValidateNoArg,
  529. }
  530. builtins["object_construct"] = builtinFunc{
  531. fType: ast.FuncTypeScalar,
  532. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  533. result := make(map[string]interface{})
  534. for i := 0; i < len(args); i += 2 {
  535. if args[i+1] != nil {
  536. s, err := cast.ToString(args[i], cast.CONVERT_SAMEKIND)
  537. if err != nil {
  538. return fmt.Errorf("key %v is not a string", args[i]), false
  539. }
  540. result[s] = args[i+1]
  541. }
  542. }
  543. return result, true
  544. },
  545. val: func(_ api.FunctionContext, args []ast.Expr) error {
  546. if len(args)%2 != 0 {
  547. return fmt.Errorf("the args must be key value pairs")
  548. }
  549. for i, arg := range args {
  550. if i%2 == 0 {
  551. if ast.IsNumericArg(arg) || ast.IsTimeArg(arg) || ast.IsBooleanArg(arg) {
  552. return ProduceErrInfo(i, "string")
  553. }
  554. }
  555. }
  556. return nil
  557. },
  558. check: returnNilIfHasAnyNil,
  559. }
  560. builtins["delay"] = builtinFunc{
  561. fType: ast.FuncTypeScalar,
  562. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  563. d, err := cast.ToInt(args[0], cast.CONVERT_SAMEKIND)
  564. if err != nil {
  565. return err, false
  566. }
  567. time.Sleep(time.Duration(d) * time.Millisecond)
  568. return args[1], true
  569. },
  570. val: func(_ api.FunctionContext, args []ast.Expr) error {
  571. if err := ValidateLen(2, len(args)); err != nil {
  572. return err
  573. }
  574. if ast.IsStringArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsBooleanArg(args[0]) {
  575. return ProduceErrInfo(0, "number - float or int")
  576. }
  577. return nil
  578. },
  579. check: returnNilIfHasAnyNil,
  580. }
  581. builtins["get_keyed_state"] = builtinFunc{
  582. fType: ast.FuncTypeScalar,
  583. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  584. if len(args) != 3 {
  585. return fmt.Errorf("the args must be two or three"), false
  586. }
  587. key, ok := args[0].(string)
  588. if !ok {
  589. return fmt.Errorf("key %v is not a string", args[0]), false
  590. }
  591. value, err := keyedstate.GetKeyedState(key)
  592. if err != nil {
  593. return args[2], true
  594. }
  595. return cast.ToType(value, args[1])
  596. },
  597. val: func(_ api.FunctionContext, args []ast.Expr) error {
  598. if err := ValidateLen(3, len(args)); err != nil {
  599. return err
  600. }
  601. a := args[1]
  602. if ast.IsNumericArg(a) || ast.IsTimeArg(a) || ast.IsBooleanArg(a) {
  603. return ProduceErrInfo(0, "string")
  604. }
  605. if av, ok := a.(*ast.StringLiteral); ok {
  606. if !(av.Val == "bigint" || av.Val == "float" || av.Val == "string" || av.Val == "boolean" || av.Val == "datetime") {
  607. return fmt.Errorf("expect one of following value for the 2nd parameter: bigint, float, string, boolean, datetime")
  608. }
  609. }
  610. return nil
  611. },
  612. check: returnNilIfHasAnyNil,
  613. }
  614. builtins["hex2dec"] = builtinFunc{
  615. fType: ast.FuncTypeScalar,
  616. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  617. hex, ok := args[0].(string)
  618. if !ok {
  619. return fmt.Errorf("invalid input type: %v please input hex string", args[0]), false
  620. }
  621. hex = strings.TrimPrefix(hex, "0x")
  622. dec, err := strconv.ParseInt(hex, 16, 64)
  623. if err != nil {
  624. return fmt.Errorf("invalid hexadecimal value: %v", hex), false
  625. }
  626. return dec, true
  627. },
  628. val: ValidateOneStrArg,
  629. check: returnNilIfHasAnyNil,
  630. }
  631. builtins["dec2hex"] = builtinFunc{
  632. fType: ast.FuncTypeScalar,
  633. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  634. dec, err := cast.ToInt(args[0], cast.STRICT)
  635. if err != nil {
  636. return err, false
  637. }
  638. hex := "0x" + strconv.FormatInt(int64(dec), 16)
  639. return hex, true
  640. },
  641. val: ValidateOneStrArg,
  642. check: returnNilIfHasAnyNil,
  643. }
  644. }
  645. func round(num float64) int {
  646. return int(num + math.Copysign(0.5, num))
  647. }
  648. func toFixed(num float64, precision int) float64 {
  649. output := math.Pow(10, float64(precision))
  650. return float64(round(num*output)) / output
  651. }
  652. func jsonCall(ctx api.StreamContext, args []interface{}) (interface{}, error) {
  653. jp, ok := args[1].(string)
  654. if !ok {
  655. return nil, fmt.Errorf("invalid jsonPath, must be a string but got %v", args[1])
  656. }
  657. return ctx.ParseJsonPath(jp, args[0])
  658. }
  659. // page Rotate storage for in memory cache
  660. // Not thread safe!
  661. type ringqueue struct {
  662. data []interface{}
  663. h int
  664. t int
  665. l int
  666. size int
  667. }
  668. func newRingqueue(size int) *ringqueue {
  669. return &ringqueue{
  670. data: make([]interface{}, size),
  671. h: 0, // When deleting, head++, if tail == head, it is empty
  672. t: 0, // When append, tail++, if tail== head, it is full
  673. size: size,
  674. }
  675. }
  676. // fill item will fill the queue with item value
  677. func (p *ringqueue) fill(item interface{}) {
  678. for {
  679. if !p.append(item) {
  680. return
  681. }
  682. }
  683. }
  684. // append item if list is not full and return true; otherwise return false
  685. func (p *ringqueue) append(item interface{}) bool {
  686. if p.l == p.size { // full
  687. return false
  688. }
  689. p.data[p.t] = item
  690. p.t++
  691. if p.t == p.size {
  692. p.t = 0
  693. }
  694. p.l++
  695. return true
  696. }
  697. // fetch get the first item in the cache and remove
  698. func (p *ringqueue) fetch() (interface{}, bool) {
  699. if p.l == 0 {
  700. return nil, false
  701. }
  702. result := p.data[p.h]
  703. p.h++
  704. if p.h == p.size {
  705. p.h = 0
  706. }
  707. p.l--
  708. return result, true
  709. }
  710. // peek get the first item in the cache but keep it
  711. func (p *ringqueue) peek() (interface{}, bool) {
  712. if p.l == 0 {
  713. return nil, false
  714. }
  715. result := p.data[p.h]
  716. return result, true
  717. }
  718. func (p *ringqueue) isFull() bool {
  719. return p.l == p.size
  720. }