funcs_misc.go 17 KB

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