mapreduce.go 7.1 KB

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