funcs_misc.go 16 KB

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