model.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package mon
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/wuntsong-org/go-zero-plus/core/breaker"
  6. "github.com/wuntsong-org/go-zero-plus/core/logx"
  7. "github.com/wuntsong-org/go-zero-plus/core/timex"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. mopt "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. const (
  12. startSession = "StartSession"
  13. abortTransaction = "AbortTransaction"
  14. commitTransaction = "CommitTransaction"
  15. withTransaction = "WithTransaction"
  16. endSession = "EndSession"
  17. )
  18. type (
  19. // Model is a mongodb store model that represents a collection.
  20. Model struct {
  21. Collection
  22. name string
  23. cli *mongo.Client
  24. brk breaker.Breaker
  25. opts []Option
  26. }
  27. wrappedSession struct {
  28. mongo.Session
  29. name string
  30. brk breaker.Breaker
  31. }
  32. )
  33. // MustNewModel returns a Model, exits on errors.
  34. func MustNewModel(uri, db, collection string, opts ...Option) *Model {
  35. model, err := NewModel(uri, db, collection, opts...)
  36. logx.Must(err)
  37. return model
  38. }
  39. // NewModel returns a Model.
  40. func NewModel(uri, db, collection string, opts ...Option) (*Model, error) {
  41. cli, err := getClient(uri, opts...)
  42. if err != nil {
  43. return nil, err
  44. }
  45. name := strings.Join([]string{uri, collection}, "/")
  46. brk := breaker.GetBreaker(uri)
  47. coll := newCollection(cli.Database(db).Collection(collection), brk)
  48. return newModel(name, cli, coll, brk, opts...), nil
  49. }
  50. func newModel(name string, cli *mongo.Client, coll Collection, brk breaker.Breaker,
  51. opts ...Option) *Model {
  52. return &Model{
  53. name: name,
  54. Collection: coll,
  55. cli: cli,
  56. brk: brk,
  57. opts: opts,
  58. }
  59. }
  60. // StartSession starts a new session.
  61. func (m *Model) StartSession(opts ...*mopt.SessionOptions) (sess mongo.Session, err error) {
  62. err = m.brk.DoWithAcceptable(func() error {
  63. starTime := timex.Now()
  64. defer func() {
  65. logDuration(context.Background(), m.name, startSession, starTime, err)
  66. }()
  67. session, sessionErr := m.cli.StartSession(opts...)
  68. if sessionErr != nil {
  69. return sessionErr
  70. }
  71. sess = &wrappedSession{
  72. Session: session,
  73. name: m.name,
  74. brk: m.brk,
  75. }
  76. return nil
  77. }, acceptable)
  78. return
  79. }
  80. // Aggregate executes an aggregation pipeline.
  81. func (m *Model) Aggregate(ctx context.Context, v, pipeline any, opts ...*mopt.AggregateOptions) error {
  82. cur, err := m.Collection.Aggregate(ctx, pipeline, opts...)
  83. if err != nil {
  84. return err
  85. }
  86. defer cur.Close(ctx)
  87. return cur.All(ctx, v)
  88. }
  89. // DeleteMany deletes documents that match the filter.
  90. func (m *Model) DeleteMany(ctx context.Context, filter any, opts ...*mopt.DeleteOptions) (int64, error) {
  91. res, err := m.Collection.DeleteMany(ctx, filter, opts...)
  92. if err != nil {
  93. return 0, err
  94. }
  95. return res.DeletedCount, nil
  96. }
  97. // DeleteOne deletes the first document that matches the filter.
  98. func (m *Model) DeleteOne(ctx context.Context, filter any, opts ...*mopt.DeleteOptions) (int64, error) {
  99. res, err := m.Collection.DeleteOne(ctx, filter, opts...)
  100. if err != nil {
  101. return 0, err
  102. }
  103. return res.DeletedCount, nil
  104. }
  105. // Find finds documents that match the filter.
  106. func (m *Model) Find(ctx context.Context, v, filter any, opts ...*mopt.FindOptions) error {
  107. cur, err := m.Collection.Find(ctx, filter, opts...)
  108. if err != nil {
  109. return err
  110. }
  111. defer cur.Close(ctx)
  112. return cur.All(ctx, v)
  113. }
  114. // FindOne finds the first document that matches the filter.
  115. func (m *Model) FindOne(ctx context.Context, v, filter any, opts ...*mopt.FindOneOptions) error {
  116. res, err := m.Collection.FindOne(ctx, filter, opts...)
  117. if err != nil {
  118. return err
  119. }
  120. return res.Decode(v)
  121. }
  122. // FindOneAndDelete finds a single document and deletes it.
  123. func (m *Model) FindOneAndDelete(ctx context.Context, v, filter any,
  124. opts ...*mopt.FindOneAndDeleteOptions) error {
  125. res, err := m.Collection.FindOneAndDelete(ctx, filter, opts...)
  126. if err != nil {
  127. return err
  128. }
  129. return res.Decode(v)
  130. }
  131. // FindOneAndReplace finds a single document and replaces it.
  132. func (m *Model) FindOneAndReplace(ctx context.Context, v, filter, replacement any,
  133. opts ...*mopt.FindOneAndReplaceOptions) error {
  134. res, err := m.Collection.FindOneAndReplace(ctx, filter, replacement, opts...)
  135. if err != nil {
  136. return err
  137. }
  138. return res.Decode(v)
  139. }
  140. // FindOneAndUpdate finds a single document and updates it.
  141. func (m *Model) FindOneAndUpdate(ctx context.Context, v, filter, update any,
  142. opts ...*mopt.FindOneAndUpdateOptions) error {
  143. res, err := m.Collection.FindOneAndUpdate(ctx, filter, update, opts...)
  144. if err != nil {
  145. return err
  146. }
  147. return res.Decode(v)
  148. }
  149. // AbortTransaction implements the mongo.Session interface.
  150. func (w *wrappedSession) AbortTransaction(ctx context.Context) (err error) {
  151. ctx, span := startSpan(ctx, abortTransaction)
  152. defer func() {
  153. endSpan(span, err)
  154. }()
  155. return w.brk.DoWithAcceptable(func() error {
  156. starTime := timex.Now()
  157. defer func() {
  158. logDuration(ctx, w.name, abortTransaction, starTime, err)
  159. }()
  160. return w.Session.AbortTransaction(ctx)
  161. }, acceptable)
  162. }
  163. // CommitTransaction implements the mongo.Session interface.
  164. func (w *wrappedSession) CommitTransaction(ctx context.Context) (err error) {
  165. ctx, span := startSpan(ctx, commitTransaction)
  166. defer func() {
  167. endSpan(span, err)
  168. }()
  169. return w.brk.DoWithAcceptable(func() error {
  170. starTime := timex.Now()
  171. defer func() {
  172. logDuration(ctx, w.name, commitTransaction, starTime, err)
  173. }()
  174. return w.Session.CommitTransaction(ctx)
  175. }, acceptable)
  176. }
  177. // WithTransaction implements the mongo.Session interface.
  178. func (w *wrappedSession) WithTransaction(
  179. ctx context.Context,
  180. fn func(sessCtx mongo.SessionContext) (any, error),
  181. opts ...*mopt.TransactionOptions,
  182. ) (res any, err error) {
  183. ctx, span := startSpan(ctx, withTransaction)
  184. defer func() {
  185. endSpan(span, err)
  186. }()
  187. err = w.brk.DoWithAcceptable(func() error {
  188. starTime := timex.Now()
  189. defer func() {
  190. logDuration(ctx, w.name, withTransaction, starTime, err)
  191. }()
  192. res, err = w.Session.WithTransaction(ctx, fn, opts...)
  193. return err
  194. }, acceptable)
  195. return
  196. }
  197. // EndSession implements the mongo.Session interface.
  198. func (w *wrappedSession) EndSession(ctx context.Context) {
  199. var err error
  200. ctx, span := startSpan(ctx, endSession)
  201. defer func() {
  202. endSpan(span, err)
  203. }()
  204. err = w.brk.DoWithAcceptable(func() error {
  205. starTime := timex.Now()
  206. defer func() {
  207. logDuration(ctx, w.name, endSession, starTime, err)
  208. }()
  209. w.Session.EndSession(ctx)
  210. return nil
  211. }, acceptable)
  212. }