mapreduce.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package mr
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "git.i2edu.net/i2/go-zero/core/errorx"
  7. "git.i2edu.net/i2/go-zero/core/lang"
  8. "git.i2edu.net/i2/go-zero/core/syncx"
  9. "git.i2edu.net/i2/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. 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. drain(collector)
  122. if r := recover(); r != nil {
  123. cancel(fmt.Errorf("%v", r))
  124. } else {
  125. finish()
  126. }
  127. }()
  128. reducer(collector, writer, cancel)
  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. // We need to write a placeholder to let MapReduce to continue on reducer done,
  148. // otherwise, all goroutines are waiting. The placeholder will be discarded by MapReduce.
  149. writer.Write(lang.Placeholder)
  150. }, opts...)
  151. return err
  152. }
  153. // MapVoid maps all elements from given generate but no output.
  154. func MapVoid(generate GenerateFunc, mapper VoidMapFunc, opts ...Option) {
  155. drain(Map(generate, func(item interface{}, writer Writer) {
  156. mapper(item)
  157. }, opts...))
  158. }
  159. // WithWorkers customizes a mapreduce processing with given workers.
  160. func WithWorkers(workers int) Option {
  161. return func(opts *mapReduceOptions) {
  162. if workers < minWorkers {
  163. opts.workers = minWorkers
  164. } else {
  165. opts.workers = workers
  166. }
  167. }
  168. }
  169. func buildOptions(opts ...Option) *mapReduceOptions {
  170. options := newOptions()
  171. for _, opt := range opts {
  172. opt(options)
  173. }
  174. return options
  175. }
  176. func buildSource(generate GenerateFunc) chan interface{} {
  177. source := make(chan interface{})
  178. threading.GoSafe(func() {
  179. defer close(source)
  180. generate(source)
  181. })
  182. return source
  183. }
  184. // drain drains the channel.
  185. func drain(channel <-chan interface{}) {
  186. // drain the channel
  187. for range channel {
  188. }
  189. }
  190. func executeMappers(mapper MapFunc, input <-chan interface{}, collector chan<- interface{},
  191. done <-chan lang.PlaceholderType, workers int) {
  192. var wg sync.WaitGroup
  193. defer func() {
  194. wg.Wait()
  195. close(collector)
  196. }()
  197. pool := make(chan lang.PlaceholderType, workers)
  198. writer := newGuardedWriter(collector, done)
  199. for {
  200. select {
  201. case <-done:
  202. return
  203. case pool <- lang.Placeholder:
  204. item, ok := <-input
  205. if !ok {
  206. <-pool
  207. return
  208. }
  209. wg.Add(1)
  210. // better to safely run caller defined method
  211. threading.GoSafe(func() {
  212. defer func() {
  213. wg.Done()
  214. <-pool
  215. }()
  216. mapper(item, writer)
  217. })
  218. }
  219. }
  220. }
  221. func newOptions() *mapReduceOptions {
  222. return &mapReduceOptions{
  223. workers: defaultWorkers,
  224. }
  225. }
  226. func once(fn func(error)) func(error) {
  227. once := new(sync.Once)
  228. return func(err error) {
  229. once.Do(func() {
  230. fn(err)
  231. })
  232. }
  233. }
  234. type guardedWriter struct {
  235. channel chan<- interface{}
  236. done <-chan lang.PlaceholderType
  237. }
  238. func newGuardedWriter(channel chan<- interface{}, done <-chan lang.PlaceholderType) guardedWriter {
  239. return guardedWriter{
  240. channel: channel,
  241. done: done,
  242. }
  243. }
  244. func (gw guardedWriter) Write(v interface{}) {
  245. select {
  246. case <-gw.done:
  247. return
  248. default:
  249. gw.channel <- v
  250. }
  251. }