From 715200104485d9c91fd84cd3264aecf54b805998 Mon Sep 17 00:00:00 2001 From: AndrewZuo01 Date: Tue, 26 Dec 2023 10:38:10 +0800 Subject: [PATCH 1/2] update component check --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 71ae189ec..f2860a880 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,7 @@ require ( require ( github.com/OpenIMSDK/protocol v0.0.21 - github.com/OpenIMSDK/tools v0.0.17 + github.com/OpenIMSDK/tools v0.0.22 github.com/go-zookeeper/zk v1.0.3 github.com/redis/go-redis/v9 v9.1.0 gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df diff --git a/go.sum b/go.sum index 8d33b2e79..02cc5bfa8 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ github.com/OpenIMSDK/open_utils v1.0.8 h1:IopxWgJwEF5ZAPsRuiZZOfcxNOQOCt/p8VDENc github.com/OpenIMSDK/open_utils v1.0.8/go.mod h1:FLoaQblWUVKQgqt2LrNzfSZLT6D3DICBn1kcOMDLUOI= github.com/OpenIMSDK/protocol v0.0.21 h1:5H6H+hJ9d/VgRqttvxD/zfK9Asd+4M8Eknk5swSbUVY= github.com/OpenIMSDK/protocol v0.0.21/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y= -github.com/OpenIMSDK/tools v0.0.17 h1:1E1HUOL2W09YUHBb4wBwrXoTSZm5ONVwLxlEX1GhlKw= -github.com/OpenIMSDK/tools v0.0.17/go.mod h1:eg+q4A34Qmu73xkY0mt37FHGMCMfC6CtmOnm0kFEGFI= +github.com/OpenIMSDK/tools v0.0.22 h1:gjcqA+lWjvF2NRX9R4c9gLfFOI/bwVctT14bs1U3HpU= +github.com/OpenIMSDK/tools v0.0.22/go.mod h1:eg+q4A34Qmu73xkY0mt37FHGMCMfC6CtmOnm0kFEGFI= github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 h1:iC9YFYKDGEy3n/FtqJnOkZsene9olVspKmkX5A2YBEo= github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4/go.mod h1:sCavSAvdzOjul4cEqeVtvlSaSScfNsTQ+46HwlTL1hc= github.com/alibabacloud-go/darabonba-openapi v0.1.18/go.mod h1:PB4HffMhJVmAgNKNq3wYbTUlFvPgxJpTzd1F5pTuUsc= From cdd2c57c2b5c3fd357bfc7527e64f73eb34d1a3a Mon Sep 17 00:00:00 2001 From: AndrewZuo01 Date: Tue, 26 Dec 2023 10:41:05 +0800 Subject: [PATCH 2/2] update component check --- go.sum | 34 +- zktools/.gitignore | 22 - zktools/LICENSE | 201 ------ zktools/README.md | 1 - zktools/a2r/api2rpc.go | 51 -- zktools/apiresp/format.go | 19 - zktools/apiresp/gin.go | 29 - zktools/apiresp/http.go | 39 -- zktools/apiresp/resp.go | 76 --- zktools/checker/check.go | 33 - .../discoveryregistry/discovery_register.go | 42 -- zktools/discoveryregistry/zookeeper/conf.go | 41 -- .../discoveryregistry/zookeeper/discover.go | 153 ----- .../discoveryregistry/zookeeper/register.go | 76 --- .../discoveryregistry/zookeeper/resolver.go | 87 --- zktools/discoveryregistry/zookeeper/zk.go | 238 ------- zktools/errs/code.go | 92 --- zktools/errs/coderr.go | 129 ---- zktools/errs/predefine.go | 64 -- zktools/errs/relation.go | 56 -- zktools/go.mod | 78 --- zktools/go.sum | 208 ------ zktools/log/color.go | 64 -- zktools/log/logger.go | 27 - zktools/log/sql_logger.go | 89 --- zktools/log/zap.go | 304 --------- zktools/log/zk_logger.go | 30 - zktools/mcontext/ctx.go | 154 ----- zktools/mgoutil/mongo.go | 168 ----- zktools/mw/gin.go | 74 --- zktools/mw/intercept_chain.go | 41 -- zktools/mw/rpc_client_interceptor.go | 114 ---- zktools/mw/rpc_server_interceptor.go | 177 ----- zktools/mw/specialerror/error.go | 47 -- zktools/network/ip.go | 41 -- zktools/ormutil/utils.go | 71 -- zktools/pagination/pagination.go | 6 - zktools/prome/gather.go | 470 -------------- zktools/prome/prometheus.go | 96 --- zktools/tokenverify/jwt_token.go | 68 -- zktools/tokenverify/jwt_token_test.go | 45 -- zktools/tx/gorm.go | 33 - zktools/tx/mongo.go | 83 --- zktools/tx/tx.go | 25 - zktools/utils/base64.go | 26 - zktools/utils/encryption.go | 78 --- zktools/utils/file.go | 92 --- zktools/utils/get_server_ip.go | 39 -- zktools/utils/id.go | 42 -- zktools/utils/id_test.go | 29 - zktools/utils/image.go | 69 -- zktools/utils/image_test.go | 41 -- zktools/utils/map.go | 147 ----- zktools/utils/md5_test.go | 29 - .../utils/platform_number_id_to_name_test.go | 61 -- zktools/utils/retry/retry.go | 198 ------ zktools/utils/retry/stratey.go | 70 -- zktools/utils/splitter/tools.go | 42 -- zktools/utils/strings.go | 141 ---- zktools/utils/time_format.go | 97 --- zktools/utils/utils.go | 209 ------ zktools/utils/utils_v2.go | 604 ------------------ zktools/utils/utils_v2_test.go | 283 -------- 63 files changed, 24 insertions(+), 6269 deletions(-) delete mode 100644 zktools/.gitignore delete mode 100644 zktools/LICENSE delete mode 100644 zktools/README.md delete mode 100644 zktools/a2r/api2rpc.go delete mode 100644 zktools/apiresp/format.go delete mode 100644 zktools/apiresp/gin.go delete mode 100644 zktools/apiresp/http.go delete mode 100644 zktools/apiresp/resp.go delete mode 100644 zktools/checker/check.go delete mode 100644 zktools/discoveryregistry/discovery_register.go delete mode 100644 zktools/discoveryregistry/zookeeper/conf.go delete mode 100644 zktools/discoveryregistry/zookeeper/discover.go delete mode 100644 zktools/discoveryregistry/zookeeper/register.go delete mode 100644 zktools/discoveryregistry/zookeeper/resolver.go delete mode 100644 zktools/discoveryregistry/zookeeper/zk.go delete mode 100644 zktools/errs/code.go delete mode 100644 zktools/errs/coderr.go delete mode 100644 zktools/errs/predefine.go delete mode 100644 zktools/errs/relation.go delete mode 100644 zktools/go.mod delete mode 100644 zktools/go.sum delete mode 100644 zktools/log/color.go delete mode 100644 zktools/log/logger.go delete mode 100644 zktools/log/sql_logger.go delete mode 100644 zktools/log/zap.go delete mode 100644 zktools/log/zk_logger.go delete mode 100644 zktools/mcontext/ctx.go delete mode 100644 zktools/mgoutil/mongo.go delete mode 100644 zktools/mw/gin.go delete mode 100644 zktools/mw/intercept_chain.go delete mode 100644 zktools/mw/rpc_client_interceptor.go delete mode 100644 zktools/mw/rpc_server_interceptor.go delete mode 100644 zktools/mw/specialerror/error.go delete mode 100644 zktools/network/ip.go delete mode 100644 zktools/ormutil/utils.go delete mode 100644 zktools/pagination/pagination.go delete mode 100644 zktools/prome/gather.go delete mode 100644 zktools/prome/prometheus.go delete mode 100644 zktools/tokenverify/jwt_token.go delete mode 100644 zktools/tokenverify/jwt_token_test.go delete mode 100644 zktools/tx/gorm.go delete mode 100644 zktools/tx/mongo.go delete mode 100644 zktools/tx/tx.go delete mode 100644 zktools/utils/base64.go delete mode 100644 zktools/utils/encryption.go delete mode 100644 zktools/utils/file.go delete mode 100644 zktools/utils/get_server_ip.go delete mode 100644 zktools/utils/id.go delete mode 100644 zktools/utils/id_test.go delete mode 100644 zktools/utils/image.go delete mode 100644 zktools/utils/image_test.go delete mode 100644 zktools/utils/map.go delete mode 100644 zktools/utils/md5_test.go delete mode 100644 zktools/utils/platform_number_id_to_name_test.go delete mode 100644 zktools/utils/retry/retry.go delete mode 100644 zktools/utils/retry/stratey.go delete mode 100644 zktools/utils/splitter/tools.go delete mode 100644 zktools/utils/strings.go delete mode 100644 zktools/utils/time_format.go delete mode 100644 zktools/utils/utils.go delete mode 100644 zktools/utils/utils_v2.go delete mode 100644 zktools/utils/utils_v2_test.go diff --git a/go.sum b/go.sum index 02cc5bfa8..e84117c46 100644 --- a/go.sum +++ b/go.sum @@ -137,6 +137,8 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0= github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= @@ -151,6 +153,11 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/redis/go-redis/v9 v9.1.0 h1:137FnGdk+EQdCbye1FW+qOEcY5S+SpY9T0NiuqvtfMY= github.com/redis/go-redis/v9 v9.1.0/go.mod h1:urWj3He21Dj5k4TK1y59xH8Uj6ATueP8AH1cY3lZl4c= +github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM= +github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= +github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= +github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM= +github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= @@ -181,6 +188,12 @@ github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca h1:uvPMDVyP7PXMMioYdyPH+0O+Ta/UO1WFfNYMO3Wz0eg= +github.com/xuri/efp v0.0.0-20230802181842-ad255f2331ca/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI= +github.com/xuri/excelize/v2 v2.8.0 h1:Vd4Qy809fupgp1v7X+nCS/MioeQmYVVzi495UCTqB7U= +github.com/xuri/excelize/v2 v2.8.0/go.mod h1:6iA2edBTKxKbZAa7X5bDhcCg51xdOn1Ar5sfoXRGrQg= +github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a h1:Mw2VNrNNNjDtw68VsEj2+st+oCSn4Uz7vZw6TbhcV1o= +github.com/xuri/nfp v0.0.0-20230819163627-dc951e3ffe1a/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -208,10 +221,10 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= -golang.org/x/image v0.9.0 h1:QrzfX26snvCM20hIhBwuHI/ThTg18b/+kcKdXHvnR+g= -golang.org/x/image v0.9.0/go.mod h1:jtrku+n79PfroUbvDdeUWMAI+heR786BofxrbiSF+J0= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/image v0.11.0 h1:ds2RoQvBvYTiJkwpSFDwCcDFNX7DqjL2WsUgTNk0Ooo= +golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -228,8 +241,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ= -golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= -golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -253,13 +266,14 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -269,8 +283,8 @@ golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/zktools/.gitignore b/zktools/.gitignore deleted file mode 100644 index 3390267f4..000000000 --- a/zktools/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -bin -logs -.devcontainer -components -logs -out-test -.github -.idea - - -deploy/open_im_demo -deploy/open_im_api -deploy/open_im_msg_gateway -deploy/open_im_msg_transfer -deploy/open_im_push -deploy/open_im_timer_task -deploy/open_im_rpc_user -deploy/open_im_rpc_friend -deploy/open_im_rpc_group -deploy/open_im_rpc_msg -deploy/open_im_rpc_auth -deploy/Open-IM-SDK-Core diff --git a/zktools/LICENSE b/zktools/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/zktools/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/zktools/README.md b/zktools/README.md deleted file mode 100644 index 58ecd25ba..000000000 --- a/zktools/README.md +++ /dev/null @@ -1 +0,0 @@ -# tools \ No newline at end of file diff --git a/zktools/a2r/api2rpc.go b/zktools/a2r/api2rpc.go deleted file mode 100644 index 87d9f7030..000000000 --- a/zktools/a2r/api2rpc.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package a2r - -import ( - "context" - - "github.com/OpenIMSDK/tools/checker" - - "github.com/gin-gonic/gin" - "google.golang.org/grpc" - - "github.com/OpenIMSDK/tools/apiresp" - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/log" -) - -func Call[A, B, C any]( - rpc func(client C, ctx context.Context, req *A, options ...grpc.CallOption) (*B, error), - client C, - c *gin.Context, -) { - var req A - if err := c.BindJSON(&req); err != nil { - log.ZWarn(c, "gin bind json error", err, "req", req) - apiresp.GinError(c, errs.ErrArgs.WithDetail(err.Error()).Wrap()) // 参数错误 - return - } - if err := checker.Validate(&req); err != nil { - apiresp.GinError(c, err) // 参数校验失败 - return - } - data, err := rpc(client, c, &req) - if err != nil { - apiresp.GinError(c, err) // RPC调用失败 - return - } - apiresp.GinSuccess(c, data) // 成功 -} diff --git a/zktools/apiresp/format.go b/zktools/apiresp/format.go deleted file mode 100644 index b53f31cbd..000000000 --- a/zktools/apiresp/format.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apiresp - -type ApiFormat interface { - ApiFormat() -} diff --git a/zktools/apiresp/gin.go b/zktools/apiresp/gin.go deleted file mode 100644 index 9d5637bfd..000000000 --- a/zktools/apiresp/gin.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apiresp - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -func GinError(c *gin.Context, err error) { - c.JSON(http.StatusOK, ParseError(err)) -} - -func GinSuccess(c *gin.Context, data any) { - c.JSON(http.StatusOK, ApiSuccess(data)) -} diff --git a/zktools/apiresp/http.go b/zktools/apiresp/http.go deleted file mode 100644 index db1c847cf..000000000 --- a/zktools/apiresp/http.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apiresp - -import ( - "encoding/json" - "net/http" -) - -func httpJson(w http.ResponseWriter, data any) { - body, err := json.Marshal(data) - if err != nil { - http.Error(w, "json marshal error: "+err.Error(), http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json; charset=utf-8") - w.WriteHeader(http.StatusOK) - _, _ = w.Write(body) -} - -func HttpError(w http.ResponseWriter, err error) { - httpJson(w, ParseError(err)) -} - -func HttpSuccess(w http.ResponseWriter, data any) { - httpJson(w, ApiSuccess(data)) -} diff --git a/zktools/apiresp/resp.go b/zktools/apiresp/resp.go deleted file mode 100644 index 13522d704..000000000 --- a/zktools/apiresp/resp.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package apiresp - -import ( - "reflect" - - "github.com/OpenIMSDK/tools/errs" -) - -type ApiResponse struct { - ErrCode int `json:"errCode"` - ErrMsg string `json:"errMsg"` - ErrDlt string `json:"errDlt"` - Data any `json:"data,omitempty"` -} - -func isAllFieldsPrivate(v any) bool { - typeOf := reflect.TypeOf(v) - if typeOf == nil { - return false - } - if typeOf.Kind() == reflect.Ptr { - typeOf = typeOf.Elem() - } - if typeOf.Kind() != reflect.Struct { - return false - } - num := typeOf.NumField() - for i := 0; i < num; i++ { - c := typeOf.Field(i).Name[0] - if c >= 'A' && c <= 'Z' { - return false - } - } - return true -} - -func ApiSuccess(data any) *ApiResponse { - if format, ok := data.(ApiFormat); ok { - format.ApiFormat() - } - if isAllFieldsPrivate(data) { - return &ApiResponse{} - } - return &ApiResponse{ - Data: data, - } -} - -func ParseError(err error) *ApiResponse { - if err == nil { - return ApiSuccess(nil) - } - unwrap := errs.Unwrap(err) - if codeErr, ok := unwrap.(errs.CodeError); ok { - resp := ApiResponse{ErrCode: codeErr.Code(), ErrMsg: codeErr.Msg(), ErrDlt: codeErr.Detail()} - if resp.ErrDlt == "" { - resp.ErrDlt = err.Error() - } - return &resp - } - return &ApiResponse{ErrCode: errs.ServerInternalError, ErrMsg: err.Error()} -} diff --git a/zktools/checker/check.go b/zktools/checker/check.go deleted file mode 100644 index 71b14a8f2..000000000 --- a/zktools/checker/check.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package checker - -import "github.com/OpenIMSDK/tools/errs" - -type Checker interface { - Check() error -} - -func Validate(args any) error { - if checker, ok := args.(Checker); ok { - if err := checker.Check(); err != nil { - if _, ok := errs.Unwrap(err).(errs.CodeError); ok { - return err - } - return errs.ErrArgs.Wrap(err.Error()) - } - } - return nil -} diff --git a/zktools/discoveryregistry/discovery_register.go b/zktools/discoveryregistry/discovery_register.go deleted file mode 100644 index faaae4fdd..000000000 --- a/zktools/discoveryregistry/discovery_register.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package discoveryregistry - -import ( - "context" - - "google.golang.org/grpc" -) - -type Conn interface { - GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]*grpc.ClientConn, error) - GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error) - GetSelfConnTarget() string - AddOption(opts ...grpc.DialOption) - CloseConn(conn *grpc.ClientConn) - // do not use this method for call rpc - GetClientLocalConns() map[string][]*grpc.ClientConn - GetUserIdHashGatewayHost(ctx context.Context, userId string) (string, error) -} - -type SvcDiscoveryRegistry interface { - Conn - Register(serviceName, host string, port int, opts ...grpc.DialOption) error - UnRegister() error - CreateRpcRootNodes(serviceNames []string) error - RegisterConf2Registry(key string, conf []byte) error - GetConfFromRegistry(key string) ([]byte, error) - Close() -} diff --git a/zktools/discoveryregistry/zookeeper/conf.go b/zktools/discoveryregistry/zookeeper/conf.go deleted file mode 100644 index 034c525ba..000000000 --- a/zktools/discoveryregistry/zookeeper/conf.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package zookeeper - -import ( - "github.com/go-zookeeper/zk" -) - -func (s *ZkClient) RegisterConf2Registry(key string, conf []byte) error { - exists, _, err := s.conn.Exists(s.getPath(key)) - if err != nil { - return err - } - if exists { - if err := s.conn.Delete(s.getPath(key), 0); err != nil { - return err - } - } - _, err = s.conn.Create(s.getPath(key), conf, 0, zk.WorldACL(zk.PermAll)) - if err != zk.ErrNodeExists { - return err - } - return nil -} - -func (s *ZkClient) GetConfFromRegistry(key string) ([]byte, error) { - bytes, _, err := s.conn.Get(s.getPath(key)) - return bytes, err -} diff --git a/zktools/discoveryregistry/zookeeper/discover.go b/zktools/discoveryregistry/zookeeper/discover.go deleted file mode 100644 index 6c2b2e085..000000000 --- a/zktools/discoveryregistry/zookeeper/discover.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package zookeeper - -import ( - "context" - "fmt" - "strings" - - "github.com/pkg/errors" - - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/log" - - "github.com/go-zookeeper/zk" - "google.golang.org/grpc" - "google.golang.org/grpc/resolver" -) - -var ( - ErrConnIsNil = errors.New("conn is nil") - ErrConnIsNilButLocalNotNil = errors.New("conn is nil, but local is not nil") -) - -func (s *ZkClient) watch(ctx context.Context) { - for { - select { - case <-ctx.Done(): - s.logger.Printf("zk watch ctx done") - return - case event := <-s.eventChan: - s.logger.Printf("zk eventChan recv new event: %+v", event) - switch event.Type { - case zk.EventSession: - switch event.State { - case zk.StateHasSession: - if s.isRegistered && !s.isStateDisconnected { - s.logger.Printf("zk session event stateHasSession: %+v, client prepare to create new temp node", event) - node, err := s.CreateTempNode(s.rpcRegisterName, s.rpcRegisterAddr) - if err != nil { - s.logger.Printf("zk session event stateHasSession: %+v, create temp node error: %v", event, err) - } else { - s.node = node - } - } - case zk.StateDisconnected: - s.isStateDisconnected = true - case zk.StateConnected: - s.isStateDisconnected = false - default: - s.logger.Printf("zk session event: %+v", event) - } - case zk.EventNodeChildrenChanged: - s.logger.Printf("zk event: %s", event.Path) - l := strings.Split(event.Path, "/") - if len(l) > 1 { - serviceName := l[len(l)-1] - s.lock.Lock() - s.flushResolverAndDeleteLocal(serviceName) - s.lock.Unlock() - } - s.logger.Printf("zk event handle success: %s", event.Path) - case zk.EventNodeDataChanged: - case zk.EventNodeCreated: - case zk.EventNodeDeleted: - case zk.EventNotWatching: - } - } - } -} - -func (s *ZkClient) GetConnsRemote(serviceName string) (conns []resolver.Address, err error) { - path := s.getPath(serviceName) - _, _, _, err = s.conn.ChildrenW(path) - if err != nil { - return nil, errors.Wrap(err, "children watch error") - } - childNodes, _, err := s.conn.Children(path) - if err != nil { - return nil, errors.Wrap(err, "get children error") - } else { - for _, child := range childNodes { - fullPath := path + "/" + child - data, _, err := s.conn.Get(fullPath) - if err != nil { - if err == zk.ErrNoNode { - return nil, errors.Wrap(err, "this is zk ErrNoNode") - } - return nil, errors.Wrap(err, "get children error") - } - log.ZDebug(context.Background(), "get addrs from remote", "conn", string(data)) - conns = append(conns, resolver.Address{Addr: string(data), ServerName: serviceName}) - } - } - return conns, nil -} -func (s *ZkClient) GetUserIdHashGatewayHost(ctx context.Context, userId string) (string, error) { - log.ZWarn(ctx, "not impliment", errors.New("zkclinet not impliment GetUserIdHashGatewayHost method")) - return "", nil -} -func (s *ZkClient) GetConns(ctx context.Context, serviceName string, opts ...grpc.DialOption) ([]*grpc.ClientConn, error) { - s.logger.Printf("get conns from client, serviceName: %s", serviceName) - s.lock.Lock() - defer s.lock.Unlock() - conns := s.localConns[serviceName] - if len(conns) == 0 { - var err error - s.logger.Printf("get conns from zk remote, serviceName: %s", serviceName) - addrs, err := s.GetConnsRemote(serviceName) - if err != nil { - return nil, err - } - if len(addrs) == 0 { - return nil, fmt.Errorf("no conn for service %s, grpc server may not exist, local conn is %v, please check zookeeper server %v, path: %s", serviceName, s.localConns, s.zkServers, s.zkRoot) - } - for _, addr := range addrs { - cc, err := grpc.DialContext(ctx, addr.Addr, append(s.options, opts...)...) - if err != nil { - log.ZError(context.Background(), "dialContext failed", err, "addr", addr.Addr, "opts", append(s.options, opts...)) - return nil, errs.Wrap(err) - } - conns = append(conns, cc) - } - s.localConns[serviceName] = conns - } - return conns, nil -} - -func (s *ZkClient) GetConn(ctx context.Context, serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { - newOpts := append(s.options, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, s.balancerName))) - s.logger.Printf("get conn from client, serviceName: %s", serviceName) - return grpc.DialContext(ctx, fmt.Sprintf("%s:///%s", s.scheme, serviceName), append(newOpts, opts...)...) -} - -func (s *ZkClient) GetSelfConnTarget() string { - return s.rpcRegisterAddr -} - -func (s *ZkClient) CloseConn(conn *grpc.ClientConn) { - conn.Close() -} diff --git a/zktools/discoveryregistry/zookeeper/register.go b/zktools/discoveryregistry/zookeeper/register.go deleted file mode 100644 index 7b13adf72..000000000 --- a/zktools/discoveryregistry/zookeeper/register.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package zookeeper - -import ( - "time" - - "github.com/go-zookeeper/zk" - "google.golang.org/grpc" -) - -func (s *ZkClient) CreateRpcRootNodes(serviceNames []string) error { - for _, serviceName := range serviceNames { - if err := s.ensureName(serviceName); err != nil && err != zk.ErrNodeExists { - return err - } - } - return nil -} - -func (s *ZkClient) CreateTempNode(rpcRegisterName, addr string) (node string, err error) { - return s.conn.CreateProtectedEphemeralSequential( - s.getPath(rpcRegisterName)+"/"+addr+"_", - []byte(addr), - zk.WorldACL(zk.PermAll), - ) -} - -func (s *ZkClient) Register(rpcRegisterName, host string, port int, opts ...grpc.DialOption) error { - if err := s.ensureName(rpcRegisterName); err != nil { - return err - } - addr := s.getAddr(host, port) - _, err := grpc.Dial(addr, opts...) - if err != nil { - return err - } - node, err := s.CreateTempNode(rpcRegisterName, addr) - if err != nil { - return err - } - s.rpcRegisterName = rpcRegisterName - s.rpcRegisterAddr = addr - s.node = node - s.isRegistered = true - return nil -} - -func (s *ZkClient) UnRegister() error { - s.lock.Lock() - defer s.lock.Unlock() - err := s.conn.Delete(s.node, -1) - if err != nil { - return err - } - time.Sleep(time.Second) - s.node = "" - s.rpcRegisterName = "" - s.rpcRegisterAddr = "" - s.isRegistered = false - s.localConns = make(map[string][]*grpc.ClientConn) - s.resolvers = make(map[string]*Resolver) - return nil -} diff --git a/zktools/discoveryregistry/zookeeper/resolver.go b/zktools/discoveryregistry/zookeeper/resolver.go deleted file mode 100644 index 0f8c3fa3e..000000000 --- a/zktools/discoveryregistry/zookeeper/resolver.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package zookeeper - -import ( - "context" - "strings" - - "github.com/OpenIMSDK/tools/log" - - "google.golang.org/grpc/resolver" -) - -type Resolver struct { - target resolver.Target - cc resolver.ClientConn - addrs []resolver.Address - - getConnsRemote func(serviceName string) (conns []resolver.Address, err error) -} - -func (r *Resolver) ResolveNowZK(o resolver.ResolveNowOptions) { - log.ZDebug( - context.Background(), - "start resolve now", - "target", - r.target, - "serviceName", - strings.TrimLeft(r.target.URL.Path, "/"), - ) - newConns, err := r.getConnsRemote(strings.TrimLeft(r.target.URL.Path, "/")) - if err != nil { - log.ZError(context.Background(), "resolve now error", err, "target", r.target) - return - } - r.addrs = newConns - if err := r.cc.UpdateState(resolver.State{Addresses: newConns}); err != nil { - log.ZError( - context.Background(), - "UpdateState error, conns is nil from svr", - err, - "conns", - newConns, - "zk path", - r.target.URL.Path, - ) - return - } - log.ZDebug(context.Background(), "resolve now finished", "target", r.target, "conns", r.addrs) -} - -func (r *Resolver) ResolveNow(o resolver.ResolveNowOptions) {} - -func (s *Resolver) Close() {} - -func (s *ZkClient) Build( - target resolver.Target, - cc resolver.ClientConn, - opts resolver.BuildOptions, -) (resolver.Resolver, error) { - s.logger.Printf("build resolver: %+v, cc: %+v", target, cc.UpdateState) - serviceName := strings.TrimLeft(target.URL.Path, "/") - r := &Resolver{} - r.target = target - r.cc = cc - r.getConnsRemote = s.GetConnsRemote - r.ResolveNowZK(resolver.ResolveNowOptions{}) - s.lock.Lock() - defer s.lock.Unlock() - s.resolvers[serviceName] = r - s.logger.Printf("build resolver finished: %+v, cc: %+v, key: %s", target, cc.UpdateState, serviceName) - return r, nil -} - -func (s *ZkClient) Scheme() string { return s.scheme } diff --git a/zktools/discoveryregistry/zookeeper/zk.go b/zktools/discoveryregistry/zookeeper/zk.go deleted file mode 100644 index 24ebc11f2..000000000 --- a/zktools/discoveryregistry/zookeeper/zk.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package zookeeper - -import ( - "context" - "github.com/OpenIMSDK/tools/log" - "net" - "strconv" - "sync" - "time" - - "github.com/go-zookeeper/zk" - "google.golang.org/grpc" - "google.golang.org/grpc/resolver" -) - -const ( - defaultFreq = time.Minute * 30 - timeout = 5 -) - -type Logger interface { - Printf(string, ...interface{}) -} - -type ZkClient struct { - zkServers []string - zkRoot string - userName string - password string - - rpcRegisterName string - rpcRegisterAddr string - isRegistered bool - scheme string - - timeout int - conn *zk.Conn - eventChan <-chan zk.Event - node string - ticker *time.Ticker - - lock sync.Locker - options []grpc.DialOption - - resolvers map[string]*Resolver - localConns map[string][]*grpc.ClientConn - cancel context.CancelFunc - isStateDisconnected bool - balancerName string - - logger Logger -} - -type ZkOption func(*ZkClient) - -func WithRoundRobin() ZkOption { - return func(client *ZkClient) { - client.balancerName = "round_robin" - } -} - -func WithUserNameAndPassword(userName, password string) ZkOption { - return func(client *ZkClient) { - client.userName = userName - client.password = password - } -} - -func WithOptions(opts ...grpc.DialOption) ZkOption { - return func(client *ZkClient) { - client.options = opts - } -} - -func WithFreq(freq time.Duration) ZkOption { - return func(client *ZkClient) { - client.ticker = time.NewTicker(freq) - } -} - -func WithTimeout(timeout int) ZkOption { - return func(client *ZkClient) { - client.timeout = timeout - } -} - -func WithLogger(logger Logger) ZkOption { - return func(client *ZkClient) { - client.logger = logger - } -} - -func NewClient(zkServers []string, zkRoot string, options ...ZkOption) (*ZkClient, error) { - client := &ZkClient{ - zkServers: zkServers, - zkRoot: "/", - scheme: zkRoot, - timeout: timeout, - localConns: make(map[string][]*grpc.ClientConn), - resolvers: make(map[string]*Resolver), - lock: &sync.Mutex{}, - } - baseCtx, cancel := context.WithCancel(context.Background()) - client.cancel = cancel - client.ticker = time.NewTicker(defaultFreq) - for _, option := range options { - option(client) - } - conn, eventChan, err := zk.Connect( - zkServers, - time.Duration(client.timeout)*time.Second, - zk.WithLogInfo(true), - zk.WithLogger(client.logger), - ) - if err != nil { - log.ZError(context.Background(), "zk Connect", err) - return nil, err - } - if client.userName != "" && client.password != "" { - if err := conn.AddAuth("digest", []byte(client.userName+":"+client.password)); err != nil { - log.ZError(context.Background(), "zk addAuth", err) - return nil, err - } - - } - client.zkRoot += zkRoot - client.eventChan = eventChan - client.conn = conn - if err := client.ensureRoot(); err != nil { - client.Close() - log.ZError(context.Background(), "zk client ensure root bug", err) - return nil, err - } - resolver.Register(client) - go client.refresh() - go client.watch(baseCtx) - time.Sleep(time.Millisecond * 50) - return client, nil -} - -func (s *ZkClient) Close() { - s.logger.Printf("close zk called") - s.cancel() - s.ticker.Stop() - s.conn.Close() -} - -func (s *ZkClient) ensureAndCreate(node string) error { - exists, _, err := s.conn.Exists(node) - if err != nil { - return err - } - if !exists { - _, err := s.conn.Create(node, []byte(""), 0, zk.WorldACL(zk.PermAll)) - if err != nil && err != zk.ErrNodeExists { - return err - } - } - return nil -} - -func (s *ZkClient) refresh() { - for range s.ticker.C { - s.logger.Printf("refresh local conns") - s.lock.Lock() - for rpcName := range s.resolvers { - s.flushResolver(rpcName) - } - for rpcName := range s.localConns { - delete(s.localConns, rpcName) - } - s.lock.Unlock() - s.logger.Printf("refresh local conns success") - } -} - -func (s *ZkClient) flushResolverAndDeleteLocal(serviceName string) { - s.logger.Printf("start flush %s", serviceName) - s.flushResolver(serviceName) - delete(s.localConns, serviceName) -} - -func (s *ZkClient) flushResolver(serviceName string) { - r, ok := s.resolvers[serviceName] - if ok { - r.ResolveNowZK(resolver.ResolveNowOptions{}) - } -} - -func (s *ZkClient) GetZkConn() *zk.Conn { - return s.conn -} - -func (s *ZkClient) GetRootPath() string { - return s.zkRoot -} - -func (s *ZkClient) GetNode() string { - return s.node -} - -func (s *ZkClient) ensureRoot() error { - return s.ensureAndCreate(s.zkRoot) -} - -func (s *ZkClient) ensureName(rpcRegisterName string) error { - return s.ensureAndCreate(s.getPath(rpcRegisterName)) -} - -func (s *ZkClient) getPath(rpcRegisterName string) string { - return s.zkRoot + "/" + rpcRegisterName -} - -func (s *ZkClient) getAddr(host string, port int) string { - return net.JoinHostPort(host, strconv.Itoa(port)) -} - -func (s *ZkClient) AddOption(opts ...grpc.DialOption) { - s.options = append(s.options, opts...) -} - -func (s *ZkClient) GetClientLocalConns() map[string][]*grpc.ClientConn { - return s.localConns -} diff --git a/zktools/errs/code.go b/zktools/errs/code.go deleted file mode 100644 index 9f70ab5e6..000000000 --- a/zktools/errs/code.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errs - -// UnknownCode 没有解析到code或解析的code=0. -const UnknownCode = 1000 - -const ( - FormattingError = 10001 - HasRegistered = 10002 - NotRegistered = 10003 - PasswordErr = 10004 - GetIMTokenErr = 10005 - RepeatSendCode = 10006 - MailSendCodeErr = 10007 - SmsSendCodeErr = 10008 - CodeInvalidOrExpired = 10009 - RegisterFailed = 10010 - ResetPasswordFailed = 10011 - RegisterLimit = 10012 - LoginLimit = 10013 - InvitationError = 10014 -) - -// 通用错误码. -const ( - NoError = 0 // 无错误 - DatabaseError = 90002 // redis/mysql等db错误 - NetworkError = 90004 // 网络错误 - DataError = 90007 // 数据错误 - - CallbackError = 80000 - - // 通用错误码. - ServerInternalError = 500 // 服务器内部错误 - ArgsError = 1001 // 输入参数错误 - NoPermissionError = 1002 // 权限不足 - DuplicateKeyError = 1003 - RecordNotFoundError = 1004 // 记录不存在 - - // 账号错误码. - UserIDNotFoundError = 1101 // UserID不存在 或未注册 - RegisteredAlreadyError = 1102 // 用户已经注册过了 - - // 群组错误码. - GroupIDNotFoundError = 1201 // GroupID不存在 - GroupIDExisted = 1202 // GroupID已存在 - NotInGroupYetError = 1203 // 不在群组中 - DismissedAlreadyError = 1204 // 群组已经解散 - GroupTypeNotSupport = 1205 - GroupRequestHandled = 1206 - - // 关系链错误码. - CanNotAddYourselfError = 1301 // 不能添加自己为好友 - BlockedByPeer = 1302 // 被对方拉黑 - NotPeersFriend = 1303 // 不是对方的好友 - RelationshipAlreadyError = 1304 // 已经是好友关系 - - // 消息错误码. - MessageHasReadDisable = 1401 - MutedInGroup = 1402 // 群成员被禁言 - MutedGroup = 1403 // 群被禁言 - MsgAlreadyRevoke = 1404 // 消息已撤回 - - // token错误码. - TokenExpiredError = 1501 - TokenInvalidError = 1502 - TokenMalformedError = 1503 - TokenNotValidYetError = 1504 - TokenUnknownError = 1505 - TokenKickedError = 1506 - TokenNotExistError = 1507 - - // 长连接网关错误码. - ConnOverMaxNumLimit = 1601 - ConnArgsErr = 1602 - - // S3错误码. - FileUploadedExpiredError = 1701 // 上传过期 -) diff --git a/zktools/errs/coderr.go b/zktools/errs/coderr.go deleted file mode 100644 index 1fa17b600..000000000 --- a/zktools/errs/coderr.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errs - -import ( - "strconv" - "strings" - - "github.com/pkg/errors" -) - -type CodeError interface { - Code() int - Msg() string - Detail() string - WithDetail(detail string) CodeError - // Is 判断是否是某个错误, loose为false时, 只有错误码相同就认为是同一个错误, 默认为true - Is(err error, loose ...bool) bool - Wrap(msg ...string) error - error -} - -func NewCodeError(code int, msg string) CodeError { - return &codeError{ - code: code, - msg: msg, - } -} - -type codeError struct { - code int - msg string - detail string -} - -func (e *codeError) Code() int { - return e.code -} - -func (e *codeError) Msg() string { - return e.msg -} - -func (e *codeError) Detail() string { - return e.detail -} - -func (e *codeError) WithDetail(detail string) CodeError { - var d string - if e.detail == "" { - d = detail - } else { - d = e.detail + ", " + detail - } - return &codeError{ - code: e.code, - msg: e.msg, - detail: d, - } -} - -func (e *codeError) Wrap(w ...string) error { - return errors.Wrap(e, strings.Join(w, ", ")) -} - -func (e *codeError) Is(err error, loose ...bool) bool { - if err == nil { - return false - } - var allowSubclasses bool - if len(loose) == 0 { - allowSubclasses = true - } else { - allowSubclasses = loose[0] - } - codeErr, ok := Unwrap(err).(CodeError) - if ok { - if allowSubclasses { - return Relation.Is(e.code, codeErr.Code()) - } else { - return codeErr.Code() == e.code - } - } - return false -} - -func (e *codeError) Error() string { - v := make([]string, 0, 3) - v = append(v, strconv.Itoa(e.code), e.msg) - if e.detail != "" { - v = append(v, e.detail) - } - return strings.Join(v, " ") -} - -func Unwrap(err error) error { - for err != nil { - unwrap, ok := err.(interface { - Unwrap() error - }) - if !ok { - break - } - err = unwrap.Unwrap() - } - return err -} - -func Wrap(err error, msg ...string) error { - if err == nil { - return nil - } - if len(msg) == 0 { - return errors.WithStack(err) - } - return errors.Wrap(err, strings.Join(msg, ", ")) -} diff --git a/zktools/errs/predefine.go b/zktools/errs/predefine.go deleted file mode 100644 index f11349891..000000000 --- a/zktools/errs/predefine.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errs - -var ( - ErrArgs = NewCodeError(ArgsError, "ArgsError") - ErrNoPermission = NewCodeError(NoPermissionError, "NoPermissionError") - ErrDatabase = NewCodeError(DatabaseError, "DatabaseError") - ErrInternalServer = NewCodeError(ServerInternalError, "ServerInternalError") - ErrNetwork = NewCodeError(NetworkError, "NetworkError") - ErrCallback = NewCodeError(CallbackError, "CallbackError") - ErrCallbackContinue = NewCodeError(CallbackError, "ErrCallbackContinue") - - ErrUserIDNotFound = NewCodeError(UserIDNotFoundError, "UserIDNotFoundError") - ErrGroupIDNotFound = NewCodeError(GroupIDNotFoundError, "GroupIDNotFoundError") - ErrGroupIDExisted = NewCodeError(GroupIDExisted, "GroupIDExisted") - - ErrRecordNotFound = NewCodeError(RecordNotFoundError, "RecordNotFoundError") - - ErrNotInGroupYet = NewCodeError(NotInGroupYetError, "NotInGroupYetError") - ErrDismissedAlready = NewCodeError(DismissedAlreadyError, "DismissedAlreadyError") - ErrRegisteredAlready = NewCodeError(RegisteredAlreadyError, "RegisteredAlreadyError") - ErrGroupTypeNotSupport = NewCodeError(GroupTypeNotSupport, "") - ErrGroupRequestHandled = NewCodeError(GroupRequestHandled, "GroupRequestHandled") - - ErrData = NewCodeError(DataError, "DataError") - ErrTokenExpired = NewCodeError(TokenExpiredError, "TokenExpiredError") - ErrTokenInvalid = NewCodeError(TokenInvalidError, "TokenInvalidError") // - ErrTokenMalformed = NewCodeError(TokenMalformedError, "TokenMalformedError") // 格式错误 - ErrTokenNotValidYet = NewCodeError(TokenNotValidYetError, "TokenNotValidYetError") // 还未生效 - ErrTokenUnknown = NewCodeError(TokenUnknownError, "TokenUnknownError") // 未知错误 - ErrTokenKicked = NewCodeError(TokenKickedError, "TokenKickedError") - ErrTokenNotExist = NewCodeError(TokenNotExistError, "TokenNotExistError") // 在redis中不存在 - ErrDuplicateKey = NewCodeError(DuplicateKeyError, "DuplicateKeyError") - - ErrMessageHasReadDisable = NewCodeError(MessageHasReadDisable, "MessageHasReadDisable") - - ErrCanNotAddYourself = NewCodeError(CanNotAddYourselfError, "CanNotAddYourselfError") - ErrBlockedByPeer = NewCodeError(BlockedByPeer, "BlockedByPeer") - ErrNotPeersFriend = NewCodeError(NotPeersFriend, "NotPeersFriend") - ErrRelationshipAlready = NewCodeError(RelationshipAlreadyError, "RelationshipAlreadyError") - - ErrMutedInGroup = NewCodeError(MutedInGroup, "MutedInGroup") - ErrMutedGroup = NewCodeError(MutedGroup, "MutedGroup") - ErrMsgAlreadyRevoke = NewCodeError(MsgAlreadyRevoke, "MsgAlreadyRevoke") - - ErrConnOverMaxNumLimit = NewCodeError(ConnOverMaxNumLimit, "ConnOverMaxNumLimit") - - ErrConnArgsErr = NewCodeError(ConnArgsErr, "args err, need token, sendID, platformID") - - ErrFileUploadedExpired = NewCodeError(FileUploadedExpiredError, "FileUploadedExpiredError") -) diff --git a/zktools/errs/relation.go b/zktools/errs/relation.go deleted file mode 100644 index 0a7ad4997..000000000 --- a/zktools/errs/relation.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errs - -var Relation = &relation{m: make(map[int]map[int]struct{})} - -func init() { - Relation.Add(RecordNotFoundError, UserIDNotFoundError) - Relation.Add(RecordNotFoundError, GroupIDNotFoundError) - Relation.Add(DuplicateKeyError, GroupIDExisted) -} - -type relation struct { - m map[int]map[int]struct{} -} - -func (r *relation) Add(codes ...int) { - if len(codes) < 2 { - panic("codes length must be greater than 2") - } - for i := 1; i < len(codes); i++ { - parent := codes[i-1] - s, ok := r.m[parent] - if !ok { - s = make(map[int]struct{}) - r.m[parent] = s - } - for _, code := range codes[i:] { - s[code] = struct{}{} - } - } -} - -func (r *relation) Is(parent, child int) bool { - if parent == child { - return true - } - s, ok := r.m[parent] - if !ok { - return false - } - _, ok = s[child] - return ok -} diff --git a/zktools/go.mod b/zktools/go.mod deleted file mode 100644 index 9303f773c..000000000 --- a/zktools/go.mod +++ /dev/null @@ -1,78 +0,0 @@ -module github.com/OpenIMSDK/tools - -go 1.18 - -require ( - github.com/bwmarrin/snowflake v0.3.0 - github.com/gin-gonic/gin v1.9.1 - github.com/go-zookeeper/zk v1.0.3 - github.com/golang-jwt/jwt/v4 v4.5.0 - github.com/jinzhu/copier v0.3.5 - github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible - github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 - github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.16.0 - github.com/stretchr/testify v1.8.3 - go.mongodb.org/mongo-driver v1.12.0 - go.uber.org/zap v1.24.0 - golang.org/x/image v0.9.0 - google.golang.org/grpc v1.56.2 - gorm.io/gorm v1.23.8 -) - -require ( - github.com/kr/text v0.2.0 // indirect - google.golang.org/protobuf v1.31.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) - -require ( - github.com/OpenIMSDK/protocol v0.0.1 - github.com/beorn7/perks v1.0.1 // indirect - github.com/bytedance/sonic v1.9.1 // indirect - github.com/cespare/xxhash/v2 v2.2.0 // indirect - github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/gabriel-vasile/mimetype v1.4.2 // indirect - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.14.0 // indirect - github.com/goccy/go-json v0.10.2 // indirect - github.com/golang/protobuf v1.5.3 // indirect - github.com/golang/snappy v0.0.3 // indirect - github.com/jinzhu/inflection v1.0.0 // indirect - github.com/jinzhu/now v1.1.5 // indirect - github.com/jonboulle/clockwork v0.4.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.13.6 // indirect - github.com/klauspost/cpuid/v2 v2.2.4 // indirect - github.com/leodido/go-urn v1.2.4 // indirect - github.com/lestrrat-go/strftime v1.0.6 // indirect - github.com/mattn/go-isatty v0.0.19 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect - github.com/pelletier/go-toml/v2 v2.0.8 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.42.0 // indirect - github.com/prometheus/procfs v0.10.1 // indirect - github.com/rogpeppe/go-internal v1.11.0 // indirect - github.com/twitchyliquid64/golang-asm v0.15.1 // indirect - github.com/ugorji/go/codec v1.2.11 // indirect - github.com/xdg-go/pbkdf2 v1.0.0 // indirect - github.com/xdg-go/scram v1.1.2 // indirect - github.com/xdg-go/stringprep v1.0.4 // indirect - github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect - go.uber.org/atomic v1.7.0 // indirect - go.uber.org/multierr v1.6.0 // indirect - golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.9.0 // indirect - golang.org/x/net v0.10.0 // indirect - golang.org/x/sync v0.2.0 // indirect - golang.org/x/sys v0.8.0 // indirect - golang.org/x/text v0.11.0 // indirect - google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect -) diff --git a/zktools/go.sum b/zktools/go.sum deleted file mode 100644 index c9fae1ceb..000000000 --- a/zktools/go.sum +++ /dev/null @@ -1,208 +0,0 @@ -github.com/OpenIMSDK/protocol v0.0.1 h1:Q6J1jCU00dfqmguxw2XI+IGcVfBAkb5Tz8LgvyeNkk0= -github.com/OpenIMSDK/protocol v0.0.1/go.mod h1:F25dFrwrIx3lkNoiuf6FkCfxuwf8L4Z8UIsdTHP/r0Y= -github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= -github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= -github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= -github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= -github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= -github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= -github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= -github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= -github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= -github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= -github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= -github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= -github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= -github.com/go-zookeeper/zk v1.0.3 h1:7M2kwOsc//9VeeFiPtf+uSJlVpU66x9Ba5+8XK7/TDg= -github.com/go-zookeeper/zk v1.0.3/go.mod h1:nOB03cncLtlp4t+UAkGSV+9beXP/akpekBwL+UX1Qcw= -github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= -github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= -github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= -github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= -github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= -github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= -github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= -github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= -github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= -github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4= -github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= -github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= -github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= -github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= -github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= -github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= -github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible h1:Y6sqxHMyB1D2YSzWkLibYKgg+SwmyFU9dF2hn6MdTj4= -github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible/go.mod h1:ZQnN8lSECaebrkQytbHj4xNgtg8CR7RYXnPok8e0EHA= -github.com/lestrrat-go/strftime v1.0.6 h1:CFGsDEt1pOpFNU+TJB0nhz9jl+K0hZSLE205AhTIGQQ= -github.com/lestrrat-go/strftime v1.0.6/go.mod h1:f7jQKgV5nnJpYgdEasS+/y7EsTb8ykN2z68n3TtcTaw= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= -github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= -github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0= -github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= -github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= -github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= -github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= -github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= -github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= -github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= -github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= -github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= -github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= -github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= -github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= -github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= -github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= -github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= -github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= -github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= -github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= -github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= -github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= -github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= -github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= -github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.mongodb.org/mongo-driver v1.12.0 h1:aPx33jmn/rQuJXPQLZQ8NtfPQG8CaqgLThFtqRb0PiE= -go.mongodb.org/mongo-driver v1.12.0/go.mod h1:AZkxhPnFJUoH7kZlFkVKucV20K387miPfm7oimrSmK0= -go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= -go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= -golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k= -golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= -golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= -golang.org/x/image v0.9.0 h1:QrzfX26snvCM20hIhBwuHI/ThTg18b/+kcKdXHvnR+g= -golang.org/x/image v0.9.0/go.mod h1:jtrku+n79PfroUbvDdeUWMAI+heR786BofxrbiSF+J0= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= -golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= -google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= -google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gorm.io/gorm v1.23.8 h1:h8sGJ+biDgBA1AD1Ha9gFCx7h8npU7AsLdlkX0n2TpE= -gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= -rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/zktools/log/color.go b/zktools/log/color.go deleted file mode 100644 index 9d1121d61..000000000 --- a/zktools/log/color.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "fmt" - - "go.uber.org/zap/zapcore" -) - -// Foreground colors. -const ( - Black Color = iota + 30 - Red - Green - Yellow - Blue - Magenta - Cyan - White -) - -var ( - _levelToColor = map[zapcore.Level]Color{ - zapcore.DebugLevel: White, - zapcore.InfoLevel: Blue, - zapcore.WarnLevel: Yellow, - zapcore.ErrorLevel: Red, - zapcore.DPanicLevel: Red, - zapcore.PanicLevel: Red, - zapcore.FatalLevel: Red, - } - _unknownLevelColor = make(map[zapcore.Level]string, len(_levelToColor)) - - _levelToLowercaseColorString = make(map[zapcore.Level]string, len(_levelToColor)) - _levelToCapitalColorString = make(map[zapcore.Level]string, len(_levelToColor)) -) - -func init() { - for level, color := range _levelToColor { - _levelToLowercaseColorString[level] = color.Add(level.String()) - _levelToCapitalColorString[level] = color.Add(level.CapitalString()) - } -} - -// Color represents a text color. -type Color uint8 - -// Add adds the coloring to the given string. -func (c Color) Add(s string) string { - return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), s) -} diff --git a/zktools/log/logger.go b/zktools/log/logger.go deleted file mode 100644 index cfbb91bdd..000000000 --- a/zktools/log/logger.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import "context" - -type Logger interface { - Debug(ctx context.Context, msg string, keysAndValues ...interface{}) - Info(ctx context.Context, msg string, keysAndValues ...interface{}) - Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) - Error(ctx context.Context, msg string, err error, keysAndValues ...interface{}) - WithValues(keysAndValues ...interface{}) Logger - WithName(name string) Logger - WithCallDepth(depth int) Logger -} diff --git a/zktools/log/sql_logger.go b/zktools/log/sql_logger.go deleted file mode 100644 index ae6cafb34..000000000 --- a/zktools/log/sql_logger.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "context" - "fmt" - "time" - - "github.com/pkg/errors" - "gorm.io/gorm" - gormLogger "gorm.io/gorm/logger" - gormUtils "gorm.io/gorm/utils" -) - -type SqlLogger struct { - LogLevel gormLogger.LogLevel - IgnoreRecordNotFoundError bool - SlowThreshold time.Duration -} - -func NewSqlLogger(logLevel gormLogger.LogLevel, ignoreRecordNotFoundError bool, slowThreshold time.Duration) *SqlLogger { - return &SqlLogger{ - LogLevel: logLevel, - IgnoreRecordNotFoundError: ignoreRecordNotFoundError, - SlowThreshold: slowThreshold, - } -} - -func (l *SqlLogger) LogMode(logLevel gormLogger.LogLevel) gormLogger.Interface { - newLogger := *l - newLogger.LogLevel = logLevel - return &newLogger -} - -func (SqlLogger) Info(ctx context.Context, msg string, args ...interface{}) { - ZInfo(ctx, msg, args) -} - -func (SqlLogger) Warn(ctx context.Context, msg string, args ...interface{}) { - ZWarn(ctx, msg, nil, args) -} - -func (SqlLogger) Error(ctx context.Context, msg string, args ...interface{}) { - ZError(ctx, msg, nil, args) -} - -func (l *SqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { - if l.LogLevel <= gormLogger.Silent { - return - } - elapsed := time.Since(begin) - switch { - case err != nil && l.LogLevel >= gormLogger.Error && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError): - sql, rows := fc() - if rows == -1 { - ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql) - } else { - ZError(ctx, "sql exec detail", err, "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql) - } - case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gormLogger.Warn: - sql, rows := fc() - slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold) - if rows == -1 { - ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql) - } else { - ZWarn(ctx, "sql exec detail", nil, "gorm", gormUtils.FileWithLineNum(), "slow sql", slowLog, "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql) - } - case l.LogLevel == gormLogger.Info: - sql, rows := fc() - if rows == -1 { - ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "sql", sql) - } else { - ZDebug(ctx, "sql exec detail", "gorm", gormUtils.FileWithLineNum(), "elapsed time", fmt.Sprintf("%f(ms)", float64(elapsed.Nanoseconds())/1e6), "rows", rows, "sql", sql) - } - } -} diff --git a/zktools/log/zap.go b/zktools/log/zap.go deleted file mode 100644 index 7bed816f4..000000000 --- a/zktools/log/zap.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "context" - "fmt" - "os" - "path/filepath" - "time" - - rotatelogs "github.com/lestrrat-go/file-rotatelogs" - - "github.com/OpenIMSDK/protocol/constant" - "github.com/OpenIMSDK/tools/mcontext" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -var ( - pkgLogger Logger - sp = string(filepath.Separator) - logLevelMap = map[int]zapcore.Level{ - 6: zapcore.DebugLevel, - 5: zapcore.DebugLevel, - 4: zapcore.InfoLevel, - 3: zapcore.WarnLevel, - 2: zapcore.ErrorLevel, - 1: zapcore.FatalLevel, - 0: zapcore.PanicLevel, - } -) - -// InitFromConfig initializes a Zap-based logger. -func InitFromConfig( - loggerPrefixName, moduleName string, - logLevel int, - isStdout bool, - isJson bool, - logLocation string, - rotateCount uint, - rotationTime uint, -) error { - l, err := NewZapLogger(loggerPrefixName, moduleName, logLevel, isStdout, isJson, logLocation, rotateCount, rotationTime) - if err != nil { - return err - } - pkgLogger = l.WithCallDepth(2) - if isJson { - pkgLogger = pkgLogger.WithName(moduleName) - } - return nil -} - -func ZDebug(ctx context.Context, msg string, keysAndValues ...interface{}) { - if pkgLogger == nil { - return - } - pkgLogger.Debug(ctx, msg, keysAndValues...) -} - -func ZInfo(ctx context.Context, msg string, keysAndValues ...interface{}) { - if pkgLogger == nil { - return - } - pkgLogger.Info(ctx, msg, keysAndValues...) -} - -func ZWarn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) { - if pkgLogger == nil { - return - } - pkgLogger.Warn(ctx, msg, err, keysAndValues...) -} - -func ZError(ctx context.Context, msg string, err error, keysAndValues ...interface{}) { - if pkgLogger == nil { - return - } - pkgLogger.Error(ctx, msg, err, keysAndValues...) -} - -type ZapLogger struct { - zap *zap.SugaredLogger - level zapcore.Level - loggerName string - loggerPrefixName string - rotationTime time.Duration -} - -func NewZapLogger( - loggerPrefixName, loggerName string, - logLevel int, - isStdout bool, - isJson bool, - logLocation string, - rotateCount uint, - rotationTime uint, -) (*ZapLogger, error) { - zapConfig := zap.Config{ - Level: zap.NewAtomicLevelAt(logLevelMap[logLevel]), - // EncoderConfig: zap.NewProductionEncoderConfig(), - // InitialFields: map[string]interface{}{"PID": os.Getegid()}, - DisableStacktrace: true, - } - if isJson { - zapConfig.Encoding = "json" - } else { - zapConfig.Encoding = "console" - } - // if isStdout { - // zapConfig.OutputPaths = append(zapConfig.OutputPaths, "stdout", "stderr") - // } - zl := &ZapLogger{level: logLevelMap[logLevel], loggerName: loggerName, loggerPrefixName: loggerPrefixName, rotationTime: time.Duration(rotationTime) * time.Hour} - opts, err := zl.cores(isStdout, isJson, logLocation, rotateCount) - if err != nil { - return nil, err - } - l, err := zapConfig.Build(opts) - if err != nil { - return nil, err - } - zl.zap = l.Sugar() - return zl, nil -} - -func (l *ZapLogger) cores(isStdout bool, isJson bool, logLocation string, rotateCount uint) (zap.Option, error) { - c := zap.NewProductionEncoderConfig() - c.EncodeTime = l.timeEncoder - c.EncodeDuration = zapcore.SecondsDurationEncoder - c.MessageKey = "msg" - c.LevelKey = "level" - c.TimeKey = "time" - c.CallerKey = "caller" - c.NameKey = "logger" - var fileEncoder zapcore.Encoder - if isJson { - c.EncodeLevel = zapcore.CapitalLevelEncoder - fileEncoder = zapcore.NewJSONEncoder(c) - fileEncoder.AddInt("PID", os.Getpid()) - } else { - c.EncodeLevel = l.capitalColorLevelEncoder - c.EncodeCaller = l.customCallerEncoder - fileEncoder = zapcore.NewConsoleEncoder(c) - } - writer, err := l.getWriter(logLocation, rotateCount) - if err != nil { - return nil, err - } - var cores []zapcore.Core - // if logLocation == "" && !isStdout { - // return nil, errors.New("log storage location is empty and not stdout") - // } - if logLocation != "" { - cores = []zapcore.Core{ - zapcore.NewCore(fileEncoder, writer, zap.NewAtomicLevelAt(l.level)), - } - } - if isStdout { - cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stdout), zap.NewAtomicLevelAt(l.level))) - // cores = append(cores, zapcore.NewCore(fileEncoder, zapcore.Lock(os.Stderr), zap.NewAtomicLevelAt(l.level))) - } - return zap.WrapCore(func(c zapcore.Core) zapcore.Core { - return zapcore.NewTee(cores...) - }), nil -} - -func (l *ZapLogger) customCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) { - s := "[" + caller.TrimmedPath() + "]" - // color, ok := _levelToColor[l.level] - // if !ok { - // color = _levelToColor[zapcore.ErrorLevel] - // } - enc.AppendString(s) -} - -func (l *ZapLogger) timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - layout := "2006-01-02 15:04:05.000" - type appendTimeEncoder interface { - AppendTimeLayout(time.Time, string) - } - if enc, ok := enc.(appendTimeEncoder); ok { - enc.AppendTimeLayout(t, layout) - return - } - enc.AppendString(t.Format(layout)) -} - -func (l *ZapLogger) getWriter(logLocation string, rorateCount uint) (zapcore.WriteSyncer, error) { - logf, err := rotatelogs.New(logLocation+sp+l.loggerPrefixName+".%Y-%m-%d", - rotatelogs.WithRotationCount(rorateCount), - rotatelogs.WithRotationTime(l.rotationTime), - ) - if err != nil { - return nil, err - } - return zapcore.AddSync(logf), nil -} - -func (l *ZapLogger) capitalColorLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { - s, ok := _levelToCapitalColorString[level] - if !ok { - s = _unknownLevelColor[zapcore.ErrorLevel] - } - pid := fmt.Sprintf("["+"PID:"+"%d"+"]", os.Getpid()) - color := _levelToColor[level] - enc.AppendString(s) - enc.AppendString(color.Add(pid)) - if l.loggerName != "" { - enc.AppendString(color.Add(l.loggerName)) - } -} - -func (l *ZapLogger) ToZap() *zap.SugaredLogger { - return l.zap -} - -func (l *ZapLogger) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) { - keysAndValues = l.kvAppend(ctx, keysAndValues) - l.zap.Debugw(msg, keysAndValues...) -} - -func (l *ZapLogger) Info(ctx context.Context, msg string, keysAndValues ...interface{}) { - keysAndValues = l.kvAppend(ctx, keysAndValues) - l.zap.Infow(msg, keysAndValues...) -} - -func (l *ZapLogger) Warn(ctx context.Context, msg string, err error, keysAndValues ...interface{}) { - if err != nil { - keysAndValues = append(keysAndValues, "error", err.Error()) - } - keysAndValues = l.kvAppend(ctx, keysAndValues) - l.zap.Warnw(msg, keysAndValues...) -} - -func (l *ZapLogger) Error(ctx context.Context, msg string, err error, keysAndValues ...interface{}) { - if err != nil { - keysAndValues = append(keysAndValues, "error", err.Error()) - } - keysAndValues = l.kvAppend(ctx, keysAndValues) - l.zap.Errorw(msg, keysAndValues...) -} - -func (l *ZapLogger) kvAppend(ctx context.Context, keysAndValues []interface{}) []interface{} { - if ctx == nil { - return keysAndValues - } - operationID := mcontext.GetOperationID(ctx) - opUserID := mcontext.GetOpUserID(ctx) - connID := mcontext.GetConnID(ctx) - triggerID := mcontext.GetTriggerID(ctx) - opUserPlatform := mcontext.GetOpUserPlatform(ctx) - remoteAddr := mcontext.GetRemoteAddr(ctx) - if opUserID != "" { - keysAndValues = append([]interface{}{constant.OpUserID, opUserID}, keysAndValues...) - } - if operationID != "" { - keysAndValues = append([]interface{}{constant.OperationID, operationID}, keysAndValues...) - } - if connID != "" { - keysAndValues = append([]interface{}{constant.ConnID, connID}, keysAndValues...) - } - if triggerID != "" { - keysAndValues = append([]interface{}{constant.TriggerID, triggerID}, keysAndValues...) - } - if opUserPlatform != "" { - keysAndValues = append([]interface{}{constant.OpUserPlatform, opUserPlatform}, keysAndValues...) - } - if remoteAddr != "" { - keysAndValues = append([]interface{}{constant.RemoteAddr, remoteAddr}, keysAndValues...) - } - return keysAndValues -} - -func (l *ZapLogger) WithValues(keysAndValues ...interface{}) Logger { - dup := *l - dup.zap = l.zap.With(keysAndValues...) - return &dup -} - -func (l *ZapLogger) WithName(name string) Logger { - dup := *l - dup.zap = l.zap.Named(name) - return &dup -} - -func (l *ZapLogger) WithCallDepth(depth int) Logger { - dup := *l - dup.zap = l.zap.WithOptions(zap.AddCallerSkip(depth)) - return &dup -} diff --git a/zktools/log/zk_logger.go b/zktools/log/zk_logger.go deleted file mode 100644 index 3579e2022..000000000 --- a/zktools/log/zk_logger.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package log - -import ( - "context" - "fmt" -) - -type ZkLogger struct{} - -func NewZkLogger() *ZkLogger { - return &ZkLogger{} -} - -func (l *ZkLogger) Printf(format string, a ...interface{}) { - ZInfo(context.Background(), "zookeeper output", "msg", fmt.Sprintf(format, a...)) -} diff --git a/zktools/mcontext/ctx.go b/zktools/mcontext/ctx.go deleted file mode 100644 index 94f7cb310..000000000 --- a/zktools/mcontext/ctx.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mcontext - -import ( - "context" - - "github.com/OpenIMSDK/protocol/constant" - "github.com/OpenIMSDK/tools/errs" -) - -var mapper = []string{constant.OperationID, constant.OpUserID, constant.OpUserPlatform, constant.ConnID} - -func WithOpUserIDContext(ctx context.Context, opUserID string) context.Context { - return context.WithValue(ctx, constant.OpUserID, opUserID) -} - -func WithOpUserPlatformContext(ctx context.Context, platform string) context.Context { - return context.WithValue(ctx, constant.OpUserPlatform, platform) -} - -func WithTriggerIDContext(ctx context.Context, triggerID string) context.Context { - return context.WithValue(ctx, constant.TriggerID, triggerID) -} - -func NewCtx(operationID string) context.Context { - c := context.Background() - ctx := context.WithValue(c, constant.OperationID, operationID) - return SetOperationID(ctx, operationID) -} - -func SetOperationID(ctx context.Context, operationID string) context.Context { - return context.WithValue(ctx, constant.OperationID, operationID) -} - -func SetOpUserID(ctx context.Context, opUserID string) context.Context { - return context.WithValue(ctx, constant.OpUserID, opUserID) -} - -func SetConnID(ctx context.Context, connID string) context.Context { - return context.WithValue(ctx, constant.ConnID, connID) -} - -func GetOperationID(ctx context.Context) string { - if ctx.Value(constant.OperationID) != nil { - s, ok := ctx.Value(constant.OperationID).(string) - if ok { - return s - } - } - return "" -} - -func GetOpUserID(ctx context.Context) string { - if ctx.Value(constant.OpUserID) != "" { - s, ok := ctx.Value(constant.OpUserID).(string) - if ok { - return s - } - } - return "" -} - -func GetConnID(ctx context.Context) string { - if ctx.Value(constant.ConnID) != "" { - s, ok := ctx.Value(constant.ConnID).(string) - if ok { - return s - } - } - return "" -} - -func GetTriggerID(ctx context.Context) string { - if ctx.Value(constant.TriggerID) != "" { - s, ok := ctx.Value(constant.TriggerID).(string) - if ok { - return s - } - } - return "" -} - -func GetOpUserPlatform(ctx context.Context) string { - if ctx.Value(constant.OpUserPlatform) != "" { - s, ok := ctx.Value(constant.OpUserPlatform).(string) - if ok { - return s - } - } - return "" -} - -func GetRemoteAddr(ctx context.Context) string { - if ctx.Value(constant.RemoteAddr) != "" { - s, ok := ctx.Value(constant.RemoteAddr).(string) - if ok { - return s - } - } - return "" -} - -func GetMustCtxInfo(ctx context.Context) (operationID, opUserID, platform, connID string, err error) { - operationID, ok := ctx.Value(constant.OperationID).(string) - if !ok { - err = errs.ErrArgs.Wrap("ctx missing operationID") - return - } - opUserID, ok1 := ctx.Value(constant.OpUserID).(string) - if !ok1 { - err = errs.ErrArgs.Wrap("ctx missing opUserID") - return - } - platform, ok2 := ctx.Value(constant.OpUserPlatform).(string) - if !ok2 { - err = errs.ErrArgs.Wrap("ctx missing platform") - return - } - connID, _ = ctx.Value(constant.ConnID).(string) - return -} - -func GetCtxInfos(ctx context.Context) (operationID, opUserID, platform, connID string, err error) { - operationID, ok := ctx.Value(constant.OperationID).(string) - if !ok { - err = errs.ErrArgs.Wrap("ctx missing operationID") - return - } - opUserID, _ = ctx.Value(constant.OpUserID).(string) - platform, _ = ctx.Value(constant.OpUserPlatform).(string) - connID, _ = ctx.Value(constant.ConnID).(string) - return -} - -func WithMustInfoCtx(values []string) context.Context { - ctx := context.Background() - for i, v := range values { - ctx = context.WithValue(ctx, mapper[i], v) - } - return ctx -} diff --git a/zktools/mgoutil/mongo.go b/zktools/mgoutil/mongo.go deleted file mode 100644 index 7b25c8764..000000000 --- a/zktools/mgoutil/mongo.go +++ /dev/null @@ -1,168 +0,0 @@ -package mgoutil - -import ( - "context" - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/pagination" - "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" -) - -func basic[T any]() bool { - var t T - switch any(t).(type) { - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string, []byte: - return true - case *int, *int8, *int16, *int32, *int64, *uint, *uint8, *uint16, *uint32, *uint64, *float32, *float64, *string, *[]byte: - return true - default: - return false - } -} - -func anes[T any](ts []T) []any { - val := make([]any, len(ts)) - for i := range ts { - val[i] = ts[i] - } - return val -} - -func findOptionToCountOption(opts []*options.FindOptions) *options.CountOptions { - return options.Count() -} - -func InsertMany[T any](ctx context.Context, coll *mongo.Collection, val []T, opts ...*options.InsertManyOptions) error { - _, err := coll.InsertMany(ctx, anes(val), opts...) - if err != nil { - return errs.Wrap(err) - } - return nil -} - -func UpdateOne(ctx context.Context, coll *mongo.Collection, filter any, update any, notMatchedErr bool, opts ...*options.UpdateOptions) error { - res, err := coll.UpdateOne(ctx, filter, update, opts...) - if err != nil { - return errs.Wrap(err) - } - if notMatchedErr && res.MatchedCount == 0 { - return errs.Wrap(mongo.ErrNoDocuments) - } - return nil -} - -func UpdateMany(ctx context.Context, coll *mongo.Collection, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error) { - res, err := coll.UpdateMany(ctx, filter, update, opts...) - if err != nil { - return nil, errs.Wrap(err) - } - return res, nil -} - -func Find[T any](ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.FindOptions) ([]T, error) { - cur, err := coll.Find(ctx, filter, opts...) - if err != nil { - return nil, errs.Wrap(err) - } - defer cur.Close(ctx) - var res []T - if basic[T]() { - var temp []map[string]T - if err := cur.All(ctx, &temp); err != nil { - return nil, errs.Wrap(err) - } - res = make([]T, 0, len(temp)) - for _, m := range temp { - if len(m) != 1 { - return nil, errs.ErrInternalServer.Wrap("mongo find result len(m) != 1") - } - for _, t := range m { - res = append(res, t) - } - } - } else { - if err := cur.All(ctx, &res); err != nil { - return nil, errs.Wrap(err) - } - } - return res, nil -} - -func FindOne[T any](ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.FindOneOptions) (res T, err error) { - cur := coll.FindOne(ctx, filter, opts...) - if err := cur.Err(); err != nil { - return res, errs.Wrap(err) - } - if err := cur.Decode(&res); err != nil { - return res, errs.Wrap(err) - } - return res, nil -} - -func FindPage[T any](ctx context.Context, coll *mongo.Collection, filter any, pagination pagination.Pagination, opts ...*options.FindOptions) (int64, []T, error) { - count, err := Count(ctx, coll, filter, findOptionToCountOption(opts)) - if err != nil { - return 0, nil, err - } - if count == 0 || pagination == nil { - return count, nil, nil - } - skip := int64(pagination.GetPageNumber()-1) * int64(pagination.GetShowNumber()) - if skip < 0 || skip >= count || pagination.GetShowNumber() <= 0 { - return count, nil, nil - } - opt := options.Find().SetSkip(skip).SetLimit(int64(pagination.GetShowNumber())) - res, err := Find[T](ctx, coll, filter, append(opts, opt)...) - if err != nil { - return 0, nil, err - } - return count, res, nil -} - -func FindPageOnly[T any](ctx context.Context, coll *mongo.Collection, filter any, pagination pagination.Pagination, opts ...*options.FindOptions) ([]T, error) { - skip := int64(pagination.GetPageNumber()-1) * int64(pagination.GetShowNumber()) - if skip < 0 || pagination.GetShowNumber() <= 0 { - return nil, nil - } - opt := options.Find().SetSkip(skip).SetLimit(int64(pagination.GetShowNumber())) - return Find[T](ctx, coll, filter, append(opts, opt)...) -} - -func Count(ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.CountOptions) (int64, error) { - return coll.CountDocuments(ctx, filter, opts...) -} - -func Exist(ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.CountOptions) (bool, error) { - opts = append(opts, options.Count().SetLimit(1)) - count, err := Count(ctx, coll, filter, opts...) - if err != nil { - return false, err - } - return count > 0, nil -} - -func DeleteOne(ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.DeleteOptions) error { - if _, err := coll.DeleteOne(ctx, filter, opts...); err != nil { - return errs.Wrap(err) - } - return nil -} - -func DeleteMany(ctx context.Context, coll *mongo.Collection, filter any, opts ...*options.DeleteOptions) error { - if _, err := coll.DeleteMany(ctx, filter, opts...); err != nil { - return errs.Wrap(err) - } - return nil -} - -func Aggregate[T any](ctx context.Context, coll *mongo.Collection, pipeline any, opts ...*options.AggregateOptions) ([]T, error) { - cur, err := coll.Aggregate(ctx, pipeline, opts...) - if err != nil { - return nil, err - } - var ts []T - if err := cur.All(ctx, &ts); err != nil { - return nil, err - } - return ts, nil -} diff --git a/zktools/mw/gin.go b/zktools/mw/gin.go deleted file mode 100644 index 3cebfcfe0..000000000 --- a/zktools/mw/gin.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mw - -import ( - "errors" - "net/http" - - "github.com/gin-gonic/gin" - - "github.com/OpenIMSDK/protocol/constant" - "github.com/OpenIMSDK/tools/apiresp" - "github.com/OpenIMSDK/tools/errs" -) - -// CorsHandler gin cross-domain configuration. -func CorsHandler() gin.HandlerFunc { - return func(c *gin.Context) { - c.Writer.Header().Set("Access-Control-Allow-Origin", "*") - c.Header("Access-Control-Allow-Methods", "*") - c.Header("Access-Control-Allow-Headers", "*") - c.Header( - "Access-Control-Expose-Headers", - "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar", - ) // Cross-domain key settings allow browsers to resolve. - c.Header( - "Access-Control-Max-Age", - "172800", - ) // Cache request information in seconds. - c.Header( - "Access-Control-Allow-Credentials", - "false", - ) // Whether cross-domain requests need to carry cookie information, the default setting is true. - c.Header( - "content-type", - "application/json", - ) // Set the return format to json. - // Release all option pre-requests - if c.Request.Method == http.MethodOptions { - c.JSON(http.StatusOK, "Options Request!") - c.Abort() - return - } - c.Next() - } -} - -func GinParseOperationID() gin.HandlerFunc { - return func(c *gin.Context) { - if c.Request.Method == http.MethodPost { - operationID := c.Request.Header.Get(constant.OperationID) - if operationID == "" { - err := errors.New("header must have operationID") - apiresp.GinError(c, errs.ErrArgs.Wrap(err.Error())) - c.Abort() - return - } - c.Set(constant.OperationID, operationID) - } - c.Next() - } -} diff --git a/zktools/mw/intercept_chain.go b/zktools/mw/intercept_chain.go deleted file mode 100644 index ae5361631..000000000 --- a/zktools/mw/intercept_chain.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mw - -import ( - "context" - - "google.golang.org/grpc" -) - -func InterceptChain(intercepts ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor { - l := len(intercepts) - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { - chain := func(currentInter grpc.UnaryServerInterceptor, currentHandler grpc.UnaryHandler) grpc.UnaryHandler { - return func(currentCtx context.Context, currentReq interface{}) (interface{}, error) { - return currentInter( - currentCtx, - currentReq, - info, - currentHandler) - } - } - chainHandler := handler - for i := l - 1; i >= 0; i-- { - chainHandler = chain(intercepts[i], chainHandler) - } - return chainHandler(ctx, req) - } -} diff --git a/zktools/mw/rpc_client_interceptor.go b/zktools/mw/rpc_client_interceptor.go deleted file mode 100644 index 2cb532e17..000000000 --- a/zktools/mw/rpc_client_interceptor.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mw - -import ( - "context" - "errors" - "fmt" - "strings" - - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" - - "github.com/OpenIMSDK/protocol/constant" - "github.com/OpenIMSDK/protocol/errinfo" - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/log" -) - -func GrpcClient() grpc.DialOption { - return grpc.WithChainUnaryInterceptor(RpcClientInterceptor) -} - -func RpcClientInterceptor( - ctx context.Context, - method string, - req, resp interface{}, - cc *grpc.ClientConn, - invoker grpc.UnaryInvoker, - opts ...grpc.CallOption, -) (err error) { - if ctx == nil { - return errs.ErrInternalServer.Wrap("call rpc request context is nil") - } - ctx, err = getRpcContext(ctx, method) - if err != nil { - return err - } - log.ZDebug(ctx, "get rpc ctx success", "conn target", cc.Target()) - err = invoker(ctx, method, req, resp, cc, opts...) - if err == nil { - log.ZInfo(ctx, "rpc client resp", "funcName", method, "resp", rpcString(resp)) - return nil - } - log.ZError(ctx, "rpc resp error", err) - rpcErr, ok := err.(interface{ GRPCStatus() *status.Status }) - if !ok { - return errs.ErrInternalServer.Wrap(err.Error()) - } - sta := rpcErr.GRPCStatus() - if sta.Code() == 0 { - return errs.NewCodeError(errs.ServerInternalError, err.Error()).Wrap() - } - if details := sta.Details(); len(details) > 0 { - errInfo, ok := details[0].(*errinfo.ErrorInfo) - if ok { - s := strings.Join(errInfo.Warp, "->") + errInfo.Cause - return errs.NewCodeError(int(sta.Code()), sta.Message()).WithDetail(s).Wrap() - } - } - return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap() -} - -func getRpcContext(ctx context.Context, method string) (context.Context, error) { - md := metadata.Pairs() - if keys, _ := ctx.Value(constant.RpcCustomHeader).([]string); len(keys) > 0 { - for _, key := range keys { - val, ok := ctx.Value(key).([]string) - if !ok { - return nil, errs.ErrInternalServer.Wrap(fmt.Sprintf("ctx missing key %s", key)) - } - if len(val) == 0 { - return nil, errs.ErrInternalServer.Wrap(fmt.Sprintf("ctx key %s value is empty", key)) - } - md.Set(key, val...) - } - md.Set(constant.RpcCustomHeader, keys...) - } - operationID, ok := ctx.Value(constant.OperationID).(string) - if !ok { - log.ZWarn(ctx, "ctx missing operationID", errors.New("ctx missing operationID"), "funcName", method) - return nil, errs.ErrArgs.Wrap("ctx missing operationID") - } - md.Set(constant.OperationID, operationID) - var checkArgs []string - checkArgs = append(checkArgs, constant.OperationID, operationID) - opUserID, ok := ctx.Value(constant.OpUserID).(string) - if ok { - md.Set(constant.OpUserID, opUserID) - checkArgs = append(checkArgs, constant.OpUserID, opUserID) - } - opUserIDPlatformID, ok := ctx.Value(constant.OpUserPlatform).(string) - if ok { - md.Set(constant.OpUserPlatform, opUserIDPlatformID) - } - connID, ok := ctx.Value(constant.ConnID).(string) - if ok { - md.Set(constant.ConnID, connID) - } - return metadata.NewOutgoingContext(ctx, md), nil -} diff --git a/zktools/mw/rpc_server_interceptor.go b/zktools/mw/rpc_server_interceptor.go deleted file mode 100644 index c4a693401..000000000 --- a/zktools/mw/rpc_server_interceptor.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package mw - -import ( - "context" - "fmt" - "github.com/OpenIMSDK/tools/checker" - "math" - - "github.com/OpenIMSDK/protocol/constant" - - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" - - "github.com/OpenIMSDK/protocol/errinfo" - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/log" - "github.com/OpenIMSDK/tools/mw/specialerror" -) - -func rpcString(v interface{}) string { - if s, ok := v.(interface{ String() string }); ok { - return s.String() - } - return fmt.Sprintf("%+v", v) -} - -func RpcServerInterceptor( - ctx context.Context, - req interface{}, - info *grpc.UnaryServerInfo, - handler grpc.UnaryHandler, -) (resp interface{}, err error) { - log.ZDebug(ctx, "rpc server req", "req", rpcString(req)) - //defer func() { - // if r := recover(); r != nil { - // log.ZError(ctx, "rpc panic", nil, "FullMethod", info.FullMethod, "type:", fmt.Sprintf("%T", r), "panic:", r) - // fmt.Printf("panic: %+v\nstack info: %s\n", r, string(debug.Stack())) - // pc, file, line, ok := runtime.Caller(4) - // if !ok { - // panic("get runtime.Caller failed") - // } - // errInfo := &errinfo.ErrorInfo{ - // Path: file, - // Line: uint32(line), - // Name: runtime.FuncForPC(pc).Name(), - // Cause: fmt.Sprintf("%s", r), - // Warp: nil, - // } - // sta, err_ := status.New(codes.Code(errs.ErrInternalServer.Code()), - // errs.ErrInternalServer.Msg()).WithDetails(errInfo) - // if err_ != nil { - // panic(err_) - // } - // err = sta.Err() - // } - //}() - funcName := info.FullMethod - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, status.New(codes.InvalidArgument, "missing metadata").Err() - } - if keys := md.Get(constant.RpcCustomHeader); len(keys) > 0 { - for _, key := range keys { - values := md.Get(key) - if len(values) == 0 { - return nil, status.New(codes.InvalidArgument, fmt.Sprintf("missing metadata key %s", key)).Err() - } - ctx = context.WithValue(ctx, key, values) - } - } - args := make([]string, 0, 4) - if opts := md.Get(constant.OperationID); len(opts) != 1 || opts[0] == "" { - return nil, status.New(codes.InvalidArgument, "operationID error").Err() - } else { - args = append(args, constant.OperationID, opts[0]) - ctx = context.WithValue(ctx, constant.OperationID, opts[0]) - } - if opts := md.Get(constant.OpUserID); len(opts) == 1 { - args = append(args, constant.OpUserID, opts[0]) - ctx = context.WithValue(ctx, constant.OpUserID, opts[0]) - } - if opts := md.Get(constant.OpUserPlatform); len(opts) == 1 { - ctx = context.WithValue(ctx, constant.OpUserPlatform, opts[0]) - } - if opts := md.Get(constant.ConnID); len(opts) == 1 { - ctx = context.WithValue(ctx, constant.ConnID, opts[0]) - } - log.ZInfo(ctx, "rpc server req", "funcName", funcName, "req", rpcString(req)) - resp, err = func() (interface{}, error) { - if err := checker.Validate(req); err != nil { - return nil, err - } - return handler(ctx, req) - }() - if err == nil { - log.ZInfo(ctx, "rpc server resp", "funcName", funcName, "resp", rpcString(resp)) - return resp, nil - } - log.ZError(ctx, "rpc server resp", err, "funcName", funcName) - unwrap := errs.Unwrap(err) - codeErr := specialerror.ErrCode(unwrap) - if codeErr == nil { - log.ZError(ctx, "rpc InternalServer error", err, "req", req) - codeErr = errs.ErrInternalServer - } - code := codeErr.Code() - if code <= 0 || code > math.MaxUint32 { - log.ZError(ctx, "rpc UnknownError", err, "rpc UnknownCode:", code) - code = errs.ServerInternalError - } - grpcStatus := status.New(codes.Code(code), codeErr.Msg()) - //var errInfo *errinfo.ErrorInfo - //if config.Config.Log.WithStack { - // if unwrap != err { - // sti, ok := err.(interface{ StackTrace() errors.StackTrace }) - // if ok { - // log.ZWarn( - // ctx, - // "rpc server resp", - // err, - // "funcName", - // funcName, - // "unwrap", - // unwrap.Error(), - // "stack", - // fmt.Sprintf("%+v", err), - // ) - // if fs := sti.StackTrace(); len(fs) > 0 { - // pc := uintptr(fs[0]) - // fn := runtime.FuncForPC(pc) - // file, line := fn.FileLine(pc) - // errInfo = &errinfo.ErrorInfo{ - // Path: file, - // Line: uint32(line), - // Name: fn.Name(), - // Cause: unwrap.Error(), - // Warp: nil, - // } - // if arr := strings.Split(err.Error(), ": "); len(arr) > 1 { - // errInfo.Warp = arr[:len(arr)-1] - // } - // } - // } - // } - //} - //if errInfo == nil { - // errInfo = &errinfo.ErrorInfo{Cause: err.Error()} - //} - errInfo := &errinfo.ErrorInfo{Cause: err.Error()} - details, err := grpcStatus.WithDetails(errInfo) - if err != nil { - log.ZWarn(ctx, "rpc server resp WithDetails error", err, "funcName", funcName) - return nil, errs.Wrap(err) - } - log.ZWarn(ctx, "rpc server resp", err, "funcName", funcName) - return nil, details.Err() -} - -func GrpcServer() grpc.ServerOption { - return grpc.ChainUnaryInterceptor(RpcServerInterceptor) -} diff --git a/zktools/mw/specialerror/error.go b/zktools/mw/specialerror/error.go deleted file mode 100644 index e97a9e636..000000000 --- a/zktools/mw/specialerror/error.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package specialerror - -import "github.com/OpenIMSDK/tools/errs" - -var handlers []func(err error) errs.CodeError - -func AddErrHandler(h func(err error) errs.CodeError) { - if h == nil { - panic("nil handler") - } - handlers = append(handlers, h) -} - -func AddReplace(target error, codeErr errs.CodeError) { - AddErrHandler(func(err error) errs.CodeError { - if err == target { - return codeErr - } - return nil - }) -} - -func ErrCode(err error) errs.CodeError { - if codeErr, ok := err.(errs.CodeError); ok { - return codeErr - } - for i := 0; i < len(handlers); i++ { - if codeErr := handlers[i](err); codeErr != nil { - return codeErr - } - } - return nil -} diff --git a/zktools/network/ip.go b/zktools/network/ip.go deleted file mode 100644 index 6dafa7e4f..000000000 --- a/zktools/network/ip.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package network - -import ( - "github.com/OpenIMSDK/tools/utils" - - "github.com/OpenIMSDK/protocol/constant" -) - -func GetRpcRegisterIP(configIP string) (string, error) { - registerIP := configIP - if registerIP == "" { - ip, err := utils.GetLocalIP() - if err != nil { - return "", err - } - registerIP = ip - } - return registerIP, nil -} - -func GetListenIP(configIP string) string { - if configIP == "" { - return constant.LocalHost - } else { - return configIP - } -} diff --git a/zktools/ormutil/utils.go b/zktools/ormutil/utils.go deleted file mode 100644 index d82a87c54..000000000 --- a/zktools/ormutil/utils.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package ormutil - -import ( - "strings" - - "gorm.io/gorm" - - "github.com/OpenIMSDK/tools/errs" -) - -func GormPage[E any](db *gorm.DB, pageNumber, showNumber int32) (uint32, []*E, error) { - var count int64 - var model E - if err := db.Model(&model).Count(&count).Error; err != nil { - return 0, nil, errs.Wrap(err) - } - var es []*E - if err := db.Limit(int(showNumber)).Offset(int((pageNumber - 1) * showNumber)).Find(&es).Error; err != nil { - return 0, nil, errs.Wrap(err) - } - return uint32(count), es, nil -} - -func GormSearch[E any](db *gorm.DB, fields []string, value string, pageNumber, showNumber int32) (uint32, []*E, error) { - if len(fields) > 0 && value != "" { - arr := make([]string, 0, len(fields)) - values := make([]interface{}, 0, len(fields)) - for _, field := range fields { - arr = append(arr, "`"+field+"` like concat('%',?,'%')") - values = append(values, value) - } - db = db.Where(strings.Join(arr, " or "), values...) - } - return GormPage[E](db, pageNumber, showNumber) -} - -func GormIn[E any](db **gorm.DB, field string, es []E) { - if len(es) == 0 { - return - } - *db = (*db).Where("`"+field+"` in ?", es) -} - -func MapCount(db *gorm.DB, field string) (map[string]uint32, error) { - var items []struct { - ID string `gorm:"column:id"` - Count uint32 `gorm:"column:count"` - } - if err := db.Select("`" + field + "` as id, count(1) as count").Group(field).Find(&items).Error; err != nil { - return nil, errs.Wrap(err) - } - m := make(map[string]uint32) - for _, item := range items { - m[item.ID] = item.Count - } - return m, nil -} diff --git a/zktools/pagination/pagination.go b/zktools/pagination/pagination.go deleted file mode 100644 index 8e779d685..000000000 --- a/zktools/pagination/pagination.go +++ /dev/null @@ -1,6 +0,0 @@ -package pagination - -type Pagination interface { - GetPageNumber() int32 - GetShowNumber() int32 -} diff --git a/zktools/prome/gather.go b/zktools/prome/gather.go deleted file mode 100644 index eb4bc6c3b..000000000 --- a/zktools/prome/gather.go +++ /dev/null @@ -1,470 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prome - -import ( - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promauto" -) - -var ( - // auth rpc. - UserLoginCounter prometheus.Counter - UserRegisterCounter prometheus.Counter - - // seg. - SeqGetSuccessCounter prometheus.Counter - SeqGetFailedCounter prometheus.Counter - SeqSetSuccessCounter prometheus.Counter - SeqSetFailedCounter prometheus.Counter - - // msg-db. - MsgInsertRedisSuccessCounter prometheus.Counter - MsgInsertRedisFailedCounter prometheus.Counter - MsgInsertMongoSuccessCounter prometheus.Counter - MsgInsertMongoFailedCounter prometheus.Counter - MsgPullFromRedisSuccessCounter prometheus.Counter - MsgPullFromRedisFailedCounter prometheus.Counter - MsgPullFromMongoSuccessCounter prometheus.Counter - MsgPullFromMongoFailedCounter prometheus.Counter - - // msg-ws. - MsgRecvTotalCounter prometheus.Counter - GetNewestSeqTotalCounter prometheus.Counter - PullMsgBySeqListTotalCounter prometheus.Counter - - SingleChatMsgRecvSuccessCounter prometheus.Counter - GroupChatMsgRecvSuccessCounter prometheus.Counter - WorkSuperGroupChatMsgRecvSuccessCounter prometheus.Counter - OnlineUserGauge prometheus.Gauge - - // msg-msg. - SingleChatMsgProcessSuccessCounter prometheus.Counter - SingleChatMsgProcessFailedCounter prometheus.Counter - GroupChatMsgProcessSuccessCounter prometheus.Counter - GroupChatMsgProcessFailedCounter prometheus.Counter - WorkSuperGroupChatMsgProcessSuccessCounter prometheus.Counter - WorkSuperGroupChatMsgProcessFailedCounter prometheus.Counter - - // msg-push. - MsgOnlinePushSuccessCounter prometheus.Counter - MsgOfflinePushSuccessCounter prometheus.Counter - MsgOfflinePushFailedCounter prometheus.Counter - // api. - ApiRequestCounter prometheus.Counter - ApiRequestSuccessCounter prometheus.Counter - ApiRequestFailedCounter prometheus.Counter - - // grpc. - GrpcRequestCounter prometheus.Counter - GrpcRequestSuccessCounter prometheus.Counter - GrpcRequestFailedCounter prometheus.Counter - - SendMsgCounter prometheus.Counter - - // conversation. - ConversationCreateSuccessCounter prometheus.Counter - ConversationCreateFailedCounter prometheus.Counter -) - -func NewUserLoginCounter() { - if UserLoginCounter != nil { - return - } - UserLoginCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "user_login", - Help: "The number of user login", - }) -} - -func NewUserRegisterCounter() { - if UserRegisterCounter != nil { - return - } - UserRegisterCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "user_register", - Help: "The number of user register", - }) -} - -func NewSeqGetSuccessCounter() { - if SeqGetSuccessCounter != nil { - return - } - SeqGetSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "seq_get_success", - Help: "The number of successful get seq", - }) -} - -func NewSeqGetFailedCounter() { - if SeqGetFailedCounter != nil { - return - } - SeqGetFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "seq_get_failed", - Help: "The number of failed get seq", - }) -} - -func NewSeqSetSuccessCounter() { - if SeqSetSuccessCounter != nil { - return - } - SeqSetSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "seq_set_success", - Help: "The number of successful set seq", - }) -} - -func NewSeqSetFailedCounter() { - if SeqSetFailedCounter != nil { - return - } - SeqSetFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "seq_set_failed", - Help: "The number of failed set seq", - }) -} - -func NewApiRequestCounter() { - if ApiRequestCounter != nil { - return - } - ApiRequestCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "api_request", - Help: "The number of api request", - }) -} - -func NewApiRequestSuccessCounter() { - if ApiRequestSuccessCounter != nil { - return - } - ApiRequestSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "api_request_success", - Help: "The number of api request success", - }) -} - -func NewApiRequestFailedCounter() { - if ApiRequestFailedCounter != nil { - return - } - ApiRequestFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "api_request_failed", - Help: "The number of api request failed", - }) -} - -func NewGrpcRequestCounter() { - if GrpcRequestCounter != nil { - return - } - GrpcRequestCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "grpc_request", - Help: "The number of api request", - }) -} - -func NewGrpcRequestSuccessCounter() { - if GrpcRequestSuccessCounter != nil { - return - } - GrpcRequestSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "grpc_request_success", - Help: "The number of grpc request success", - }) -} - -func NewGrpcRequestFailedCounter() { - if GrpcRequestFailedCounter != nil { - return - } - GrpcRequestFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "grpc_request_failed", - Help: "The number of grpc request failed", - }) -} - -func NewSendMsgCount() { - if SendMsgCounter != nil { - return - } - SendMsgCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "send_msg", - Help: "The number of send msg", - }) -} - -func NewMsgInsertRedisSuccessCounter() { - if MsgInsertRedisSuccessCounter != nil { - return - } - MsgInsertRedisSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_insert_redis_success", - Help: "The number of successful insert msg to redis", - }) -} - -func NewMsgInsertRedisFailedCounter() { - if MsgInsertRedisFailedCounter != nil { - return - } - MsgInsertRedisFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_insert_redis_failed", - Help: "The number of failed insert msg to redis", - }) -} - -func NewMsgInsertMongoSuccessCounter() { - if MsgInsertMongoSuccessCounter != nil { - return - } - MsgInsertMongoSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_insert_mongo_success", - Help: "The number of successful insert msg to mongo", - }) -} - -func NewMsgInsertMongoFailedCounter() { - if MsgInsertMongoFailedCounter != nil { - return - } - MsgInsertMongoFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_insert_mongo_failed", - Help: "The number of failed insert msg to mongo", - }) -} - -func NewMsgPullFromRedisSuccessCounter() { - if MsgPullFromRedisSuccessCounter != nil { - return - } - MsgPullFromRedisSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_pull_from_redis_success", - Help: "The number of successful pull msg from redis", - }) -} - -func NewMsgPullFromRedisFailedCounter() { - if MsgPullFromRedisFailedCounter != nil { - return - } - MsgPullFromRedisFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_pull_from_redis_failed", - Help: "The number of failed pull msg from redis", - }) -} - -func NewMsgPullFromMongoSuccessCounter() { - if MsgPullFromMongoSuccessCounter != nil { - return - } - MsgPullFromMongoSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_pull_from_mongo_success", - Help: "The number of successful pull msg from mongo", - }) -} - -func NewMsgPullFromMongoFailedCounter() { - if MsgPullFromMongoFailedCounter != nil { - return - } - MsgPullFromMongoFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_pull_from_mongo_failed", - Help: "The number of failed pull msg from mongo", - }) -} - -func NewMsgRecvTotalCounter() { - if MsgRecvTotalCounter != nil { - return - } - MsgRecvTotalCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_recv_total", - Help: "The number of msg received", - }) -} - -func NewGetNewestSeqTotalCounter() { - if GetNewestSeqTotalCounter != nil { - return - } - GetNewestSeqTotalCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "get_newest_seq_total", - Help: "the number of get newest seq", - }) -} - -func NewPullMsgBySeqListTotalCounter() { - if PullMsgBySeqListTotalCounter != nil { - return - } - PullMsgBySeqListTotalCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "pull_msg_by_seq_list_total", - Help: "The number of pull msg by seq list", - }) -} - -func NewSingleChatMsgRecvSuccessCounter() { - if SingleChatMsgRecvSuccessCounter != nil { - return - } - SingleChatMsgRecvSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "single_chat_msg_recv_success", - Help: "The number of single chat msg successful received ", - }) -} - -func NewGroupChatMsgRecvSuccessCounter() { - if GroupChatMsgRecvSuccessCounter != nil { - return - } - GroupChatMsgRecvSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "group_chat_msg_recv_success", - Help: "The number of group chat msg successful received", - }) -} - -func NewWorkSuperGroupChatMsgRecvSuccessCounter() { - if WorkSuperGroupChatMsgRecvSuccessCounter != nil { - return - } - WorkSuperGroupChatMsgRecvSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "work_super_group_chat_msg_recv_success", - Help: "The number of work/super group chat msg successful received", - }) -} - -func NewOnlineUserGauges() { - if OnlineUserGauge != nil { - return - } - OnlineUserGauge = promauto.NewGauge(prometheus.GaugeOpts{ - Name: "online_user_num", - Help: "The number of online user num", - }) -} - -func NewSingleChatMsgProcessSuccessCounter() { - if SingleChatMsgProcessSuccessCounter != nil { - return - } - SingleChatMsgProcessSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "single_chat_msg_process_success", - Help: "The number of single chat msg successful processed", - }) -} - -func NewSingleChatMsgProcessFailedCounter() { - if SingleChatMsgProcessFailedCounter != nil { - return - } - SingleChatMsgProcessFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "single_chat_msg_process_failed", - Help: "The number of single chat msg failed processed", - }) -} - -func NewGroupChatMsgProcessSuccessCounter() { - if GroupChatMsgProcessSuccessCounter != nil { - return - } - GroupChatMsgProcessSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "group_chat_msg_process_success", - Help: "The number of group chat msg successful processed", - }) -} - -func NewGroupChatMsgProcessFailedCounter() { - if GroupChatMsgProcessFailedCounter != nil { - return - } - GroupChatMsgProcessFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "group_chat_msg_process_failed", - Help: "The number of group chat msg failed processed", - }) -} - -func NewWorkSuperGroupChatMsgProcessSuccessCounter() { - if WorkSuperGroupChatMsgProcessSuccessCounter != nil { - return - } - WorkSuperGroupChatMsgProcessSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "work_super_group_chat_msg_process_success", - Help: "The number of work/super group chat msg successful processed", - }) -} - -func NewWorkSuperGroupChatMsgProcessFailedCounter() { - if WorkSuperGroupChatMsgProcessFailedCounter != nil { - return - } - WorkSuperGroupChatMsgProcessFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "work_super_group_chat_msg_process_failed", - Help: "The number of work/super group chat msg failed processed", - }) -} - -func NewMsgOnlinePushSuccessCounter() { - if MsgOnlinePushSuccessCounter != nil { - return - } - MsgOnlinePushSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_online_push_success", - Help: "The number of msg successful online pushed", - }) -} - -func NewMsgOfflinePushSuccessCounter() { - if MsgOfflinePushSuccessCounter != nil { - return - } - MsgOfflinePushSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_offline_push_success", - Help: "The number of msg successful offline pushed", - }) -} - -func NewMsgOfflinePushFailedCounter() { - if MsgOfflinePushFailedCounter != nil { - return - } - MsgOfflinePushFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "msg_offline_push_failed", - Help: "The number of msg failed offline pushed", - }) -} - -func NewConversationCreateSuccessCounter() { - if ConversationCreateSuccessCounter != nil { - return - } - ConversationCreateSuccessCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "conversation_push_success", - Help: "The number of conversation successful pushed", - }) -} - -func NewConversationCreateFailedCounter() { - if ConversationCreateFailedCounter != nil { - return - } - ConversationCreateFailedCounter = promauto.NewCounter(prometheus.CounterOpts{ - Name: "conversation_push_failed", - Help: "The number of conversation failed pushed", - }) -} diff --git a/zktools/prome/prometheus.go b/zktools/prome/prometheus.go deleted file mode 100644 index 077d1c2d5..000000000 --- a/zktools/prome/prometheus.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package prome - -import ( - "bytes" - "net/http" - "strconv" - - "github.com/gin-gonic/gin" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -var Enable bool - -func StartPrometheusSrv(prometheusPort int) error { - if !Enable { - return nil - } - http.Handle("/metrics", promhttp.Handler()) - return http.ListenAndServe(":"+strconv.Itoa(prometheusPort), nil) -} - -func PrometheusHandler() gin.HandlerFunc { - h := promhttp.Handler() - return func(c *gin.Context) { - h.ServeHTTP(c.Writer, c.Request) - } -} - -type responseBodyWriter struct { - gin.ResponseWriter - body *bytes.Buffer -} - -func (r responseBodyWriter) Write(b []byte) (int, error) { - r.body.Write(b) - return r.ResponseWriter.Write(b) -} - -func PrometheusMiddleware(c *gin.Context) { - Inc(ApiRequestCounter) - w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer} - c.Writer = w - c.Next() - if c.Writer.Status() == http.StatusOK { - Inc(ApiRequestSuccessCounter) - } else { - Inc(ApiRequestFailedCounter) - } -} - -func Inc(counter prometheus.Counter) { - if Enable { - if counter != nil { - counter.Inc() - } - } -} - -func Add(counter prometheus.Counter, add int) { - if Enable { - if counter != nil { - counter.Add(float64(add)) - } - } -} - -func GaugeInc(gauges prometheus.Gauge) { - if Enable { - if gauges != nil { - gauges.Inc() - } - } -} - -func GaugeDec(gauges prometheus.Gauge) { - if Enable { - if gauges != nil { - gauges.Dec() - } - } -} diff --git a/zktools/tokenverify/jwt_token.go b/zktools/tokenverify/jwt_token.go deleted file mode 100644 index 5f3b898a1..000000000 --- a/zktools/tokenverify/jwt_token.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package tokenverify - -import ( - "time" - - "github.com/golang-jwt/jwt/v4" - - "github.com/OpenIMSDK/tools/errs" - "github.com/OpenIMSDK/tools/utils" -) - -type Claims struct { - UserID string - PlatformID int // login platform - jwt.RegisteredClaims -} - -func BuildClaims(uid string, platformID int, ttl int64) Claims { - now := time.Now() - before := now.Add(-time.Minute * 5) - return Claims{ - UserID: uid, - PlatformID: platformID, - RegisteredClaims: jwt.RegisteredClaims{ - ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*24) * time.Hour)), // Expiration time - IssuedAt: jwt.NewNumericDate(now), // Issuing time - NotBefore: jwt.NewNumericDate(before), // Begin Effective time - }, - } -} - -func GetClaimFromToken(tokensString string, secretFunc jwt.Keyfunc) (*Claims, error) { - token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secretFunc) - if err != nil { - if ve, ok := err.(*jwt.ValidationError); ok { - if ve.Errors&jwt.ValidationErrorMalformed != 0 { - return nil, utils.Wrap(errs.ErrTokenMalformed, "") - } else if ve.Errors&jwt.ValidationErrorExpired != 0 { - return nil, utils.Wrap(errs.ErrTokenExpired, "") - } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 { - return nil, utils.Wrap(errs.ErrTokenNotValidYet, "") - } else { - return nil, utils.Wrap(errs.ErrTokenUnknown, "") - } - } else { - return nil, utils.Wrap(errs.ErrTokenUnknown, "") - } - } else { - if claims, ok := token.Claims.(*Claims); ok && token.Valid { - return claims, nil - } - return nil, utils.Wrap(errs.ErrTokenUnknown, "") - } -} diff --git a/zktools/tokenverify/jwt_token_test.go b/zktools/tokenverify/jwt_token_test.go deleted file mode 100644 index ef3d96234..000000000 --- a/zktools/tokenverify/jwt_token_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package tokenverify - -import ( - "testing" - - "github.com/golang-jwt/jwt/v4" - - "github.com/OpenIMSDK/protocol/constant" -) - -var secret = "OpenIM_server" - -func Test_ParseToken(t *testing.T) { - claims1 := BuildClaims("123456", constant.AndroidPadPlatformID, 10) - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims1) - tokenString, err := token.SignedString([]byte(secret)) - if err != nil { - t.Fatal(err) - } - claim2, err := GetClaimFromToken(tokenString, secretFun()) - if err != nil { - t.Fatal(err) - } - t.Log(claim2) -} - -func secretFun() jwt.Keyfunc { - return func(token *jwt.Token) (interface{}, error) { - return []byte(secret), nil - } -} diff --git a/zktools/tx/gorm.go b/zktools/tx/gorm.go deleted file mode 100644 index 98e71cb9f..000000000 --- a/zktools/tx/gorm.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package tx - -import ( - "gorm.io/gorm" -) - -func NewGorm(db *gorm.DB) Tx { - return &_Gorm{tx: db} -} - -type _Gorm struct { - tx *gorm.DB -} - -func (g *_Gorm) Transaction(fn func(tx any) error) error { - return g.tx.Transaction(func(tx *gorm.DB) error { - return fn(tx) - }) -} diff --git a/zktools/tx/mongo.go b/zktools/tx/mongo.go deleted file mode 100644 index 3ead4153b..000000000 --- a/zktools/tx/mongo.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package tx - -import ( - "context" - "go.mongodb.org/mongo-driver/bson" - "sync" - - "go.mongodb.org/mongo-driver/mongo" -) - -func NewMongo(client *mongo.Client) CtxTx { - return &_Mongo{ - initialized: false, - lock: &sync.Mutex{}, - client: client, - } -} - -type _Mongo struct { - initialized bool - lock sync.Locker - client *mongo.Client - tx func(func(ctx context.Context) error) error -} - -func (m *_Mongo) init(ctx context.Context) (err error) { - m.lock.Lock() - defer func() { - if err == nil { - m.initialized = true - } - m.lock.Unlock() - }() - if m.initialized { - return nil - } - var res map[string]any - if err := m.client.Database("admin").RunCommand(ctx, bson.M{"isMaster": 1}).Decode(&res); err != nil { - return err - } - _, allowTx := res["setName"] - if !allowTx { - return nil - } - m.tx = func(fn func(ctx context.Context) error) error { - sess, err := m.client.StartSession() - if err != nil { - return err - } - defer sess.EndSession(ctx) - _, err = sess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) { - return nil, fn(sessCtx) - }) - return err - } - return nil -} - -func (m *_Mongo) Transaction(ctx context.Context, fn func(ctx context.Context) error) error { - if !m.initialized { - if err := m.init(ctx); err != nil { - return err - } - } - if m.tx == nil { - return fn(ctx) - } - return m.tx(fn) -} diff --git a/zktools/tx/tx.go b/zktools/tx/tx.go deleted file mode 100644 index 9a6fe02ef..000000000 --- a/zktools/tx/tx.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package tx - -import "context" - -type Tx interface { - Transaction(fn func(tx any) error) error -} - -type CtxTx interface { - Transaction(ctx context.Context, fn func(ctx context.Context) error) error -} diff --git a/zktools/utils/base64.go b/zktools/utils/base64.go deleted file mode 100644 index 9502dcde8..000000000 --- a/zktools/utils/base64.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import "encoding/base64" - -func Base64Encode(data string) string { - return base64.StdEncoding.EncodeToString([]byte(data)) -} - -func Base64Decode(data string) string { - decodedByte, _ := base64.StdEncoding.DecodeString(data) - return string(decodedByte) -} diff --git a/zktools/utils/encryption.go b/zktools/utils/encryption.go deleted file mode 100644 index 23266d8f7..000000000 --- a/zktools/utils/encryption.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/md5" - "encoding/hex" - "errors" -) - -func Md5(s string, salt ...string) string { - h := md5.New() - h.Write([]byte(s)) - if len(salt) > 0 { - h.Write([]byte(salt[0])) - } - cipher := h.Sum(nil) - return hex.EncodeToString(cipher) -} - -func AesEncrypt(data []byte, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - encryptBytes := pkcs7Padding(data, blockSize) - crypted := make([]byte, len(encryptBytes)) - blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) - blockMode.CryptBlocks(crypted, encryptBytes) - return crypted, nil -} - -func AesDecrypt(data []byte, key []byte) ([]byte, error) { - block, err := aes.NewCipher(key) - if err != nil { - return nil, err - } - blockSize := block.BlockSize() - blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) - crypted := make([]byte, len(data)) - blockMode.CryptBlocks(crypted, data) - crypted, err = pkcs7UnPadding(crypted) - if err != nil { - return nil, err - } - return crypted, nil -} - -func pkcs7Padding(data []byte, blockSize int) []byte { - padding := blockSize - len(data)%blockSize - padText := bytes.Repeat([]byte{byte(padding)}, padding) - return append(data, padText...) -} - -func pkcs7UnPadding(data []byte) ([]byte, error) { - length := len(data) - if length == 0 { - return nil, errors.New("encrypt error") - } - unPadding := int(data[length-1]) - return data[:(length - unPadding)], nil -} diff --git a/zktools/utils/file.go b/zktools/utils/file.go deleted file mode 100644 index e61de4116..000000000 --- a/zktools/utils/file.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "os" - "strconv" - "strings" -) - -const ( - BYTE = 1 << (10 * iota) - KILOBYTE - MEGABYTE - GIGABYTE - TERABYTE - PETABYTE - EXABYTE -) - -// Determine whether the given path is a folder -func IsDir(path string) bool { - s, err := os.Stat(path) - if err != nil { - return false - } - return s.IsDir() -} - -// Determine whether the given path is a file -func IsFile(path string) bool { - return !IsDir(path) -} - -// Create a directory -func MkDir(path string) error { - return os.MkdirAll(path, os.ModePerm) -} - -//func GetNewFileNameAndContentType(fileName string, fileType int) (string, string) { -// suffix := path.Ext(fileName) -// newName := fmt.Sprintf("%d-%d%s", time.Now().UnixNano(), rand.Int(), fileName) -// contentType := "" -// if fileType == constant.ImageType { -// contentType = "image/" + suffix[1:] -// } -// return newName, contentType -//} - -func ByteSize(bytes uint64) string { - unit := "" - value := float64(bytes) - switch { - case bytes >= EXABYTE: - unit = "E" - value = value / EXABYTE - case bytes >= PETABYTE: - unit = "P" - value = value / PETABYTE - case bytes >= TERABYTE: - unit = "T" - value = value / TERABYTE - case bytes >= GIGABYTE: - unit = "G" - value = value / GIGABYTE - case bytes >= MEGABYTE: - unit = "M" - value = value / MEGABYTE - case bytes >= KILOBYTE: - unit = "K" - value = value / KILOBYTE - case bytes >= BYTE: - unit = "B" - case bytes == 0: - return "0" - } - result := strconv.FormatFloat(value, 'f', 1, 64) - result = strings.TrimSuffix(result, ".0") - return result + unit -} diff --git a/zktools/utils/get_server_ip.go b/zktools/utils/get_server_ip.go deleted file mode 100644 index aad0bf2cc..000000000 --- a/zktools/utils/get_server_ip.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "errors" - "net" -) - -var ServerIP = "" - -func GetLocalIP() (string, error) { - addrs, err := net.InterfaceAddrs() - if err != nil { - return "", err - } - for _, address := range addrs { - - if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - return ipnet.IP.String(), nil - } - } - } - - return "", errors.New("no ip") -} diff --git a/zktools/utils/id.go b/zktools/utils/id.go deleted file mode 100644 index 25e942f36..000000000 --- a/zktools/utils/id.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "github.com/bwmarrin/snowflake" -) - -func init() { - var err error - idGenerator, err = snowflake.NewNode(getNodeNum()) - if err != nil { - panic(err) - } -} - -func getNodeNum() int64 { - return 1 -} - -var idGenerator *snowflake.Node - -func GenID() string { - return idGenerator.Generate().String() -} - -func GenIDs(count int) []string { - //impl - return []string{} -} diff --git a/zktools/utils/id_test.go b/zktools/utils/id_test.go deleted file mode 100644 index d6ab3e665..000000000 --- a/zktools/utils/id_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import "testing" - -func TestGenID(t *testing.T) { - m := map[string]struct{}{} - for i := 0; i < 2000; i++ { - got := GenID() - if _, ok := m[got]; !ok { - m[got] = struct{}{} - } else { - t.Error("id generate error", got) - } - } -} diff --git a/zktools/utils/image.go b/zktools/utils/image.go deleted file mode 100644 index f93591f9e..000000000 --- a/zktools/utils/image.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "errors" - "image" - "image/gif" - "image/jpeg" - "image/png" - "io" - "os" - - "github.com/nfnt/resize" - "golang.org/x/image/bmp" -) - -func GenSmallImage(src, dst string) error { - fIn, _ := os.Open(src) - defer fIn.Close() - - fOut, _ := os.Create(dst) - defer fOut.Close() - - if err := scale(fIn, fOut, 0, 0, 0); err != nil { - return err - } - return nil -} - -func scale(in io.Reader, out io.Writer, width, height, quality int) error { - origin, fm, err := image.Decode(in) - if err != nil { - return err - } - if width == 0 || height == 0 { - width = origin.Bounds().Max.X / 2 - height = origin.Bounds().Max.Y / 2 - } - if quality == 0 { - quality = 25 - } - canvas := resize.Thumbnail(uint(width), uint(height), origin, resize.Lanczos3) - - switch fm { - case "jpeg": - return jpeg.Encode(out, canvas, &jpeg.Options{quality}) - case "png": - return png.Encode(out, canvas) - case "gif": - return gif.Encode(out, canvas, &gif.Options{}) - case "bmp": - return bmp.Encode(out, canvas) - default: - return errors.New("ERROR FORMAT") - } -} diff --git a/zktools/utils/image_test.go b/zktools/utils/image_test.go deleted file mode 100644 index 87d78620f..000000000 --- a/zktools/utils/image_test.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "path/filepath" - "runtime" - "testing" - - "github.com/stretchr/testify/assert" -) - -var ( - _, b, _, _ = runtime.Caller(0) - // Root folder of this project - Root = filepath.Join(filepath.Dir(b), "../..") -) - -func Test_GenSmallImage(t *testing.T) { - println(Root) - err := GenSmallImage(Root+"/docs/open-im-logo.png", Root+"/out-test/open-im-logo-test.png") - assert.Nil(t, err) - - err = GenSmallImage(Root+"/docs/open-im-logo.png", "out-test/open-im-logo-test.png") - assert.Nil(t, err) - - err = GenSmallImage(Root+"/docs/Architecture.jpg", "out-test/Architecture-test.jpg") - assert.Nil(t, err) -} diff --git a/zktools/utils/map.go b/zktools/utils/map.go deleted file mode 100644 index cd7f3f1de..000000000 --- a/zktools/utils/map.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "encoding/json" - "sync" -) - -type Map struct { - sync.RWMutex - m map[interface{}]interface{} -} - -func (m *Map) init() { - if m.m == nil { - m.m = make(map[interface{}]interface{}) - } -} - -func (m *Map) UnsafeGet(key interface{}) interface{} { - if m.m == nil { - return nil - } else { - return m.m[key] - } -} - -func (m *Map) Get(key interface{}) interface{} { - m.RLock() - defer m.RUnlock() - return m.UnsafeGet(key) -} - -func (m *Map) UnsafeSet(key interface{}, value interface{}) { - m.init() - m.m[key] = value -} - -func (m *Map) Set(key interface{}, value interface{}) { - m.Lock() - defer m.Unlock() - m.UnsafeSet(key, value) -} - -func (m *Map) TestAndSet(key interface{}, value interface{}) interface{} { - m.Lock() - defer m.Unlock() - - m.init() - - if v, ok := m.m[key]; ok { - return v - } else { - m.m[key] = value - return nil - } -} - -func (m *Map) UnsafeDel(key interface{}) { - m.init() - delete(m.m, key) -} - -func (m *Map) Del(key interface{}) { - m.Lock() - defer m.Unlock() - m.UnsafeDel(key) -} - -func (m *Map) UnsafeLen() int { - if m.m == nil { - return 0 - } else { - return len(m.m) - } -} - -func (m *Map) Len() int { - m.RLock() - defer m.RUnlock() - return m.UnsafeLen() -} - -func (m *Map) UnsafeRange(f func(interface{}, interface{})) { - if m.m == nil { - return - } - for k, v := range m.m { - f(k, v) - } -} - -func (m *Map) RLockRange(f func(interface{}, interface{})) { - m.RLock() - defer m.RUnlock() - m.UnsafeRange(f) -} - -func (m *Map) LockRange(f func(interface{}, interface{})) { - m.Lock() - defer m.Unlock() - m.UnsafeRange(f) -} - -func MapToJsonString(param map[string]interface{}) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} -func MapIntToJsonString(param map[string]int32) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} -func JsonStringToMap(str string) (tempMap map[string]int32) { - _ = json.Unmarshal([]byte(str), &tempMap) - return tempMap -} -func GetSwitchFromOptions(Options map[string]bool, key string) (result bool) { - if Options == nil { - return true - } - if flag, ok := Options[key]; !ok || flag { - return true - } - return false -} - -func SetSwitchFromOptions(options map[string]bool, key string, value bool) { - if options == nil { - options = make(map[string]bool, 5) - } - options[key] = value -} diff --git a/zktools/utils/md5_test.go b/zktools/utils/md5_test.go deleted file mode 100644 index 1add67f32..000000000 --- a/zktools/utils/md5_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_Md5(t *testing.T) { - result := Md5("go") - assert.Equal(t, result, "34d1f91fb2e514b8576fab1a75a89a6b") - - result2 := Md5("go") - assert.Equal(t, result, result2) -} diff --git a/zktools/utils/platform_number_id_to_name_test.go b/zktools/utils/platform_number_id_to_name_test.go deleted file mode 100644 index 37e49d704..000000000 --- a/zktools/utils/platform_number_id_to_name_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "testing" - - "github.com/OpenIMSDK/protocol/constant" - - "github.com/stretchr/testify/assert" -) - -func Test_PlatformIDToName(t *testing.T) { - assert.Equal(t, constant.PlatformIDToName(1), "IOS") - assert.Equal(t, constant.PlatformIDToName(2), "Android") - assert.Equal(t, constant.PlatformIDToName(3), "Windows") - assert.Equal(t, constant.PlatformIDToName(4), "OSX") - assert.Equal(t, constant.PlatformIDToName(5), "Web") - assert.Equal(t, constant.PlatformIDToName(6), "MiniWeb") - assert.Equal(t, constant.PlatformIDToName(7), "Linux") - - assert.Equal(t, constant.PlatformIDToName(0), "") -} - -func Test_PlatformNameToID(t *testing.T) { - assert.Equal(t, constant.PlatformNameToID("IOS"), int32(1)) - assert.Equal(t, constant.PlatformNameToID("Android"), int32(2)) - assert.Equal(t, constant.PlatformNameToID("Windows"), int32(3)) - assert.Equal(t, constant.PlatformNameToID("OSX"), int32(4)) - assert.Equal(t, constant.PlatformNameToID("Web"), int32(5)) - assert.Equal(t, constant.PlatformNameToID("MiniWeb"), int32(6)) - assert.Equal(t, constant.PlatformNameToID("Linux"), int32(7)) - - assert.Equal(t, constant.PlatformNameToID("UnknownDevice"), int32(0)) - assert.Equal(t, constant.PlatformNameToID(""), int32(0)) -} - -func Test_PlatformNameToClass(t *testing.T) { - assert.Equal(t, constant.PlatformNameToClass("IOS"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("Android"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("OSX"), "PC") - assert.Equal(t, constant.PlatformNameToClass("Windows"), "PC") - assert.Equal(t, constant.PlatformNameToClass("Web"), "PC") - assert.Equal(t, constant.PlatformNameToClass("MiniWeb"), "Mobile") - assert.Equal(t, constant.PlatformNameToClass("Linux"), "PC") - - assert.Equal(t, constant.PlatformNameToClass("UnknownDevice"), "") - assert.Equal(t, constant.PlatformNameToClass(""), "") -} diff --git a/zktools/utils/retry/retry.go b/zktools/utils/retry/retry.go deleted file mode 100644 index eb2a387cb..000000000 --- a/zktools/utils/retry/retry.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package retry - -import ( - "context" - "errors" - "fmt" - "runtime/debug" - "time" -) - -var ( - ErrorAbort = errors.New("stop retry") - ErrorTimeout = errors.New("retry timeout") - ErrorContextDeadlineExceed = errors.New("context deadline exceeded") - ErrorEmptyRetryFunc = errors.New("empty retry function") - ErrorTimeFormat = errors.New("time out err") -) - -type RetriesFunc func() error -type Option func(c *Config) -type HookFunc func() -type RetriesChecker func(err error) (needRetry bool) -type Config struct { - MaxRetryTimes int - Timeout time.Duration - RetryChecker RetriesChecker - Strategy Strategy - RecoverPanic bool - BeforeTry HookFunc - AfterTry HookFunc -} - -var ( - DefaultMaxRetryTimes = 3 - DefaultTimeout = time.Minute - DefaultInterval = time.Second * 2 - DefaultRetryChecker = func(err error) bool { - return !errors.Is(err, ErrorAbort) // not abort error, should continue retry - } -) - -func newDefaultConfig() *Config { - return &Config{ - MaxRetryTimes: DefaultMaxRetryTimes, - RetryChecker: DefaultRetryChecker, - Timeout: DefaultTimeout, - Strategy: NewLinear(DefaultInterval), - BeforeTry: func() {}, - AfterTry: func() {}, - } -} - -func WithTimeout(timeout time.Duration) Option { - return func(c *Config) { - c.Timeout = timeout - } -} - -func WithMaxRetryTimes(times int) Option { - return func(c *Config) { - c.MaxRetryTimes = times - } -} - -func WithRecoverPanic() Option { - return func(c *Config) { - c.RecoverPanic = true - } -} - -func WithBeforeHook(hook HookFunc) Option { - return func(c *Config) { - c.BeforeTry = hook - } -} - -func WithAfterHook(hook HookFunc) Option { - return func(c *Config) { - c.AfterTry = hook - } -} - -func WithRetryChecker(checker RetriesChecker) Option { - return func(c *Config) { - c.RetryChecker = checker - } -} - -func WithBackOffStrategy(s BackoffStrategy, duration time.Duration) Option { - return func(c *Config) { - switch s { - case StrategyConstant: - c.Strategy = NewConstant(duration) - case StrategyLinear: - c.Strategy = NewLinear(duration) - case StrategyFibonacci: - c.Strategy = NewFibonacci(duration) - } - } -} - -func WithCustomStrategy(s Strategy) Option { - return func(c *Config) { - c.Strategy = s - } -} - -func Do(ctx context.Context, fn RetriesFunc, opts ...Option) error { - if fn == nil { - return ErrorEmptyRetryFunc - } - var ( - abort = make(chan struct{}, 1) // caller choose to abort retry - run = make(chan error, 1) - panicInfoChan = make(chan string, 1) - - timer *time.Timer - runErr error - ) - config := newDefaultConfig() - for _, o := range opts { - o(config) - } - if config.Timeout > 0 { - timer = time.NewTimer(config.Timeout) - } else { - return ErrorTimeFormat - } - go func() { - var err error - defer func() { - if e := recover(); e == nil { - return - } else { - panicInfoChan <- fmt.Sprintf("retry function panic has occured, err=%v, stack:%s", e, string(debug.Stack())) - } - }() - for i := 0; i < config.MaxRetryTimes; i++ { - config.BeforeTry() - err = fn() - config.AfterTry() - if err == nil { - run <- nil - return - } - // check whether to retry - if config.RetryChecker != nil { - needRetry := config.RetryChecker(err) - if !needRetry { - abort <- struct{}{} - return - } - } - if config.Strategy != nil { - interval := config.Strategy.Sleep(i + 1) - <-time.After(interval) - } - } - run <- err - }() - select { - case <-ctx.Done(): - // context deadline exceed - return ErrorContextDeadlineExceed - case <-timer.C: - // timeout - return ErrorTimeout - case <-abort: - // caller abort - return ErrorAbort - case msg := <-panicInfoChan: - // panic occurred - if !config.RecoverPanic { - panic(msg) - } - runErr = fmt.Errorf("panic occurred=%s", msg) - case e := <-run: - // normal run - if e != nil { - runErr = fmt.Errorf("retry failed, err=%w", e) - } - } - return runErr -} diff --git a/zktools/utils/retry/stratey.go b/zktools/utils/retry/stratey.go deleted file mode 100644 index 8dca54161..000000000 --- a/zktools/utils/retry/stratey.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package retry - -import "time" - -type BackoffStrategy int - -const ( - StrategyConstant BackoffStrategy = iota - StrategyLinear - StrategyFibonacci -) - -type Strategy interface { - Sleep(times int) time.Duration -} -type Constant struct { - startInterval time.Duration -} - -func NewConstant(d time.Duration) *Constant { - return &Constant{startInterval: d} -} - -type Linear struct { - startInterval time.Duration -} - -func NewLinear(d time.Duration) *Linear { - return &Linear{startInterval: d} -} - -type Fibonacci struct { - startInterval time.Duration -} - -func NewFibonacci(d time.Duration) *Fibonacci { - return &Fibonacci{startInterval: d} -} - -func (c *Constant) Sleep(_ int) time.Duration { - return c.startInterval -} -func (l *Linear) Sleep(times int) time.Duration { - return l.startInterval * time.Duration(times) - -} -func (f *Fibonacci) Sleep(times int) time.Duration { - return f.startInterval * time.Duration(fibonacciNumber(times)) - -} -func fibonacciNumber(n int) int { - if n == 0 || n == 1 { - return n - } - return fibonacciNumber(n-1) + fibonacciNumber(n-2) -} diff --git a/zktools/utils/splitter/tools.go b/zktools/utils/splitter/tools.go deleted file mode 100644 index d36b9c3be..000000000 --- a/zktools/utils/splitter/tools.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package splitter - -type SplitResult struct { - Item []string -} -type Splitter struct { - splitCount int - data []string -} - -func NewSplitter(splitCount int, data []string) *Splitter { - return &Splitter{splitCount: splitCount, data: data} -} -func (s *Splitter) GetSplitResult() (result []*SplitResult) { - remain := len(s.data) % s.splitCount - integer := len(s.data) / s.splitCount - for i := 0; i < integer; i++ { - r := new(SplitResult) - r.Item = s.data[i*s.splitCount : (i+1)*s.splitCount] - result = append(result, r) - } - if remain > 0 { - r := new(SplitResult) - r.Item = s.data[integer*s.splitCount:] - result = append(result, r) - } - return result -} diff --git a/zktools/utils/strings.go b/zktools/utils/strings.go deleted file mode 100644 index 641c43e9f..000000000 --- a/zktools/utils/strings.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "encoding/json" - "math/rand" - "strconv" -) - -func IntToString(i int) string { - return strconv.FormatInt(int64(i), 10) -} - -func StringToInt(i string) int { - j, _ := strconv.Atoi(i) - return j -} -func StringToInt64(i string) int64 { - j, _ := strconv.ParseInt(i, 10, 64) - return j -} -func StringToInt32(i string) int32 { - j, _ := strconv.ParseInt(i, 10, 64) - return int32(j) -} -func Int32ToString(i int32) string { - return strconv.FormatInt(int64(i), 10) -} - -func Uint32ToString(i uint32) string { - return strconv.FormatInt(int64(i), 10) -} - -// judge a string whether in the string list -func IsContain(target string, List []string) bool { - for _, element := range List { - - if target == element { - return true - } - } - return false -} -func IsContainInt32(target int32, List []int32) bool { - for _, element := range List { - if target == element { - return true - } - } - return false -} -func IsContainInt(target int, List []int) bool { - for _, element := range List { - if target == element { - return true - } - } - return false -} -func InterfaceArrayToStringArray(data []interface{}) (i []string) { - for _, param := range data { - i = append(i, param.(string)) - } - return i -} -func StructToJsonString(param interface{}) string { - dataType, _ := json.Marshal(param) - dataString := string(dataType) - return dataString -} - -func StructToJsonBytes(param interface{}) []byte { - dataType, _ := json.Marshal(param) - return dataType -} - -// The incoming parameter must be a pointer -func JsonStringToStruct(s string, args interface{}) error { - err := json.Unmarshal([]byte(s), args) - return err -} - -func GetMsgID(sendID string) string { - t := int64ToString(GetCurrentTimestampByNano()) - return Md5(t + sendID + int64ToString(rand.Int63n(GetCurrentTimestampByNano()))) -} - -func int64ToString(i int64) string { - return strconv.FormatInt(i, 10) -} -func Int64ToString(i int64) string { - return strconv.FormatInt(i, 10) -} - -func RemoveDuplicateElement(idList []string) []string { - result := make([]string, 0, len(idList)) - temp := map[string]struct{}{} - for _, item := range idList { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - result = append(result, item) - } - } - return result -} - -func RemoveDuplicate[T comparable](arr []T) []T { - result := make([]T, 0, len(arr)) - temp := map[T]struct{}{} - for _, item := range arr { - if _, ok := temp[item]; !ok { - temp[item] = struct{}{} - result = append(result, item) - } - } - return result -} - -func IsDuplicateStringSlice(arr []string) bool { - t := make(map[string]struct{}) - for _, s := range arr { - if _, ok := t[s]; ok { - return true - } - t[s] = struct{}{} - } - return false -} diff --git a/zktools/utils/time_format.go b/zktools/utils/time_format.go deleted file mode 100644 index 9278a58ef..000000000 --- a/zktools/utils/time_format.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "strconv" - "time" -) - -const ( - TimeOffset = 8 * 3600 //8 hour offset - HalfOffset = 12 * 3600 //Half-day hourly offset -) - -// Get the current timestamp by Second -func GetCurrentTimestampBySecond() int64 { - return time.Now().Unix() -} - -// Convert timestamp to time.Time type -func UnixSecondToTime(second int64) time.Time { - return time.Unix(second, 0) -} - -// Convert nano timestamp to time.Time type -func UnixNanoSecondToTime(nanoSecond int64) time.Time { - return time.Unix(0, nanoSecond) -} -func UnixMillSecondToTime(millSecond int64) time.Time { - return time.Unix(0, millSecond*1e6) -} - -// Get the current timestamp by Nano -func GetCurrentTimestampByNano() int64 { - return time.Now().UnixNano() -} - -// Get the current timestamp by Mill -func GetCurrentTimestampByMill() int64 { - return time.Now().UnixNano() / 1e6 -} - -// Get the timestamp at 0 o'clock of the day -func GetCurDayZeroTimestamp() int64 { - timeStr := time.Now().Format("2006-01-02") - t, _ := time.Parse("2006-01-02", timeStr) - return t.Unix() - TimeOffset -} - -// Get the timestamp at 12 o'clock on the day -func GetCurDayHalfTimestamp() int64 { - return GetCurDayZeroTimestamp() + HalfOffset - -} - -// Get the formatted time at 0 o'clock of the day, the format is "2006-01-02_00-00-00" -func GetCurDayZeroTimeFormat() string { - return time.Unix(GetCurDayZeroTimestamp(), 0).Format("2006-01-02_15-04-05") -} - -// Get the formatted time at 12 o'clock of the day, the format is "2006-01-02_12-00-00" -func GetCurDayHalfTimeFormat() string { - return time.Unix(GetCurDayZeroTimestamp()+HalfOffset, 0).Format("2006-01-02_15-04-05") -} -func GetTimeStampByFormat(datetime string) string { - timeLayout := "2006-01-02 15:04:05" - loc, _ := time.LoadLocation("Local") - tmp, _ := time.ParseInLocation(timeLayout, datetime, loc) - timestamp := tmp.Unix() - return strconv.FormatInt(timestamp, 10) -} - -func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 { - tm, _ := time.Parse(timeFormat, timeSrc) - return tm.Unix() -} - -func TimeStringToTime(timeString string) (time.Time, error) { - t, err := time.Parse("2006-01-02", timeString) - return t, err -} - -func TimeToString(t time.Time) string { - return t.Format("2006-01-02") -} diff --git a/zktools/utils/utils.go b/zktools/utils/utils.go deleted file mode 100644 index 0b14a949d..000000000 --- a/zktools/utils/utils.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "github.com/jinzhu/copier" - "github.com/pkg/errors" - "hash/crc32" - "math/rand" - "runtime" - "sort" - "strconv" - "strings" - "time" -) - -// copy a by b b->a -func CopyStructFields(a interface{}, b interface{}, fields ...string) (err error) { - return copier.Copy(a, b) -} - -func Wrap1(err error) error { - return errors.Wrap(err, "==> "+printCallerNameAndLine()) -} - -func Wrap2[T any](a T, err error) (T, error) { - if err != nil { - return a, errors.Wrap(err, "==> "+printCallerNameAndLine()) - } - return a, nil -} - -func Wrap3[T any, V any](a T, b V, err error) (T, V, error) { - if err != nil { - return a, b, errors.Wrap(err, "==> "+printCallerNameAndLine()) - } - return a, b, nil -} - -func Wrap(err error, message string) error { - return errors.Wrap(err, "==> "+printCallerNameAndLine()+message) -} - -func WithMessage(err error, message string) error { - return errors.WithMessage(err, "==> "+printCallerNameAndLine()+message) -} - -func printCallerNameAndLine() string { - pc, _, line, _ := runtime.Caller(2) - return runtime.FuncForPC(pc).Name() + "()@" + strconv.Itoa(line) + ": " -} - -func GetSelfFuncName() string { - pc, _, _, _ := runtime.Caller(1) - return cleanUpFuncName(runtime.FuncForPC(pc).Name()) -} - -func GetFuncName(skips ...int) string { - skip := 1 - if len(skips) > 0 { - skip = skips[0] + 1 - } - pc, _, _, _ := runtime.Caller(skip) - return cleanUpFuncName(runtime.FuncForPC(pc).Name()) -} - -func cleanUpFuncName(funcName string) string { - end := strings.LastIndex(funcName, ".") - if end == -1 { - return "" - } - return funcName[end+1:] -} - -// Get the intersection of two slices -func Intersect(slice1, slice2 []int64) []int64 { - m := make(map[int64]bool) - n := make([]int64, 0) - for _, v := range slice1 { - m[v] = true - } - for _, v := range slice2 { - flag, _ := m[v] - if flag { - n = append(n, v) - } - } - return n -} - -// Get the diff of two slices -func Difference(slice1, slice2 []int64) []int64 { - m := make(map[int64]bool) - n := make([]int64, 0) - inter := Intersect(slice1, slice2) - for _, v := range inter { - m[v] = true - } - for _, v := range slice1 { - if !m[v] { - n = append(n, v) - } - } - - for _, v := range slice2 { - if !m[v] { - n = append(n, v) - } - } - return n -} - -// Get the intersection of two slices -func IntersectString(slice1, slice2 []string) []string { - m := make(map[string]bool) - n := make([]string, 0) - for _, v := range slice1 { - m[v] = true - } - for _, v := range slice2 { - flag, _ := m[v] - if flag { - n = append(n, v) - } - } - return n -} - -// Get the diff of two slices -func DifferenceString(slice1, slice2 []string) []string { - m := make(map[string]bool) - n := make([]string, 0) - inter := IntersectString(slice1, slice2) - for _, v := range inter { - m[v] = true - } - for _, v := range slice1 { - if !m[v] { - n = append(n, v) - } - } - - for _, v := range slice2 { - if !m[v] { - n = append(n, v) - } - } - return n -} - -func OperationIDGenerator() string { - return strconv.FormatInt(time.Now().UnixNano()+int64(rand.Uint32()), 10) -} - -func GetHashCode(s string) uint32 { - return crc32.ChecksumIEEE([]byte(s)) -} - -func GenConversationIDForSingle(sendID, recvID string) string { - l := []string{sendID, recvID} - sort.Strings(l) - return "si_" + strings.Join(l, "_") -} - -func GenConversationUniqueKeyForGroup(groupID string) string { - return groupID -} - -func GenGroupConversationID(groupID string) string { - return "sg_" + groupID -} - -func GenConversationUniqueKeyForSingle(sendID, recvID string) string { - l := []string{sendID, recvID} - sort.Strings(l) - return strings.Join(l, "_") -} - -func GetNotificationConversationIDByConversationID(conversationID string) string { - l := strings.Split(conversationID, "_") - if len(l) > 1 { - l[0] = "n" - return strings.Join(l, "_") - } - return "" -} - -func GetSelfNotificationConversationID(userID string) string { - return "n_" + userID + "_" + userID -} - -func GetSeqsBeginEnd(seqs []int64) (int64, int64) { - if len(seqs) == 0 { - return 0, 0 - } - return seqs[0], seqs[len(seqs)-1] -} diff --git a/zktools/utils/utils_v2.go b/zktools/utils/utils_v2.go deleted file mode 100644 index 6522a9e36..000000000 --- a/zktools/utils/utils_v2.go +++ /dev/null @@ -1,604 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "encoding/json" - "reflect" - "sort" -) - -// SliceSub a中存在,b中不存在 (a-b) -func SliceSub[E comparable](a, b []E) []E { - k := make(map[E]struct{}) - for i := 0; i < len(b); i++ { - k[b[i]] = struct{}{} - } - t := make(map[E]struct{}) - rs := make([]E, 0, len(a)) - for i := 0; i < len(a); i++ { - e := a[i] - if _, ok := t[e]; ok { - continue - } - if _, ok := k[e]; ok { - continue - } - rs = append(rs, e) - t[e] = struct{}{} - } - return rs -} - -// SliceSubAny a中存在,b中不存在 (a-b) -func SliceSubAny[E comparable, T any](a []E, b []T, fn func(t T) E) []E { - return SliceSub(a, Slice(b, fn)) -} - -// SliceAnySub a中存在,b中不存在 (a-b) fn 返回的是uuid -func SliceAnySub[E any, T comparable](a, b []E, fn func(t E) T) []E { - m := make(map[T]E) - for i := 0; i < len(b); i++ { - v := b[i] - m[fn(v)] = v - } - var es []E - for i := 0; i < len(a); i++ { - v := a[i] - if _, ok := m[fn(v)]; !ok { - es = append(es, v) - } - } - return es -} - -// DistinctAny 去重 -func DistinctAny[E any, K comparable](es []E, fn func(e E) K) []E { - v := make([]E, 0, len(es)) - tmp := map[K]struct{}{} - for i := 0; i < len(es); i++ { - t := es[i] - k := fn(t) - if _, ok := tmp[k]; !ok { - tmp[k] = struct{}{} - v = append(v, t) - } - } - return v -} - -func DistinctAnyGetComparable[E any, K comparable](es []E, fn func(e E) K) []K { - v := make([]K, 0, len(es)) - tmp := map[K]struct{}{} - for i := 0; i < len(es); i++ { - t := es[i] - k := fn(t) - if _, ok := tmp[k]; !ok { - tmp[k] = struct{}{} - v = append(v, k) - } - } - return v -} - -// Distinct 去重 -func Distinct[T comparable](ts []T) []T { - if len(ts) < 2 { - return ts - } else if len(ts) == 2 { - if ts[0] == ts[1] { - return ts[:1] - } else { - return ts - } - } - return DistinctAny(ts, func(t T) T { - return t - }) -} - -// Delete 删除切片元素, 支持负数删除倒数第几个 -func Delete[E any](es []E, index ...int) []E { - switch len(index) { - case 0: - return es - case 1: - i := index[0] - if i < 0 { - i = len(es) + i - } - if len(es) <= i { - return es - } - return append(es[:i], es[i+1:]...) - default: - tmp := make(map[int]struct{}) - for _, i := range index { - if i < 0 { - i = len(es) + i - } - tmp[i] = struct{}{} - } - v := make([]E, 0, len(es)) - for i := 0; i < len(es); i++ { - if _, ok := tmp[i]; !ok { - v = append(v, es[i]) - } - } - return v - } -} - -// DeleteAt 删除切片元素, 支持负数删除倒数第几个 -func DeleteAt[E any](es *[]E, index ...int) []E { - v := Delete(*es, index...) - *es = v - return v -} - -// IndexAny get the index of the element -func IndexAny[E any, K comparable](e E, es []E, fn func(e E) K) int { - k := fn(e) - for i := 0; i < len(es); i++ { - if fn(es[i]) == k { - return i - } - } - return -1 -} - -// IndexOf get the index of the element -func IndexOf[E comparable](e E, es ...E) int { - return IndexAny(e, es, func(t E) E { - return t - }) -} - -// Contain 是否包含 -func Contain[E comparable](e E, es ...E) bool { - return IndexOf(e, es...) >= 0 -} - -// DuplicateAny 是否有重复的 -func DuplicateAny[E any, K comparable](es []E, fn func(e E) K) bool { - t := make(map[K]struct{}) - for _, e := range es { - k := fn(e) - if _, ok := t[k]; ok { - return true - } - t[k] = struct{}{} - } - return false -} - -// Duplicate 是否有重复的 -func Duplicate[E comparable](es []E) bool { - return DuplicateAny(es, func(e E) E { - return e - }) -} - -// SliceToMapOkAny slice to map (自定义类型, 筛选) -func SliceToMapOkAny[E any, K comparable, V any](es []E, fn func(e E) (K, V, bool)) map[K]V { - kv := make(map[K]V) - for i := 0; i < len(es); i++ { - t := es[i] - if k, v, ok := fn(t); ok { - kv[k] = v - } - } - return kv -} - -// SliceToMapAny slice to map (自定义类型) -func SliceToMapAny[E any, K comparable, V any](es []E, fn func(e E) (K, V)) map[K]V { - return SliceToMapOkAny(es, func(e E) (K, V, bool) { - k, v := fn(e) - return k, v, true - }) -} - -// SliceToMap slice to map -func SliceToMap[E any, K comparable](es []E, fn func(e E) K) map[K]E { - return SliceToMapOkAny(es, func(e E) (K, E, bool) { - k := fn(e) - return k, e, true - }) -} - -// SliceSetAny slice to map[K]struct{} -func SliceSetAny[E any, K comparable](es []E, fn func(e E) K) map[K]struct{} { - return SliceToMapAny(es, func(e E) (K, struct{}) { - return fn(e), struct{}{} - }) -} - -func Filter[E, T any](es []E, fn func(e E) (T, bool)) []T { - rs := make([]T, 0, len(es)) - for i := 0; i < len(es); i++ { - e := es[i] - if t, ok := fn(e); ok { - rs = append(rs, t) - } - } - return rs -} - -// Slice 批量转换切片类型 -func Slice[E any, T any](es []E, fn func(e E) T) []T { - v := make([]T, len(es)) - for i := 0; i < len(es); i++ { - v[i] = fn(es[i]) - } - return v -} - -// SliceSet slice to map[E]struct{} -func SliceSet[E comparable](es []E) map[E]struct{} { - return SliceSetAny(es, func(e E) E { - return e - }) -} - -// HasKey get whether the map contains key -func HasKey[K comparable, V any](m map[K]V, k K) bool { - if m == nil { - return false - } - _, ok := m[k] - return ok -} - -// Min get minimum value -func Min[E Ordered](e ...E) E { - v := e[0] - for _, t := range e[1:] { - if v > t { - v = t - } - } - return v -} - -// Max get maximum value -func Max[E Ordered](e ...E) E { - v := e[0] - for _, t := range e[1:] { - if v < t { - v = t - } - } - return v -} - -func Paginate[E any](es []E, pageNumber int, showNumber int) []E { - if pageNumber <= 0 { - return []E{} - } - if showNumber <= 0 { - return []E{} - } - start := (pageNumber - 1) * showNumber - end := start + showNumber - if start >= len(es) { - return []E{} - } - if end > len(es) { - end = len(es) - } - return es[start:end] -} - -// BothExistAny 获取切片中共同存在的元素(交集) -func BothExistAny[E any, K comparable](es [][]E, fn func(e E) K) []E { - if len(es) == 0 { - return []E{} - } - var idx int - ei := make([]map[K]E, len(es)) - for i := 0; i < len(ei); i++ { - e := es[i] - if len(e) == 0 { - return []E{} - } - kv := make(map[K]E) - for j := 0; j < len(e); j++ { - t := e[j] - k := fn(t) - kv[k] = t - } - ei[i] = kv - if len(kv) < len(ei[idx]) { - idx = i - } - } - v := make([]E, 0, len(ei[idx])) - for k := range ei[idx] { - all := true - for i := 0; i < len(ei); i++ { - if i == idx { - continue - } - if _, ok := ei[i][k]; !ok { - all = false - break - } - } - if !all { - continue - } - v = append(v, ei[idx][k]) - } - return v -} - -// BothExist 获取切片中共同存在的元素(交集) -func BothExist[E comparable](es ...[]E) []E { - return BothExistAny(es, func(e E) E { - return e - }) -} - -//// CompleteAny a中存在b的所有元素, 同时b中的所有元素a -//func CompleteAny[K comparable, E any](ks []K, es []E, fn func(e E) K) bool { -// if len(ks) == 0 && len(es) == 0 { -// return true -// } -// kn := make(map[K]uint8) -// for _, e := range Distinct(ks) { -// kn[e]++ -// } -// for k := range SliceSetAny(es, fn) { -// kn[k]++ -// } -// for _, n := range kn { -// if n != 2 { -// return false -// } -// } -// return true -//} - -// Complete a和b去重后是否相等(忽略顺序) -func Complete[E comparable](a []E, b []E) bool { - return len(Single(a, b)) == 0 -} - -// Keys get map keys -func Keys[K comparable, V any](kv map[K]V) []K { - ks := make([]K, 0, len(kv)) - for k := range kv { - ks = append(ks, k) - } - return ks -} - -// Values get map values -func Values[K comparable, V any](kv map[K]V) []V { - vs := make([]V, 0, len(kv)) - for k := range kv { - vs = append(vs, kv[k]) - } - return vs -} - -// Sort basic type sorting -func Sort[E Ordered](es []E, asc bool) []E { - SortAny(es, func(a, b E) bool { - if asc { - return a < b - } else { - return a > b - } - }) - return es -} - -// SortAny custom sort method -func SortAny[E any](es []E, fn func(a, b E) bool) { - sort.Sort(&sortSlice[E]{ - ts: es, - fn: fn, - }) -} - -// If true -> a, false -> b -func If[T any](isa bool, a, b T) T { - if isa { - return a - } - return b -} - -func ToPtr[T any](t T) *T { - return &t -} - -// Equal 比较切片是否相对(包括元素顺序) -func Equal[E comparable](a []E, b []E) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - return true -} - -// Single a中存在,b中不存在 或 b中存在,a中不存在 -func Single[E comparable](a, b []E) []E { - kn := make(map[E]uint8) - for _, e := range Distinct(a) { - kn[e]++ - } - for _, e := range Distinct(b) { - kn[e]++ - } - v := make([]E, 0, len(kn)) - for k, n := range kn { - if n == 1 { - v = append(v, k) - } - } - return v -} - -// Order 将ts按es排序 -func Order[E comparable, T any](es []E, ts []T, fn func(t T) E) []T { - if len(es) == 0 || len(ts) == 0 { - return ts - } - kv := make(map[E][]T) - for i := 0; i < len(ts); i++ { - t := ts[i] - k := fn(t) - kv[k] = append(kv[k], t) - } - rs := make([]T, 0, len(ts)) - for _, e := range es { - vs := kv[e] - delete(kv, e) - rs = append(rs, vs...) - } - for k := range kv { - rs = append(rs, kv[k]...) - } - return rs -} - -func OrderPtr[E comparable, T any](es []E, ts *[]T, fn func(t T) E) []T { - *ts = Order(es, *ts, fn) - return *ts -} - -func UniqueJoin(s ...string) string { - data, _ := json.Marshal(s) - return string(data) -} - -type sortSlice[E any] struct { - ts []E - fn func(a, b E) bool -} - -func (o *sortSlice[E]) Len() int { - return len(o.ts) -} - -func (o *sortSlice[E]) Less(i, j int) bool { - return o.fn(o.ts[i], o.ts[j]) -} - -func (o *sortSlice[E]) Swap(i, j int) { - o.ts[i], o.ts[j] = o.ts[j], o.ts[i] -} - -// Ordered types that can be sorted -type Ordered interface { - ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string -} - -func Unwrap(err error) error { - for err != nil { - unwrap, ok := err.(interface { - Unwrap() error - }) - if !ok { - break - } - err = unwrap.Unwrap() - } - return err -} - -// NotNilReplace 当new_不为空时, 将old设置为new_ -func NotNilReplace[T any](old, new_ *T) { - if new_ == nil { - return - } - *old = *new_ -} - -func StructFieldNotNilReplace(dest, src interface{}) { - destVal := reflect.ValueOf(dest).Elem() - srcVal := reflect.ValueOf(src).Elem() - - for i := 0; i < destVal.NumField(); i++ { - destField := destVal.Field(i) - srcField := srcVal.Field(i) - - // Check if the source field is valid - if srcField.IsValid() { - // Check if the target field can be set - if destField.CanSet() { - // Handling fields of slice type - if destField.Kind() == reflect.Slice && srcField.Kind() == reflect.Slice { - elemType := destField.Type().Elem() - // Check if a slice element is a pointer to a structure - if elemType.Kind() == reflect.Ptr && elemType.Elem().Kind() == reflect.Struct { - // Create a new slice to store the copied elements - newSlice := reflect.MakeSlice(destField.Type(), srcField.Len(), srcField.Cap()) - for j := 0; j < srcField.Len(); j++ { - newElem := reflect.New(elemType.Elem()) - // Recursive update, retaining non-zero values - StructFieldNotNilReplace(newElem.Interface(), srcField.Index(j).Interface()) - // Checks if the field of the new element is zero-valued, and if so, preserves the value at the corresponding position in the original slice - for k := 0; k < newElem.Elem().NumField(); k++ { - if newElem.Elem().Field(k).IsZero() { - newElem.Elem().Field(k).Set(destField.Index(j).Elem().Field(k)) - } - } - newSlice.Index(j).Set(newElem) - } - destField.Set(newSlice) - } else { - destField.Set(srcField) - } - } else { - // For non-sliced fields, update the source field if it is non-zero, otherwise keep the original value - if !srcField.IsZero() { - destField.Set(srcField) - } - } - } - } - } -} - -func Batch[T any, V any](fn func(T) V, ts []T) []V { - if ts == nil { - return nil - } - res := make([]V, 0, len(ts)) - for i := range ts { - res = append(res, fn(ts[i])) - } - return res -} - -func InitSlice[T any](val *[]T) { - if val != nil && *val == nil { - *val = []T{} - } -} - -func InitMap[K comparable, V any](val *map[K]V) { - if val != nil && *val == nil { - *val = map[K]V{} - } -} diff --git a/zktools/utils/utils_v2_test.go b/zktools/utils/utils_v2_test.go deleted file mode 100644 index fd625745f..000000000 --- a/zktools/utils/utils_v2_test.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright © 2023 OpenIM. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package utils - -import ( - "fmt" - "reflect" - "testing" -) - -func TestDistinct(t *testing.T) { - arr := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - fmt.Println(Distinct(arr)) -} - -func TestDeleteAt(t *testing.T) { - arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - fmt.Println(Delete(arr, 0, 1, -1, -2)) - fmt.Println(Delete(arr)) - fmt.Println(Delete(arr, 1)) -} - -func TestSliceToMap(t *testing.T) { - type Item struct { - ID string - Name string - } - list := []Item{ - {ID: "111", Name: "111"}, - {ID: "222", Name: "222"}, - {ID: "333", Name: "333"}, - } - - m := SliceToMap(list, func(t Item) string { - return t.ID - }) - - fmt.Printf("%+v\n", m) - -} - -func TestIndexOf(t *testing.T) { - arr := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - - fmt.Println(IndexOf(3, arr...)) - -} - -func TestSort(t *testing.T) { - arr := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - fmt.Println(Sort(arr, false)) -} - -func TestBothExist(t *testing.T) { - arr1 := []int{1, 1, 1, 4, 4, 5, 2, 3, 3, 3, 6} - arr2 := []int{6, 1, 3} - arr3 := []int{5, 1, 3, 6} - fmt.Println(BothExist(arr1, arr2, arr3)) -} - -func TestCompleteAny(t *testing.T) { - type Item struct { - ID int - Value string - } - - ids := []int{1, 2, 3, 4, 5, 6, 7, 8} - - var list []Item - - for _, id := range ids { - list = append(list, Item{ - ID: id, - Value: fmt.Sprintf("%d", id*1000), - }) - } - - DeleteAt(&list, -1) - DeleteAt(&ids, -1) - - ok := Complete(ids, Slice(list, func(t Item) int { - return t.ID - })) - - fmt.Printf("%+v\n", ok) -} - -func TestStructFieldNotNilReplace(t *testing.T) { - type Req struct { - GroupID string `json:"groupID"` - GroupName string `json:"groupName"` - Notification string `json:"notification"` - Introduction string `json:"introduction"` - Count int64 `json:"faceURL"` - OwnerUserID string `json:"ownerUserID"` - } - - tests := []struct { - name string - req Req - resp Req - want Req - }{ - { - name: "One by one conversion", - req: Req{ - GroupID: "groupID", - GroupName: "groupName", - Notification: "notification", - Introduction: "introduction", - Count: 123, - OwnerUserID: "ownerUserID", - }, - resp: Req{ - GroupID: "ID", - GroupName: "Name", - Notification: "notification", - Introduction: "introduction", - Count: 456, - OwnerUserID: "ownerUserID", - }, - want: Req{ - GroupID: "groupID", - GroupName: "groupName", - Notification: "notification", - Introduction: "introduction", - Count: 123, - OwnerUserID: "ownerUserID", - }, - }, - { - name: "Changing the values of some fields", - req: Req{ - GroupID: "groupID", - GroupName: "groupName", - Notification: "", - Introduction: "", - Count: 123, - OwnerUserID: "ownerUserID", - }, - resp: Req{ - GroupID: "ID", - GroupName: "Name", - Notification: "notification", - Introduction: "introduction", - Count: 456, - OwnerUserID: "ownerUserID", - }, - want: Req{ - GroupID: "groupID", - GroupName: "groupName", - Notification: "notification", - Introduction: "introduction", - Count: 123, - OwnerUserID: "ownerUserID", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - StructFieldNotNilReplace(&tt.resp, &tt.req) - fmt.Println(tt.resp) - if !reflect.DeepEqual(tt.want, tt.resp) { - t.Errorf("%v have a err,%v", tt.name, tt.want) - } - }) - } - - type Req11 struct { - GroupID *string `json:"groupID"` - GroupName *string `json:"groupName"` - Notification *string `json:"notification"` - Introduction *string `json:"introduction"` - Count *int64 `json:"faceURL"` - OwnerUserID *string `json:"ownerUserID"` - } - - type Req1 struct { - Re []*Req - Re1 *Req - Re2 Req11 - } - r := Req{ - GroupID: "groupID1", - GroupName: "groupName2", - Notification: "1", - Introduction: "1", - Count: 123, - OwnerUserID: "ownerUserID1", - } - tests1 := []struct { - name string - req Req1 - resp Req1 - want Req1 - }{ - { - name: "name", - req: Req1{ - Re: []*Req{ - { - GroupID: "groupID1", - GroupName: "groupName2", - Notification: "1", - Introduction: "1", - Count: 123, - OwnerUserID: "ownerUserID1", - }, - { - GroupID: "groupID2", - GroupName: "groupName2", - Notification: "2", - Introduction: "2", - Count: 456, - OwnerUserID: "ownerUserID2", - }, - }, - Re1: &r, - Re2: Req11{ - GroupID: &r.GroupID, - GroupName: &r.GroupName, - Notification: &r.Notification, - Introduction: &r.Introduction, - Count: &r.Count, - OwnerUserID: &r.OwnerUserID, - }, - }, - resp: Req1{}, - want: Req1{ - Re: []*Req{ - { - GroupID: "groupID1", - GroupName: "groupName2", - Notification: "1", - Introduction: "1", - Count: 123, - OwnerUserID: "ownerUserID1", - }, - { - GroupID: "groupID2", - GroupName: "groupName2", - Notification: "2", - Introduction: "2", - Count: 456, - OwnerUserID: "ownerUserID2", - }, - }, - Re1: &r, - Re2: Req11{ - GroupID: &r.GroupID, - GroupName: &r.GroupName, - Notification: &r.Notification, - Introduction: &r.Introduction, - Count: &r.Count, - OwnerUserID: &r.OwnerUserID, - }, - }, - }, - } - for _, tt := range tests1 { - t.Run(tt.name, func(t *testing.T) { - StructFieldNotNilReplace(&tt.resp, &tt.req) - fmt.Println(tt.resp) - if !reflect.DeepEqual(tt.want, tt.resp) { - t.Errorf("%v have a err,%v", tt.name, tt.want) - } - }) - } - -}