mapreduce.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. package mr
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "github.com/tal-tech/go-zero/core/errorx"
  7. "github.com/tal-tech/go-zero/core/lang"
  8. "github.com/tal-tech/go-zero/core/syncx"
  9. "github.com/tal-tech/go-zero/core/threading"
  10. )
  11. const (
  12. defaultWorkers = 16
  13. minWorkers = 1
  14. )
  15. var (
  16. ErrCancelWithNil = errors.New("mapreduce cancelled with nil")
  17. ErrReduceNoOutput = errors.New("reduce not writing value")
  18. )
  19. type (
  20. GenerateFunc func(source chan<- interface{})
  21. MapFunc func(item interface{}, writer Writer)
  22. VoidMapFunc func(item interface{})
  23. MapperFunc func(item interface{}, writer Writer, cancel func(error))
  24. ReducerFunc func(pipe <-chan interface{}, writer Writer, cancel func(error))
  25. VoidReducerFunc func(pipe <-chan interface{}, cancel func(error))
  26. Option func(opts *mapReduceOptions)
  27. mapReduceOptions struct {
  28. workers int
  29. }
  30. Writer interface {
  31. Write(v interface{})
  32. }
  33. )
  34. func Finish(fns ...func() error) error {
  35. if len(fns) == 0 {
  36. return nil
  37. }
  38. return MapReduceVoid(func(source chan<- interface{}) {
  39. for _, fn := range fns {
  40. source <- fn
  41. }
  42. }, func(item interface{}, writer Writer, cancel func(error)) {
  43. fn := item.(func() error)
  44. if err := fn(); err != nil {
  45. cancel(err)
  46. }
  47. }, func(pipe <-chan interface{}, cancel func(error)) {
  48. drain(pipe)
  49. }, WithWorkers(len(fns)))
  50. }
  51. func FinishVoid(fns ...func()) {
  52. if len(fns) == 0 {
  53. return
  54. }
  55. MapVoid(func(source chan<- interface{}) {
  56. for _, fn := range fns {
  57. source <- fn
  58. }
  59. }, func(item interface{}) {
  60. fn := item.(func())
  61. fn()
  62. }, WithWorkers(len(fns)))
  63. }
  64. func Map(generate GenerateFunc, mapper MapFunc, opts ...Option) chan interface{} {
  65. options := buildOptions(opts...)
  66. source := buildSource(generate)
  67. collector := make(chan interface{}, options.workers)
  68. done := syncx.NewDoneChan()
  69. go executeMappers(mapper, source, collector, done.Done(), options.workers)
  70. return collector
  71. }
  72. func MapReduce(generate GenerateFunc, mapper MapperFunc, reducer ReducerFunc, opts ...Option) (interface{}, error) {
  73. source := buildSource(generate)
  74. return MapReduceWithSource(source, mapper, reducer, opts...)
  75. }
  76. func MapReduceWithSource(source <-chan interface{}, mapper MapperFunc, reducer ReducerFunc,
  77. opts ...Option) (interface{}, error) {
  78. options := buildOptions(opts...)
  79. output := make(chan interface{})
  80. collector := make(chan interface{}, options.workers)
  81. done := syncx.NewDoneChan()
  82. writer := newGuardedWriter(output, done.Done())
  83. var closeOnce sync.Once
  84. var retErr errorx.AtomicError
  85. finish := func() {
  86. closeOnce.Do(func() {
  87. done.Close()
  88. close(output)
  89. })
  90. }
  91. cancel := once(func(err error) {
  92. if err != nil {
  93. retErr.Set(err)
  94. } else {
  95. retErr.Set(ErrCancelWithNil)
  96. }
  97. drain(source)
  98. finish()
  99. })
  100. go func() {
  101. defer func() {
  102. if r := recover(); r != nil {
  103. cancel(fmt.Errorf("%v", r))
  104. } else {
  105. finish()
  106. }
  107. }()
  108. reducer(collector, writer, cancel)
  109. drain(collector)
  110. }()
  111. go executeMappers(func(item interface{}, w Writer) {
  112. mapper(item, w, cancel)
  113. }, source, collector, done.Done(), options.workers)
  114. value, ok := <-output
  115. if err := retErr.Load(); err != nil {
  116. return nil, err
  117. } else if ok {
  118. return value, nil
  119. } else {
  120. return nil, ErrReduceNoOutput
  121. }
  122. }
  123. func MapReduceVoid(generator GenerateFunc, mapper MapperFunc, reducer VoidReducerFunc, opts ...Option) error {
  124. _, err := MapReduce(generator, mapper, func(input <-chan interface{}, writer Writer, cancel func(error)) {
  125. reducer(input, cancel)
  126. drain(input)
  127. // We need to write a placeholder to let MapReduce to continue on reducer done,
  128. // otherwise, all goroutines are waiting. The placeholder will be discarded by MapReduce.
  129. writer.Write(lang.Placeholder)
  130. }, opts...)
  131. return err
  132. }
  133. func MapVoid(generate GenerateFunc, mapper VoidMapFunc, opts ...Option) {
  134. drain(Map(generate, func(item interface{}, writer Writer) {
  135. mapper(item)
  136. }, opts...))
  137. }
  138. func WithWorkers(workers int) Option {
  139. return func(opts *mapReduceOptions) {
  140. if workers < minWorkers {
  141. opts.workers = minWorkers
  142. } else {
  143. opts.workers = workers
  144. }
  145. }
  146. }
  147. func buildOptions(opts ...Option) *mapReduceOptions {
  148. options := newOptions()
  149. for _, opt := range opts {
  150. opt(options)
  151. }
  152. return options
  153. }
  154. func buildSource(generate GenerateFunc) chan interface{} {
  155. source := make(chan interface{})
  156. threading.GoSafe(func() {
  157. defer close(source)
  158. generate(source)
  159. })
  160. return source
  161. }
  162. // drain drains the channel.
  163. func drain(channel <-chan interface{}) {
  164. // drain the channel
  165. for range channel {
  166. }
  167. }
  168. func executeMappers(mapper MapFunc, input <-chan interface{}, collector chan<- interface{},
  169. done <-chan lang.PlaceholderType, workers int) {
  170. var wg sync.WaitGroup
  171. defer func() {
  172. wg.Wait()
  173. close(collector)
  174. }()
  175. pool := make(chan lang.PlaceholderType, workers)
  176. writer := newGuardedWriter(collector, done)
  177. for {
  178. select {
  179. case <-done:
  180. return
  181. case pool <- lang.Placeholder:
  182. item, ok := <-input
  183. if !ok {
  184. <-pool
  185. return
  186. }
  187. wg.Add(1)
  188. // better to safely run caller defined method
  189. threading.GoSafe(func() {
  190. defer func() {
  191. wg.Done()
  192. <-pool
  193. }()
  194. mapper(item, writer)
  195. })
  196. }
  197. }
  198. }
  199. func newOptions() *mapReduceOptions {
  200. return &mapReduceOptions{
  201. workers: defaultWorkers,
  202. }
  203. }
  204. func once(fn func(error)) func(error) {
  205. once := new(sync.Once)
  206. return func(err error) {
  207. once.Do(func() {
  208. fn(err)
  209. })
  210. }
  211. }
  212. type guardedWriter struct {
  213. channel chan<- interface{}
  214. done <-chan lang.PlaceholderType
  215. }
  216. func newGuardedWriter(channel chan<- interface{}, done <-chan lang.PlaceholderType) guardedWriter {
  217. return guardedWriter{
  218. channel: channel,
  219. done: done,
  220. }
  221. }
  222. func (gw guardedWriter) Write(v interface{}) {
  223. select {
  224. case <-gw.done:
  225. return
  226. default:
  227. gw.channel <- v
  228. }
  229. }