mapreduce.go 7.5 KB

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