funcs_misc.go 19 KB

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