iter.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //go:generate mockgen -package mongo -destination iter_mock.go -source iter.go Iter
  2. package mongo
  3. import (
  4. "git.i2edu.net/i2/go-zero/core/breaker"
  5. "github.com/globalsign/mgo/bson"
  6. )
  7. type (
  8. // Iter interface represents a mongo iter.
  9. Iter interface {
  10. All(result interface{}) error
  11. Close() error
  12. Done() bool
  13. Err() error
  14. For(result interface{}, f func() error) error
  15. Next(result interface{}) bool
  16. State() (int64, []bson.Raw)
  17. Timeout() bool
  18. }
  19. // A ClosableIter is a closable mongo iter.
  20. ClosableIter struct {
  21. Iter
  22. Cleanup func()
  23. }
  24. promisedIter struct {
  25. Iter
  26. promise keepablePromise
  27. }
  28. rejectedIter struct{}
  29. )
  30. func (i promisedIter) All(result interface{}) error {
  31. return i.promise.keep(i.Iter.All(result))
  32. }
  33. func (i promisedIter) Close() error {
  34. return i.promise.keep(i.Iter.Close())
  35. }
  36. func (i promisedIter) Err() error {
  37. return i.Iter.Err()
  38. }
  39. func (i promisedIter) For(result interface{}, f func() error) error {
  40. var ferr error
  41. err := i.Iter.For(result, func() error {
  42. ferr = f()
  43. return ferr
  44. })
  45. if ferr == err {
  46. return i.promise.accept(err)
  47. }
  48. return i.promise.keep(err)
  49. }
  50. // Close closes a mongo iter.
  51. func (it *ClosableIter) Close() error {
  52. err := it.Iter.Close()
  53. it.Cleanup()
  54. return err
  55. }
  56. func (i rejectedIter) All(result interface{}) error {
  57. return breaker.ErrServiceUnavailable
  58. }
  59. func (i rejectedIter) Close() error {
  60. return breaker.ErrServiceUnavailable
  61. }
  62. func (i rejectedIter) Done() bool {
  63. return false
  64. }
  65. func (i rejectedIter) Err() error {
  66. return breaker.ErrServiceUnavailable
  67. }
  68. func (i rejectedIter) For(result interface{}, f func() error) error {
  69. return breaker.ErrServiceUnavailable
  70. }
  71. func (i rejectedIter) Next(result interface{}) bool {
  72. return false
  73. }
  74. func (i rejectedIter) State() (int64, []bson.Raw) {
  75. return 0, nil
  76. }
  77. func (i rejectedIter) Timeout() bool {
  78. return false
  79. }