funcs_misc.go 19 KB

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