mapreduce.go 7.5 KB

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