mapreduce.go 7.6 KB

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