funcs_misc.go 20 KB

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