diff --git a/.licenserc.json b/.licenserc.json index 87cb298..89bcc2d 100644 --- a/.licenserc.json +++ b/.licenserc.json @@ -1,5 +1,9 @@ { "**/*.go": "// Copyright 2021 ecodeclub", "**/*.{yml}": "# Copyright 2021 ecodeclub", - "**/*.sh": "# Copyright 2021 ecodeclub" + "**/*.sh": "# Copyright 2021 ecodeclub", + + "ignore": [ + "mocks" + ] } \ No newline at end of file diff --git a/channel/email/email.go b/channel/email/email.go index ba1ebe7..ce69a13 100644 --- a/channel/email/email.go +++ b/channel/email/email.go @@ -17,9 +17,12 @@ package email import ( "context" "crypto/tls" + "fmt" "net" "net/smtp" + "github.com/ecodeclub/notify-go/pkg/log" + "github.com/ecodeclub/ekit/slice" "github.com/ecodeclub/notify-go/pkg/notifier" "github.com/jordan-wright/email" @@ -58,7 +61,10 @@ func NewEmailChannel(cfg Config) *ChannelEmailImpl { } func (c *ChannelEmailImpl) Execute(ctx context.Context, deli notifier.Delivery) error { - var err error + var ( + err error + logger = log.FromContext(ctx) + ) msgContent := c.initEmailContent(deli.Content) c.email.To = slice.Map[notifier.Receiver, string](deli.Receivers, func(idx int, src notifier.Receiver) string { @@ -72,6 +78,7 @@ func (c *ChannelEmailImpl) Execute(ctx context.Context, deli notifier.Delivery) c.email.HTML = []byte(msgContent.Html) c.email.Text = []byte(msgContent.Text) + logger.Info("email execute", "params", fmt.Sprintf("to[%v], from[%s]", c.email.To, c.email.From)) ch := make(chan struct{}) go func() { defer func() { @@ -85,9 +92,11 @@ func (c *ChannelEmailImpl) Execute(ctx context.Context, deli notifier.Delivery) select { case <-ctx.Done(): err = ctx.Err() + logger.Error("email execute err", "err", err.Error()) case <-ch: if err != nil { err = errors.Wrap(err, "failed to send mail") + logger.Error("email execute err", "err", err.Error()) } } diff --git a/channel/push/push.go b/channel/push/push.go index b1ccba6..7bd52f2 100644 --- a/channel/push/push.go +++ b/channel/push/push.go @@ -21,6 +21,8 @@ import ( "strconv" "time" + "github.com/ecodeclub/notify-go/pkg/log" + "github.com/ecodeclub/ekit/slice" "github.com/ecodeclub/notify-go/pkg/notifier" "github.com/ecodeclub/notify-go/pkg/ral" @@ -81,6 +83,8 @@ func NewPushChannel(c Config, client ral.Client) *ChannelPushImpl { } func (pc *ChannelPushImpl) Execute(ctx context.Context, deli notifier.Delivery) error { + var logger = log.FromContext(ctx) + token, err := pc.getToken(ctx) if err != nil { return err @@ -110,6 +114,7 @@ func (pc *ChannelPushImpl) Execute(ctx context.Context, deli notifier.Delivery) var resp map[string]any err = pc.client.Ral(ctx, "Send", req, &resp, map[string]any{}) + logger.Auto("res", err, "resp", resp) return err } @@ -118,7 +123,11 @@ func (pc *ChannelPushImpl) Name() string { } func (pc *ChannelPushImpl) getToken(ctx context.Context) (token string, err error) { + var logger = log.FromContext(ctx) + ts, sign := pc.getSign() + logger.Debug("get sign", "timestamp", ts, "sign", sign) + req := ral.Request{ Header: map[string]string{"content-type": "application/json;charset=utf-8"}, Body: map[string]interface{}{ @@ -140,6 +149,8 @@ func (pc *ChannelPushImpl) getToken(ctx context.Context) (token string, err erro if !ok { err = errors.New("[push] 获取token失败") } + + logger.Debug("get token", "token", token) return } diff --git a/go.mod b/go.mod index a8ec322..2d4f534 100644 --- a/go.mod +++ b/go.mod @@ -7,10 +7,14 @@ require ( github.com/IBM/sarama v1.41.1 github.com/ecodeclub/ekit v0.0.8 github.com/go-resty/resty/v2 v2.7.0 + github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75 github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatible github.com/kevinburke/twilio-go v0.0.0-20221122012537-65f3dd7539e2 github.com/pborman/uuid v1.2.0 github.com/pkg/errors v0.8.1 + github.com/stretchr/testify v1.8.4 + go.uber.org/mock v0.3.0 + moul.io/http2curl v1.0.0 xorm.io/xorm v1.3.2 ) @@ -41,7 +45,9 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pierrec/lz4/v4 v4.1.18 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/syndtr/goleveldb v1.0.0 // indirect github.com/ttacon/builder v0.0.0-20170518171403-c099f663e1c2 // indirect github.com/ttacon/libphonenumber v1.2.1 // indirect @@ -50,5 +56,6 @@ require ( golang.org/x/sync v0.3.0 // indirect golang.org/x/text v0.12.0 // indirect google.golang.org/protobuf v1.26.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect ) diff --git a/go.sum b/go.sum index 9e2e216..b258ea6 100644 --- a/go.sum +++ b/go.sum @@ -125,7 +125,10 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75 h1:f0n1xnMSmBLzVfsMMvriDyA75NB/oBgILX2GcHXIQzY= +github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75/go.mod h1:g2644b03hfBX9Ov0ZBDgXXens4rxSxmqFBbhvKv2yVA= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= @@ -234,6 +237,7 @@ github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/u github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= 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/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= @@ -252,9 +256,13 @@ github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxv github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= @@ -360,6 +368,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6O github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +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/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= @@ -375,7 +385,9 @@ github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeV github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= @@ -422,6 +434,8 @@ go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= +go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= @@ -458,8 +472,8 @@ golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKG golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= 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= -golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= +golang.org/x/mod v0.11.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -596,6 +610,8 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= @@ -726,6 +742,8 @@ modernc.org/tcl v1.8.13/go.mod h1:V+q/Ef0IJaNUSECieLU4o+8IScapxnMyFV6i/7uQlAY= modernc.org/token v1.0.0 h1:a0jaWiNMDhDUtqOj09wvjWWAqd3q7WpBulmL9H2egsk= modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= modernc.org/z v1.2.19/go.mod h1:+ZpP0pc4zz97eukOzW3xagV/lS82IpPN9NGG5pNF9vY= +moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8= +moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 h1:bvLlAPW1ZMTWA32LuZMBEGHAUOcATZjzHcotf3SWweM= diff --git a/pkg/iterator/iterator.go b/pkg/iterator/iterator.go new file mode 100644 index 0000000..40f8981 --- /dev/null +++ b/pkg/iterator/iterator.go @@ -0,0 +1,44 @@ +// Copyright 2021 ecodeclub +// +// 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 iterator + +type ListIter[T []E, E any] struct { + val T + length int + index int +} + +var _ Iterable[any] = &ListIter[[]any, any]{} + +func (it *ListIter[T, E]) Next() (E, bool) { + var e E + if it.index >= it.length { + return e, true + } + res := it.val[it.index] + it.index++ + return res, false +} + +func NewListIter[T []E, E any](array T) *ListIter[T, E] { + if array == nil { + return &ListIter[T, E]{} + } + return &ListIter[T, E]{ + val: array, + length: len(array), + index: 0, + } +} diff --git a/pkg/iterator/iterator_test.go b/pkg/iterator/iterator_test.go new file mode 100644 index 0000000..154b3cf --- /dev/null +++ b/pkg/iterator/iterator_test.go @@ -0,0 +1,61 @@ +// Copyright 2021 ecodeclub +// +// 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 iterator + +import ( + "reflect" + "testing" +) + +type MyStr string + +func equal[T []E, E any](t *testing.T, it *ListIter[T, E], want T) { + res := make([]E, 0, 10) + for { + got, done := it.Next() + if done { + break + } + res = append(res, got) + } + if !reflect.DeepEqual(res, want) { + t.Errorf("Next() got = %v, want %v", res, want) + } +} + +func TestListIter_Nil(t *testing.T) { + var a []int + lr := NewListIter(a) + want := make([]int, 0, 10) + equal[[]int, int](t, lr, want) +} + +func TestListIter_Empty(t *testing.T) { + lr := NewListIter([]int{}) + want := make([]int, 0, 10) + equal[[]int, int](t, lr, want) +} + +func TestListIter_Base(t *testing.T) { + lr := NewListIter[[]int, int]([]int{1, 2, 3, 4}) + want := []int{1, 2, 3, 4} + equal[[]int, int](t, lr, want) +} + +func TestListIter_TypeAlias(t *testing.T) { + lr := NewListIter[[]MyStr, MyStr]([]MyStr{"a", "b", "c", "d"}) + want := []MyStr{"a", "b", "c", "d"} + equal[[]MyStr, MyStr](t, lr, want) +} diff --git a/pkg/iterator/type.go b/pkg/iterator/type.go new file mode 100644 index 0000000..f9e99f3 --- /dev/null +++ b/pkg/iterator/type.go @@ -0,0 +1,19 @@ +// Copyright 2021 ecodeclub +// +// 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 iterator + +type Iterable[T any] interface { + Next() (T, bool) +} diff --git a/pkg/log/log.go b/pkg/log/log.go index 122f782..fb34cfa 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -16,21 +16,79 @@ package log import ( "context" + "io" "log/slog" + "os" + + "github.com/pborman/uuid" ) -type ContextLogKey struct{} +type ( + ContextLogKey struct{} + LogIDKey struct{} +) -func FromContext(ctx context.Context) *slog.Logger { - if l, ok := ctx.Value(ContextLogKey{}).(*slog.Logger); ok { +func FromContext(ctx context.Context) *Logger { + if l, ok := ctx.Value(ContextLogKey{}).(*Logger); ok { return l } - return slog.Default() + return Default() +} + +type Logger struct { + *slog.Logger +} + +func Default() *Logger { + l := newLogger(os.Stdout, slog.LevelInfo) + l.Logger = l.Logger.With("LOGID", uuid.NewUUID().String()) + return l +} + +func New() *Logger { + return newLogger(os.Stdout, slog.LevelInfo) +} + +func newLogger(w io.Writer, level slog.Level) *Logger { + l := &Logger{ + Logger: slog.New( + slog.NewTextHandler(w, &slog.HandlerOptions{ + AddSource: false, + Level: level, + }), + ), + } + return l } -func WithContext(ctx context.Context, l *slog.Logger) context.Context { - if _, ok := ctx.Value(ContextLogKey{}).(*slog.Logger); ok { +func (l *Logger) WithContext(ctx context.Context) context.Context { + if _, ok := ctx.Value(ContextLogKey{}).(*Logger); ok { return ctx } return context.WithValue(ctx, ContextLogKey{}, l) } + +func (l *Logger) Auto(msg string, err error, args ...any) { + if err != nil { + l.Error(msg, append(args, "err", err.Error())...) + return + } + l.Info(msg, append(args, "err", nil)...) +} + +func (l *Logger) WithFields(args ...any) *Logger { + return &Logger{Logger: l.Logger.With(args...)} +} + +func (l *Logger) WithLogID(ctx context.Context) *Logger { + var ( + logId string + ok bool + ) + logId, ok = ctx.Value(LogIDKey{}).(string) + if !ok { + logId = uuid.NewUUID().String() + } + + return &Logger{Logger: l.Logger.With("LOGID", logId)} +} diff --git a/pkg/notifier/channel.go b/pkg/notifier/channel.go index 94b23df..61e25ef 100644 --- a/pkg/notifier/channel.go +++ b/pkg/notifier/channel.go @@ -22,6 +22,7 @@ type Delivery struct { Content Content } +//go:generate mockgen -package=mocks -destination=mocks/channel.mock.go -source=channel.go IChannel type IChannel interface { Name() string Execute(ctx context.Context, deli Delivery) error diff --git a/pkg/notifier/content.go b/pkg/notifier/content.go index 7797d99..f994957 100644 --- a/pkg/notifier/content.go +++ b/pkg/notifier/content.go @@ -17,6 +17,7 @@ package notifier type Content struct { Title string Data []byte + // push使用 ClickType string URL string diff --git a/pkg/notifier/mocks/channel.mock.go b/pkg/notifier/mocks/channel.mock.go new file mode 100644 index 0000000..6eead85 --- /dev/null +++ b/pkg/notifier/mocks/channel.mock.go @@ -0,0 +1,68 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: channel.go +// +// Generated by this command: +// +// mockgen -package=mocks -destination=mocks/channel.mock.go -source=channel.go IChannel +// +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + notifier "github.com/ecodeclub/notify-go/pkg/notifier" + gomock "go.uber.org/mock/gomock" +) + +// MockIChannel is a mock of IChannel interface. +type MockIChannel struct { + ctrl *gomock.Controller + recorder *MockIChannelMockRecorder +} + +// MockIChannelMockRecorder is the mock recorder for MockIChannel. +type MockIChannelMockRecorder struct { + mock *MockIChannel +} + +// NewMockIChannel creates a new mock instance. +func NewMockIChannel(ctrl *gomock.Controller) *MockIChannel { + mock := &MockIChannel{ctrl: ctrl} + mock.recorder = &MockIChannelMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockIChannel) EXPECT() *MockIChannelMockRecorder { + return m.recorder +} + +// Execute mocks base method. +func (m *MockIChannel) Execute(ctx context.Context, deli notifier.Delivery) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Execute", ctx, deli) + ret0, _ := ret[0].(error) + return ret0 +} + +// Execute indicates an expected call of Execute. +func (mr *MockIChannelMockRecorder) Execute(ctx, deli any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockIChannel)(nil).Execute), ctx, deli) +} + +// Name mocks base method. +func (m *MockIChannel) Name() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Name") + ret0, _ := ret[0].(string) + return ret0 +} + +// Name indicates an expected call of Name. +func (mr *MockIChannelMockRecorder) Name() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockIChannel)(nil).Name)) +} diff --git a/pkg/ral/ral.go b/pkg/ral/ral.go index b295e00..0dcf4ad 100644 --- a/pkg/ral/ral.go +++ b/pkg/ral/ral.go @@ -17,58 +17,101 @@ package ral import ( "context" "fmt" + "net/http" + "github.com/ecodeclub/ekit/bean/option" + "github.com/ecodeclub/ekit/slice" "github.com/ecodeclub/notify-go/pkg/log" "github.com/go-resty/resty/v2" "github.com/pkg/errors" + "moul.io/http2curl" ) +type File resty.File + type Client struct { Service Resource + Debug bool } -func NewClient(service Resource) Client { - return Client{service} +func WithDebug(debug bool) option.Option[Client] { + return func(t *Client) { + t.Debug = debug + } } type Request struct { - Header map[string]string - Query map[string]string - Body any - PathParams map[string]string - AuthScheme string - AuthToken string + Header map[string]string + Query map[string]string + Body any + FormData map[string]string + PathParams map[string]string + UploadFiles []File + UploadFilePath map[string]string + AuthScheme string + AuthToken string + BasicUserName string + BasicPassword string +} + +func NewClient(service Resource, opts ...option.Option[Client]) Client { + c := Client{Service: service} + option.Apply[Client](&c, opts...) + return c } -func (c Client) Ral(ctx context.Context, name string, req Request, respSucc any, respFail any) error { +func (c Client) Ral(ctx context.Context, name string, req Request, respSuc any, respFail any) error { var lr = NewLogRecord() logger := log.FromContext(ctx) defer lr.Flush(logger) - intf, ok := c.getUrl(name) + urlInfo, ok := slice.Find[Interface](c.Service.Interface, func(src Interface) bool { + return src.Name == name + }) if !ok { return errors.New("[ral] 获取接口配置失败") } - lr.Host = intf.Host - lr.Port = intf.Port + lr.Host = urlInfo.Host + lr.Port = urlInfo.Port lr.Protocol = c.Service.Protocol - lr.Url = intf.URL - lr.Method = intf.Method + lr.Url = urlInfo.URL + lr.Method = urlInfo.Method - rc := resty.New().EnableTrace().SetRetryCount(c.Service.Retry) - rc.SetBaseURL(fmt.Sprintf("%s://%s:%s", c.Service.Protocol, intf.Host, intf.Port)) + rc := resty.New().EnableTrace().SetDebug(c.Debug).SetRetryCount(c.Service.Retry) + rc.SetPreRequestHook( + func(client *resty.Client, request *http.Request) error { + command, err := http2curl.GetCurlCommand(request) + logger.Info("", "curl", command) + lr.CurlCmd = command.String() + return err + }) + rc.SetBaseURL(fmt.Sprintf("%s://%s:%s", c.Service.Protocol, urlInfo.Host, urlInfo.Port)) client := rc.R().SetContext(ctx). SetHeaders(req.Header). SetQueryParams(req.Query). - SetBody(req.Body). - SetResult(respSucc). + SetBody(req.Body). // json data + SetFormData(req.FormData). // form data + SetResult(respSuc). SetError(respFail). SetPathParams(req.PathParams). - SetAuthScheme(req.AuthScheme).SetAuthToken(req.AuthToken) + SetAuthScheme(req.AuthScheme).SetAuthToken(req.AuthToken). + SetBasicAuth(req.BasicUserName, req.BasicPassword) + + //通过文件流上传 + if len(req.UploadFiles) != 0 { + for _, f := range req.UploadFiles { + client.SetFileReader(f.ParamName, f.Name, f.Reader) + } + } - rsp, err := client.Execute(intf.Method, intf.URL) + //通过文件path上传 + if req.UploadFilePath != nil { + client.SetFiles(req.UploadFilePath) + } + + rsp, err := client.Execute(urlInfo.Method, urlInfo.URL) lr.RspCode = rsp.StatusCode() lr.Error = rsp.Error() @@ -83,13 +126,3 @@ func (c Client) Ral(ctx context.Context, name string, req Request, respSucc any, return err } - -func (c Client) getUrl(name string) (Interface, bool) { - intf := Interface{} - for _, it := range c.Service.Interface { - if it.Name == name { - return it, true - } - } - return intf, false -} diff --git a/pkg/ral/record.go b/pkg/ral/record.go index 01c4882..f991cf4 100644 --- a/pkg/ral/record.go +++ b/pkg/ral/record.go @@ -19,6 +19,8 @@ import ( "log/slog" "sync" "time" + + "github.com/ecodeclub/notify-go/pkg/log" ) type Record struct { @@ -36,6 +38,7 @@ type Record struct { timeCostPointLock sync.Mutex field map[string]any fieldLock sync.Mutex + CurlCmd string } type StaticsItem struct { @@ -88,7 +91,7 @@ func (s *StaticsItem) GetDuration() time.Duration { return s.StopPoint.Sub(s.StartPoint) } -func (lr *Record) Flush(l *slog.Logger) { +func (lr *Record) Flush(l *log.Logger) { field := make([]any, 0, 16) field = append(field, "code", lr.RspCode, diff --git a/queue/kafka/kafka.go b/queue/kafka/kafka.go index ca6c292..a04aaa9 100644 --- a/queue/kafka/kafka.go +++ b/queue/kafka/kafka.go @@ -17,13 +17,9 @@ package kafka import ( "context" "encoding/json" - "log/slog" - "sync" - "time" - - "github.com/ecodeclub/notify-go/pkg/log" "github.com/IBM/sarama" + "github.com/ecodeclub/notify-go/pkg/log" "github.com/ecodeclub/notify-go/pkg/notifier" ) @@ -67,42 +63,27 @@ func (k *Kafka) Produce(ctx context.Context, c notifier.IChannel, delivery notif config.Producer.Return.Successes = true producer, err := sarama.NewAsyncProducer(k.Config.Hosts, config) if err != nil { - slog.Error("[mq] 创建生产者出错", "err", err) + logger.Error("创建生产者出错", "err", err) + return err } defer producer.AsyncClose() - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - <-producer.Successes() - }() - - wg.Add(1) - go func() { - defer wg.Done() - <-producer.Errors() - }() - // 根据channel类型,和路由策略选取发送的topic topic, err := k.topicBalancer[c.Name()].GetNext() if err != nil { - logger.Error("[Producer] choose topic fail", "channel", c.Name(), "err", err) + logger.Error("选择发送topic失败", "channel", c.Name(), "err", err) + return err } // 序列化data data, _ := json.Marshal(delivery) - saramaMsg := &sarama.ProducerMessage{Topic: topic.Name, Key: nil, Value: sarama.ByteEncoder(data)} + producer.Input() <- &sarama.ProducerMessage{Topic: topic.Name, Key: nil, Value: sarama.ByteEncoder(data)} - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*10) select { - case producer.Input() <- saramaMsg: - logger.Info("[mq] 发送消息成功") - case <-ctx.Done(): - logger.Warn("[mq] 发送消息超时") + case <-producer.Successes(): + case msgErr := <-producer.Errors(): + logger.Error("发送kafka消息失败", "msgErr", msgErr) } - cancel() - wg.Wait() return nil } @@ -111,7 +92,7 @@ func (k *Kafka) Consume(ctx context.Context, c notifier.IChannel) { logger := log.FromContext(ctx) consumer, err := k.newConsumer(c.Name()) if err != nil { - logger.Error("[kafka] 消费者启动失败", "err", err) + logger.Error("消费者启动失败", "err", err) } for { @@ -165,7 +146,7 @@ func (k *Kafka) WrapSaramaHandler(ctx context.Context, executor notifier.IChanne } type ConsumeWrapper struct { - logger *slog.Logger + logger *log.Logger Executor notifier.IChannel } @@ -176,7 +157,9 @@ func (c *ConsumeWrapper) ConsumeClaim(session sarama.ConsumerGroupSession, claim if err != nil { c.logger.Error("[consumer] unmarshal task detail fail", "err", err) } - err = c.Executor.Execute(context.TODO(), delivery) + + ctx := c.logger.WithContext(context.Background()) + err = c.Executor.Execute(ctx, delivery) if err != nil { c.logger.Error("[consumer] 执行消息发送失败", "topic", msg.Topic, "partition", msg.Partition, "offset", msg.Offset, "err", err) diff --git a/task.go b/task.go index 79c8f6e..4c5b448 100644 --- a/task.go +++ b/task.go @@ -17,10 +17,19 @@ package notify_go import ( "context" "time" + + "github.com/ecodeclub/notify-go/pkg/log" + + "github.com/ecodeclub/ekit/slice" + "github.com/ecodeclub/notify-go/pkg/iterator" + "github.com/gorhill/cronexpr" ) +// DefaultTask 默认任务 type DefaultTask struct { - Err chan error + Err chan error + HookBefore func() + HookAfter func() *Notification } @@ -28,35 +37,104 @@ type DefaultTask struct { type TriggerTask struct { Err chan error TriggerTime time.Time + HookBefore func() + HookAfter func() *Notification } // CircleTask 循环触发任务 type CircleTask struct { - Err chan error - CircleTime string - Deadline string + IterCronTimes iterator.Iterable[time.Time] + CronExpr string + BeginTime time.Time + EndTime time.Time + HookBefore func() + HookAfter func() + circleNum uint64 + circleFailNum uint64 *Notification } func NewTriggerTask(notification *Notification, t time.Time) *TriggerTask { r := &TriggerTask{ + Err: make(chan error), TriggerTime: t, Notification: notification, + HookBefore: func() {}, + HookAfter: func() {}, } - return r } -func (tt *TriggerTask) Send(ctx context.Context) *TriggerTask { - for { - select { - case <-ctx.Done(): - tt.Err <- ctx.Err() - return tt - case <-time.After(time.Until(tt.TriggerTime)): - err := tt.Notification.Send(ctx) - tt.Err <- err +// Send 一次性任务 +func (tt *TriggerTask) Send(ctx context.Context) { + tt.HookBefore() + defer tt.HookAfter() + + timer := time.After(time.Until(tt.TriggerTime)) + select { + case <-ctx.Done(): + tt.Err <- ctx.Err() + case <-timer: + err := tt.Notification.Send(ctx) + tt.Err <- err + } +} + +func NewCircleTask(notification *Notification, expr string, begin time.Time, end time.Time) *CircleTask { + ct := &CircleTask{ + BeginTime: begin, + EndTime: end, + CronExpr: expr, + HookBefore: func() {}, + HookAfter: func() {}, + Notification: notification, + } + ct.fillCronTimes(begin, end) + return ct +} + +func (ct *CircleTask) fillCronTimes(begin, end time.Time) { + cron := cronexpr.MustParse(ct.CronExpr) + cronTimes := make([]time.Time, 0) + + // 根据cronexpr规则, 首次执行执行时间为>begin的第一个整点 + // 比如time.Now是12:00:22, 每分钟执行, 则首次执行时整数分钟, 12:01:00 + begin = cron.Next(begin) + for begin.Before(end) && !begin.IsZero() { + cronTimes = append(cronTimes, begin) + begin = cron.Next(begin) + } + + // 过滤历史时间 + // 比较的时候注意时区问题, time.Parse默认是UTC + legalCronTimes := slice.FilterDelete[time.Time](cronTimes, + func(idx int, src time.Time) bool { + return src.Before(time.Now()) + }) + ct.IterCronTimes = iterator.NewListIter(legalCronTimes) +} + +func (ct *CircleTask) Send(ctx context.Context) { + ct.HookBefore() + defer ct.HookAfter() + + select { + case <-ctx.Done(): + return + default: + for { + triggerPoint, done := ct.IterCronTimes.Next() + if done { + break + } + <-time.After(time.Until(triggerPoint)) + ct.circleNum++ + err := ct.Notification.Send(context.TODO()) + if err != nil { + ct.circleFailNum++ + log.Default().Error("circle task execute fail", "err", err) + } } } } diff --git a/task_test.go b/task_test.go new file mode 100644 index 0000000..882479a --- /dev/null +++ b/task_test.go @@ -0,0 +1,254 @@ +// Copyright 2021 ecodeclub +// +// 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 notify_go + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/ecodeclub/ekit/slice" + "github.com/ecodeclub/notify-go/pkg/notifier" + "github.com/ecodeclub/notify-go/pkg/notifier/mocks" + "github.com/stretchr/testify/assert" + "go.uber.org/mock/gomock" +) + +/* +测试场景: +1. 调用一次:超时、不超时没有返回error、不超时返回error +2. 并发调用多次:一般不存在这种场景, 同一个TriggerTask只会调用一次, 不同的task间并发安全 +*/ +func TestTriggerTask_Send(t *testing.T) { + t.Parallel() + + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + channel := mocks.NewMockIChannel(ctrl) + + o1 := channel.EXPECT().Execute(gomock.Any(), gomock.Any()).Return(nil) + o2 := channel.EXPECT().Execute(gomock.Any(), gomock.Any()).Return(context.DeadlineExceeded) + o3 := channel.EXPECT().Execute(gomock.Any(), gomock.Any()).Return(errors.New("test error appear")) + gomock.InOrder(o1, o2, o3) + + type fields struct { + Err chan error + TriggerTime time.Time + Notification *Notification + } + tests := []struct { + name string + fields fields + wantErr error + }{ + { + name: "normal", + fields: fields{ + Err: make(chan error), + TriggerTime: time.Now().Add(1 * time.Second), + Notification: NewNotification(channel, []notifier.Receiver{}, notifier.Content{}), + }, + }, + { + name: "time out", + fields: fields{ + Err: make(chan error), + TriggerTime: time.Now().Add(4 * time.Second), + Notification: NewNotification(channel, []notifier.Receiver{}, notifier.Content{}), + }, + wantErr: context.DeadlineExceeded, + }, + { + name: "error", + fields: fields{ + Err: make(chan error), + TriggerTime: time.Now().Add(1 * time.Second), + Notification: NewNotification(channel, []notifier.Receiver{}, notifier.Content{}), + }, + wantErr: errors.New("test error appear"), + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + tt := &TriggerTask{ + Err: tc.fields.Err, + TriggerTime: tc.fields.TriggerTime, + Notification: tc.fields.Notification, + HookBefore: func() {}, + HookAfter: func() {}, + } + ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) + defer cancel() + go tt.Send(ctx) + err := <-tc.fields.Err + assert.Equal(t, err, tc.wantErr) + }) + } +} + +/* +测试场景: +1. 调用一次:超时、不超时没有返回error、不超时返回error +2. 并发调用多次:一般不存在这种场景 +*/ +func TestCircleTask_Send(t *testing.T) { + ctrl := gomock.NewController(t) + defer ctrl.Finish() + + channel := mocks.NewMockIChannel(ctrl) + channel.EXPECT().Execute(gomock.Any(), gomock.Any()).Return(nil).AnyTimes() + + tests := []struct { + name string + Notification *Notification + cronExpr string + begin time.Time + end time.Time + wantFailCnt uint64 + wantCnt uint64 + }{ + { + name: "base", + Notification: NewNotification(channel, []notifier.Receiver{}, notifier.Content{}), + begin: time.Now().Add(time.Second), + end: time.Now().Add(5 * time.Second), + cronExpr: "* * * * * * *", // 每秒执行 + wantCnt: 4, + wantFailCnt: 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ct := NewCircleTask(tt.Notification, tt.cronExpr, tt.begin, tt.end) + ctx, cancel := context.WithTimeout(context.TODO(), 3*time.Second) + defer cancel() + ct.Send(ctx) + assert.Equal(t, tt.wantCnt, ct.circleNum) + }) + } +} + +func TestCircleTask_fillCronTimes(t *testing.T) { + type args struct { + expr string + begin time.Time + end time.Time + } + tests := []struct { + name string + args args + want []time.Time + }{ + { + name: "every minute 历史时间全部被过滤", + args: args{ + expr: "* * * * *", + begin: func() time.Time { + ti, _ := time.ParseInLocation("2006-01-02 15:04:05", "2023-10-26 15:31:00", time.Local) + return ti + }(), + end: func() time.Time { + ti, _ := time.ParseInLocation("2006-01-02 15:04:05", "2023-10-26 15:33:00", time.Local) + return ti + }(), + }, + want: make([]time.Time, 0), + }, + { + name: "every minute 开始时间晚于结束时间", + args: args{ + expr: "* * * * *", + begin: func() time.Time { + ti, _ := time.ParseInLocation("2006-01-02 15:04:05", "2023-10-26 15:33:00", time.Local) + return ti + }(), + end: func() time.Time { + ti, _ := time.ParseInLocation("2006-01-02 15:04:05", "2023-10-26 15:31:00", time.Local) + return ti + }(), + }, + want: make([]time.Time, 0), + }, + { + name: "every second", + args: args{ + expr: "* * * * * * *", + begin: func() time.Time { return time.Now().Add(100 * time.Second) }(), + end: func() time.Time { return time.Now().Add(105 * time.Second) }(), + }, + want: func() []time.Time { + res := make([]time.Time, 0) + begin := time.Now().Add(100 * time.Second) + end := time.Now().Add(105 * time.Second) + begin = begin.Add(time.Second) + for begin.Before(end) { + res = append(res, begin) + begin = begin.Add(time.Second) + } + return res + }(), + }, + { + name: "every minute", + args: args{ + expr: "* * * * *", + begin: func() time.Time { + return time.Now().Add(100 * time.Minute) + }(), + end: func() time.Time { + return time.Now().Add(104 * time.Minute) + }(), + }, + want: func() []time.Time { + res := make([]time.Time, 0) + begin := time.Now().Add(100 * time.Minute) + end := time.Now().Add(104 * time.Minute) + begin = begin.Add(time.Minute) + for begin.Before(end) { + res = append(res, begin.Truncate(time.Minute)) // 秒数需要置0 + begin = begin.Add(time.Minute) + } + return res + }(), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ct := &CircleTask{ + CronExpr: tt.args.expr, + } + + ct.fillCronTimes(tt.args.begin, tt.args.end) + cronTimes := make([]time.Time, 0) + for { + ti, done := ct.IterCronTimes.Next() + if done { + break + } + cronTimes = append(cronTimes, ti) + } + assert.Equal(t, toStr(tt.want), toStr(cronTimes)) + }) + } +} + +func toStr(arr []time.Time) []string { + return slice.Map[time.Time](arr, func(idx int, src time.Time) string { + return src.Format("2006-01-02 15:04:05") + }) +}