mapreduce.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package mr
  2. import (
  3. "context"
  4. "errors"
  5. "sync"
  6. "sync/atomic"
  7. "github.com/zeromicro/go-zero/core/errorx"
  8. "github.com/zeromicro/go-zero/core/lang"
  9. )
  10. const (
  11. defaultWorkers = 16
  12. minWorkers = 1
  13. )
  14. var (
  15. // ErrCancelWithNil is an error that mapreduce was cancelled with nil.
  16. ErrCancelWithNil = errors.New("mapreduce cancelled with nil")
  17. // ErrReduceNoOutput is an error that reduce did not output a value.
  18. ErrReduceNoOutput = errors.New("reduce not writing value")
  19. )
  20. type (
  21. // ForEachFunc is used to do element processing, but no output.
  22. ForEachFunc func(item interface{})
  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. // MapperFunc is used to do element processing and write the output to writer,
  28. // use cancel func to cancel the processing.
  29. MapperFunc func(item interface{}, writer Writer, cancel func(error))
  30. // ReducerFunc is used to reduce all the mapping output and write to writer,
  31. // use cancel func to cancel the processing.
  32. ReducerFunc func(pipe <-chan interface{}, writer Writer, cancel func(error))
  33. // VoidReducerFunc is used to reduce all the mapping output, but no output.
  34. // Use cancel func to cancel the processing.
  35. VoidReducerFunc func(pipe <-chan interface{}, cancel func(error))
  36. // Option defines the method to customize the mapreduce.
  37. Option func(opts *mapReduceOptions)
  38. mapperContext struct {
  39. ctx context.Context
  40. mapper MapFunc
  41. source <-chan interface{}
  42. panicChan *onceChan
  43. collector chan<- interface{}
  44. doneChan <-chan lang.PlaceholderType
  45. workers int
  46. }
  47. mapReduceOptions struct {
  48. ctx context.Context
  49. workers int
  50. }
  51. // Writer interface wraps Write method.
  52. Writer interface {
  53. Write(v interface{})
  54. }
  55. )
  56. // Finish runs fns parallelly, cancelled on any error.
  57. func Finish(fns ...func() error) error {
  58. if len(fns) == 0 {
  59. return nil
  60. }
  61. return MapReduceVoid(func(source chan<- interface{}) {
  62. for _, fn := range fns {
  63. source <- fn
  64. }
  65. }, func(item interface{}, writer Writer, cancel func(error)) {
  66. fn := item.(func() error)
  67. if err := fn(); err != nil {
  68. cancel(err)
  69. }
  70. }, func(pipe <-chan interface{}, cancel func(error)) {
  71. }, WithWorkers(len(fns)))
  72. }
  73. // FinishVoid runs fns parallelly.
  74. func FinishVoid(fns ...func()) {
  75. if len(fns) == 0 {
  76. return
  77. }
  78. ForEach(func(source chan<- interface{}) {
  79. for _, fn := range fns {
  80. source <- fn
  81. }
  82. }, func(item interface{}) {
  83. fn := item.(func())
  84. fn()
  85. }, WithWorkers(len(fns)))
  86. }
  87. // ForEach maps all elements from given generate but no output.
  88. func ForEach(generate GenerateFunc, mapper ForEachFunc, opts ...Option) {
  89. options := buildOptions(opts...)
  90. panicChan := &onceChan{channel: make(chan interface{})}
  91. source := buildSource(generate, panicChan)
  92. collector := make(chan interface{})
  93. done := make(chan lang.PlaceholderType)
  94. go executeMappers(mapperContext{
  95. ctx: options.ctx,
  96. mapper: func(item interface{}, _ Writer) {
  97. mapper(item)
  98. },
  99. source: source,
  100. panicChan: panicChan,
  101. collector: collector,
  102. doneChan: done,
  103. workers: options.workers,
  104. })
  105. for {
  106. select {
  107. case v := <-panicChan.channel:
  108. panic(v)
  109. case _, ok := <-collector:
  110. if !ok {
  111. return
  112. }
  113. }
  114. }
  115. }
  116. // MapReduce maps all elements generated from given generate func,
  117. // and reduces the output elements with given reducer.
  118. func MapReduce(generate GenerateFunc, mapper MapperFunc, reducer ReducerFunc,
  119. opts ...Option) (interface{}, error) {
  120. panicChan := &onceChan{channel: make(chan interface{})}
  121. source := buildSource(generate, panicChan)
  122. return mapReduceWithPanicChan(source, panicChan, mapper, reducer, opts...)
  123. }
  124. // MapReduceChan maps all elements from source, and reduce the output elements with given reducer.
  125. func MapReduceChan(source <-chan interface{}, mapper MapperFunc, reducer ReducerFunc,
  126. opts ...Option) (interface{}, error) {
  127. panicChan := &onceChan{channel: make(chan interface{})}
  128. return mapReduceWithPanicChan(source, panicChan, mapper, reducer, opts...)
  129. }
  130. // MapReduceChan maps all elements from source, and reduce the output elements with given reducer.
  131. func mapReduceWithPanicChan(source <-chan interface{}, panicChan *onceChan, mapper MapperFunc,
  132. reducer ReducerFunc, opts ...Option) (interface{}, error) {
  133. options := buildOptions(opts...)
  134. // output is used to write the final result
  135. output := make(chan interface{})
  136. defer func() {
  137. // reducer can only write once, if more, panic
  138. for range output {
  139. panic("more than one element written in reducer")
  140. }
  141. }()
  142. // collector is used to collect data from mapper, and consume in reducer
  143. collector := make(chan interface{}, options.workers)
  144. // if done is closed, all mappers and reducer should stop processing
  145. done := make(chan lang.PlaceholderType)
  146. writer := newGuardedWriter(options.ctx, output, done)
  147. var closeOnce sync.Once
  148. // use atomic.Value to avoid data race
  149. var retErr errorx.AtomicError
  150. finish := func() {
  151. closeOnce.Do(func() {
  152. close(done)
  153. close(output)
  154. })
  155. }
  156. cancel := once(func(err error) {
  157. if err != nil {
  158. retErr.Set(err)
  159. } else {
  160. retErr.Set(ErrCancelWithNil)
  161. }
  162. drain(source)
  163. finish()
  164. })
  165. go func() {
  166. defer func() {
  167. drain(collector)
  168. if r := recover(); r != nil {
  169. panicChan.write(r)
  170. }
  171. finish()
  172. }()
  173. reducer(collector, writer, cancel)
  174. }()
  175. go executeMappers(mapperContext{
  176. ctx: options.ctx,
  177. mapper: func(item interface{}, w Writer) {
  178. mapper(item, w, cancel)
  179. },
  180. source: source,
  181. panicChan: panicChan,
  182. collector: collector,
  183. doneChan: done,
  184. workers: options.workers,
  185. })
  186. select {
  187. case <-options.ctx.Done():
  188. cancel(context.DeadlineExceeded)
  189. return nil, context.DeadlineExceeded
  190. case v := <-panicChan.channel:
  191. panic(v)
  192. case v, ok := <-output:
  193. if err := retErr.Load(); err != nil {
  194. return nil, err
  195. } else if ok {
  196. return v, nil
  197. } else {
  198. return nil, ErrReduceNoOutput
  199. }
  200. }
  201. }
  202. // MapReduceVoid maps all elements generated from given generate,
  203. // and reduce the output elements with given reducer.
  204. func MapReduceVoid(generate GenerateFunc, mapper MapperFunc, reducer VoidReducerFunc, opts ...Option) error {
  205. _, err := MapReduce(generate, mapper, func(input <-chan interface{}, writer Writer, cancel func(error)) {
  206. reducer(input, cancel)
  207. }, opts...)
  208. if errors.Is(err, ErrReduceNoOutput) {
  209. return nil
  210. }
  211. return err
  212. }
  213. // WithContext customizes a mapreduce processing accepts a given ctx.
  214. func WithContext(ctx context.Context) Option {
  215. return func(opts *mapReduceOptions) {
  216. opts.ctx = ctx
  217. }
  218. }
  219. // WithWorkers customizes a mapreduce processing with given workers.
  220. func WithWorkers(workers int) Option {
  221. return func(opts *mapReduceOptions) {
  222. if workers < minWorkers {
  223. opts.workers = minWorkers
  224. } else {
  225. opts.workers = workers
  226. }
  227. }
  228. }
  229. func buildOptions(opts ...Option) *mapReduceOptions {
  230. options := newOptions()
  231. for _, opt := range opts {
  232. opt(options)
  233. }
  234. return options
  235. }
  236. func buildSource(generate GenerateFunc, panicChan *onceChan) chan interface{} {
  237. source := make(chan interface{})
  238. go func() {
  239. defer func() {
  240. if r := recover(); r != nil {
  241. panicChan.write(r)
  242. }
  243. close(source)
  244. }()
  245. generate(source)
  246. }()
  247. return source
  248. }
  249. // drain drains the channel.
  250. func drain(channel <-chan interface{}) {
  251. // drain the channel
  252. for range channel {
  253. }
  254. }
  255. func executeMappers(mCtx mapperContext) {
  256. var wg sync.WaitGroup
  257. defer func() {
  258. wg.Wait()
  259. close(mCtx.collector)
  260. drain(mCtx.source)
  261. }()
  262. var failed int32
  263. pool := make(chan lang.PlaceholderType, mCtx.workers)
  264. writer := newGuardedWriter(mCtx.ctx, mCtx.collector, mCtx.doneChan)
  265. for atomic.LoadInt32(&failed) == 0 {
  266. select {
  267. case <-mCtx.ctx.Done():
  268. return
  269. case <-mCtx.doneChan:
  270. return
  271. case pool <- lang.Placeholder:
  272. item, ok := <-mCtx.source
  273. if !ok {
  274. <-pool
  275. return
  276. }
  277. wg.Add(1)
  278. go func() {
  279. defer func() {
  280. if r := recover(); r != nil {
  281. atomic.AddInt32(&failed, 1)
  282. mCtx.panicChan.write(r)
  283. }
  284. wg.Done()
  285. <-pool
  286. }()
  287. mCtx.mapper(item, writer)
  288. }()
  289. }
  290. }
  291. }
  292. func newOptions() *mapReduceOptions {
  293. return &mapReduceOptions{
  294. ctx: context.Background(),
  295. workers: defaultWorkers,
  296. }
  297. }
  298. func once(fn func(error)) func(error) {
  299. once := new(sync.Once)
  300. return func(err error) {
  301. once.Do(func() {
  302. fn(err)
  303. })
  304. }
  305. }
  306. type guardedWriter struct {
  307. ctx context.Context
  308. channel chan<- interface{}
  309. done <-chan lang.PlaceholderType
  310. }
  311. func newGuardedWriter(ctx context.Context, channel chan<- interface{},
  312. done <-chan lang.PlaceholderType) guardedWriter {
  313. return guardedWriter{
  314. ctx: ctx,
  315. channel: channel,
  316. done: done,
  317. }
  318. }
  319. func (gw guardedWriter) Write(v interface{}) {
  320. select {
  321. case <-gw.ctx.Done():
  322. return
  323. case <-gw.done:
  324. return
  325. default:
  326. gw.channel <- v
  327. }
  328. }
  329. type onceChan struct {
  330. channel chan interface{}
  331. wrote int32
  332. }
  333. func (oc *onceChan) write(val interface{}) {
  334. if atomic.CompareAndSwapInt32(&oc.wrote, 0, 1) {
  335. oc.channel <- val
  336. }
  337. }