github.com/slspeek/camlistore_namedsearch@v0.0.0-20140519202248-ed6f70f7721a/pkg/blobserver/mergedenum.go (about) 1 /* 2 Copyright 2011 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package blobserver 18 19 import ( 20 "camlistore.org/pkg/blob" 21 "camlistore.org/pkg/context" 22 ) 23 24 const buffered = 8 25 26 // TODO: it'd be nice to make sources be []BlobEnumerator, but that 27 // makes callers more complex since assignable interfaces' slice forms 28 // aren't assignable. 29 func MergedEnumerate(ctx *context.Context, dest chan<- blob.SizedRef, sources []Storage, after string, limit int) error { 30 defer close(dest) 31 32 startEnum := func(source Storage) (*blob.ChanPeeker, <-chan error) { 33 ch := make(chan blob.SizedRef, buffered) 34 errch := make(chan error, 1) 35 go func() { 36 errch <- source.EnumerateBlobs(ctx, ch, after, limit) 37 }() 38 return &blob.ChanPeeker{Ch: ch}, errch 39 } 40 41 peekers := make([]*blob.ChanPeeker, 0, len(sources)) 42 errs := make([]<-chan error, 0, len(sources)) 43 for _, source := range sources { 44 peeker, errch := startEnum(source) 45 peekers = append(peekers, peeker) 46 errs = append(errs, errch) 47 } 48 49 nSent := 0 50 lastSent := "" 51 for nSent < limit { 52 lowestIdx := -1 53 var lowest blob.SizedRef 54 for idx, peeker := range peekers { 55 for !peeker.Closed() && peeker.MustPeek().Ref.String() <= lastSent { 56 peeker.Take() 57 } 58 if peeker.Closed() { 59 continue 60 } 61 sb := peeker.MustPeek() // can't be nil if not Closed 62 if lowestIdx == -1 || sb.Ref.String() < lowest.Ref.String() { // TODO: add cheaper Ref comparison function, avoiding String 63 lowestIdx = idx 64 lowest = sb 65 } 66 } 67 if lowestIdx == -1 { 68 // all closed 69 break 70 } 71 72 dest <- lowest 73 nSent++ 74 lastSent = lowest.Ref.String() 75 } 76 77 // Once we've gotten enough, ignore the rest of whatever's 78 // coming in. 79 for _, peeker := range peekers { 80 go peeker.ConsumeAll() 81 } 82 83 // If any part returns an error, we return an error. 84 var retErr error 85 for _, errch := range errs { 86 if err := <-errch; err != nil { 87 retErr = err 88 } 89 } 90 return retErr 91 }