mapreduce.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 elements 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. defer func() {
  100. for range output {
  101. panic("more than one element written in reducer")
  102. }
  103. }()
  104. collector := make(chan interface{}, options.workers)
  105. done := syncx.NewDoneChan()
  106. writer := newGuardedWriter(output, done.Done())
  107. var closeOnce sync.Once
  108. var retErr errorx.AtomicError
  109. finish := func() {
  110. closeOnce.Do(func() {
  111. done.Close()
  112. close(output)
  113. })
  114. }
  115. cancel := once(func(err error) {
  116. if err != nil {
  117. retErr.Set(err)
  118. } else {
  119. retErr.Set(ErrCancelWithNil)
  120. }
  121. drain(source)
  122. finish()
  123. })
  124. go func() {
  125. defer func() {
  126. drain(collector)
  127. if r := recover(); r != nil {
  128. cancel(fmt.Errorf("%v", r))
  129. } else {
  130. finish()
  131. }
  132. }()
  133. reducer(collector, writer, cancel)
  134. }()
  135. go executeMappers(func(item interface{}, w Writer) {
  136. mapper(item, w, cancel)
  137. }, source, collector, done.Done(), options.workers)
  138. value, ok := <-output
  139. if err := retErr.Load(); err != nil {
  140. return nil, err
  141. } else if ok {
  142. return value, nil
  143. } else {
  144. return nil, ErrReduceNoOutput
  145. }
  146. }
  147. // MapReduceVoid maps all elements generated from given generate,
  148. // and reduce the output elements with given reducer.
  149. func MapReduceVoid(generate GenerateFunc, mapper MapperFunc, reducer VoidReducerFunc, opts ...Option) error {
  150. _, err := MapReduce(generate, mapper, func(input <-chan interface{}, writer Writer, cancel func(error)) {
  151. reducer(input, cancel)
  152. // We need to write a placeholder to let MapReduce to continue on reducer done,
  153. // otherwise, all goroutines are waiting. The placeholder will be discarded by MapReduce.
  154. writer.Write(lang.Placeholder)
  155. }, opts...)
  156. return err
  157. }
  158. // MapVoid maps all elements from given generate but no output.
  159. func MapVoid(generate GenerateFunc, mapper VoidMapFunc, opts ...Option) {
  160. drain(Map(generate, func(item interface{}, writer Writer) {
  161. mapper(item)
  162. }, opts...))
  163. }
  164. // WithWorkers customizes a mapreduce processing with given workers.
  165. func WithWorkers(workers int) Option {
  166. return func(opts *mapReduceOptions) {
  167. if workers < minWorkers {
  168. opts.workers = minWorkers
  169. } else {
  170. opts.workers = workers
  171. }
  172. }
  173. }
  174. func buildOptions(opts ...Option) *mapReduceOptions {
  175. options := newOptions()
  176. for _, opt := range opts {
  177. opt(options)
  178. }
  179. return options
  180. }
  181. func buildSource(generate GenerateFunc) chan interface{} {
  182. source := make(chan interface{})
  183. threading.GoSafe(func() {
  184. defer close(source)
  185. generate(source)
  186. })
  187. return source
  188. }
  189. // drain drains the channel.
  190. func drain(channel <-chan interface{}) {
  191. // drain the channel
  192. for range channel {
  193. }
  194. }
  195. func executeMappers(mapper MapFunc, input <-chan interface{}, collector chan<- interface{},
  196. done <-chan lang.PlaceholderType, workers int) {
  197. var wg sync.WaitGroup
  198. defer func() {
  199. wg.Wait()
  200. close(collector)
  201. }()
  202. pool := make(chan lang.PlaceholderType, workers)
  203. writer := newGuardedWriter(collector, done)
  204. for {
  205. select {
  206. case <-done:
  207. return
  208. case pool <- lang.Placeholder:
  209. item, ok := <-input
  210. if !ok {
  211. <-pool
  212. return
  213. }
  214. wg.Add(1)
  215. // better to safely run caller defined method
  216. threading.GoSafe(func() {
  217. defer func() {
  218. wg.Done()
  219. <-pool
  220. }()
  221. mapper(item, writer)
  222. })
  223. }
  224. }
  225. }
  226. func newOptions() *mapReduceOptions {
  227. return &mapReduceOptions{
  228. workers: defaultWorkers,
  229. }
  230. }
  231. func once(fn func(error)) func(error) {
  232. once := new(sync.Once)
  233. return func(err error) {
  234. once.Do(func() {
  235. fn(err)
  236. })
  237. }
  238. }
  239. type guardedWriter struct {
  240. channel chan<- interface{}
  241. done <-chan lang.PlaceholderType
  242. }
  243. func newGuardedWriter(channel chan<- interface{}, done <-chan lang.PlaceholderType) guardedWriter {
  244. return guardedWriter{
  245. channel: channel,
  246. done: done,
  247. }
  248. }
  249. func (gw guardedWriter) Write(v interface{}) {
  250. select {
  251. case <-gw.done:
  252. return
  253. default:
  254. gw.channel <- v
  255. }
  256. }