mapreduce.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. // drain output here, otherwise for loop panic in defer
  192. drain(output)
  193. panic(v)
  194. case v, ok := <-output:
  195. if err := retErr.Load(); err != nil {
  196. return nil, err
  197. } else if ok {
  198. return v, nil
  199. } else {
  200. return nil, ErrReduceNoOutput
  201. }
  202. }
  203. }
  204. // MapReduceVoid maps all elements generated from given generate,
  205. // and reduce the output elements with given reducer.
  206. func MapReduceVoid(generate GenerateFunc, mapper MapperFunc, reducer VoidReducerFunc, opts ...Option) error {
  207. _, err := MapReduce(generate, mapper, func(input <-chan interface{}, writer Writer, cancel func(error)) {
  208. reducer(input, cancel)
  209. }, opts...)
  210. if errors.Is(err, ErrReduceNoOutput) {
  211. return nil
  212. }
  213. return err
  214. }
  215. // WithContext customizes a mapreduce processing accepts a given ctx.
  216. func WithContext(ctx context.Context) Option {
  217. return func(opts *mapReduceOptions) {
  218. opts.ctx = ctx
  219. }
  220. }
  221. // WithWorkers customizes a mapreduce processing with given workers.
  222. func WithWorkers(workers int) Option {
  223. return func(opts *mapReduceOptions) {
  224. if workers < minWorkers {
  225. opts.workers = minWorkers
  226. } else {
  227. opts.workers = workers
  228. }
  229. }
  230. }
  231. func buildOptions(opts ...Option) *mapReduceOptions {
  232. options := newOptions()
  233. for _, opt := range opts {
  234. opt(options)
  235. }
  236. return options
  237. }
  238. func buildSource(generate GenerateFunc, panicChan *onceChan) chan interface{} {
  239. source := make(chan interface{})
  240. go func() {
  241. defer func() {
  242. if r := recover(); r != nil {
  243. panicChan.write(r)
  244. }
  245. close(source)
  246. }()
  247. generate(source)
  248. }()
  249. return source
  250. }
  251. // drain drains the channel.
  252. func drain(channel <-chan interface{}) {
  253. // drain the channel
  254. for range channel {
  255. }
  256. }
  257. func executeMappers(mCtx mapperContext) {
  258. var wg sync.WaitGroup
  259. defer func() {
  260. wg.Wait()
  261. close(mCtx.collector)
  262. drain(mCtx.source)
  263. }()
  264. var failed int32
  265. pool := make(chan lang.PlaceholderType, mCtx.workers)
  266. writer := newGuardedWriter(mCtx.ctx, mCtx.collector, mCtx.doneChan)
  267. for atomic.LoadInt32(&failed) == 0 {
  268. select {
  269. case <-mCtx.ctx.Done():
  270. return
  271. case <-mCtx.doneChan:
  272. return
  273. case pool <- lang.Placeholder:
  274. item, ok := <-mCtx.source
  275. if !ok {
  276. <-pool
  277. return
  278. }
  279. wg.Add(1)
  280. go func() {
  281. defer func() {
  282. if r := recover(); r != nil {
  283. atomic.AddInt32(&failed, 1)
  284. mCtx.panicChan.write(r)
  285. }
  286. wg.Done()
  287. <-pool
  288. }()
  289. mCtx.mapper(item, writer)
  290. }()
  291. }
  292. }
  293. }
  294. func newOptions() *mapReduceOptions {
  295. return &mapReduceOptions{
  296. ctx: context.Background(),
  297. workers: defaultWorkers,
  298. }
  299. }
  300. func once(fn func(error)) func(error) {
  301. once := new(sync.Once)
  302. return func(err error) {
  303. once.Do(func() {
  304. fn(err)
  305. })
  306. }
  307. }
  308. type guardedWriter struct {
  309. ctx context.Context
  310. channel chan<- interface{}
  311. done <-chan lang.PlaceholderType
  312. }
  313. func newGuardedWriter(ctx context.Context, channel chan<- interface{},
  314. done <-chan lang.PlaceholderType) guardedWriter {
  315. return guardedWriter{
  316. ctx: ctx,
  317. channel: channel,
  318. done: done,
  319. }
  320. }
  321. func (gw guardedWriter) Write(v interface{}) {
  322. select {
  323. case <-gw.ctx.Done():
  324. return
  325. case <-gw.done:
  326. return
  327. default:
  328. gw.channel <- v
  329. }
  330. }
  331. type onceChan struct {
  332. channel chan interface{}
  333. wrote int32
  334. }
  335. func (oc *onceChan) write(val interface{}) {
  336. if atomic.CompareAndSwapInt32(&oc.wrote, 0, 1) {
  337. oc.channel <- val
  338. }
  339. }