model.go 6.3 KB

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