Home Download Docs Code Community
     1	/*
     2	Copyright 2013 The Perkeep Authors
     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		"context"
    21		"sync"
    22	
    23		"perkeep.org/pkg/blob"
    24	)
    25	
    26	// EnumerateAll runs fn for each blob in src.
    27	// If fn returns an error, iteration stops and fn isn't called again.
    28	// EnumerateAll will not return concurrently with fn.
    29	func EnumerateAll(ctx context.Context, src BlobEnumerator, fn func(blob.SizedRef) error) error {
    30		return EnumerateAllFrom(ctx, src, "", fn)
    31	}
    32	
    33	// EnumerateAllFrom is like EnumerateAll, but takes an after parameter.
    34	func EnumerateAllFrom(ctx context.Context, src BlobEnumerator, after string, fn func(blob.SizedRef) error) error {
    35		const batchSize = 1000
    36		var mu sync.Mutex // protects returning with an error while fn is still running
    37		errc := make(chan error, 1)
    38		for {
    39			ch := make(chan blob.SizedRef, 16)
    40			n := 0
    41			go func() {
    42				var err error
    43				for sb := range ch {
    44					if err != nil {
    45						continue
    46					}
    47					mu.Lock()
    48					err = fn(sb)
    49					mu.Unlock()
    50					after = sb.Ref.String()
    51					n++
    52				}
    53				errc <- err
    54			}()
    55			err := src.EnumerateBlobs(ctx, ch, after, batchSize)
    56			if err != nil {
    57				mu.Lock() // make sure fn callback finished; no need to unlock
    58				return err
    59			}
    60			if err := <-errc; err != nil {
    61				return err
    62			}
    63			if n == 0 {
    64				return nil
    65			}
    66		}
    67	}
    68	
    69	// RefTypes returns a list of blobref types appearing on the provided enumerator.
    70	// A blobref type is a string like "sha1", or whatever is on the left side
    71	// of the hyphen in a blobref.
    72	// To get the alphabet valid for the right side of the hyphen, use blob.TypeAlphabet(type).
    73	func RefTypes(src BlobEnumerator) ([]string, error) {
    74		// TODO(bradfitz): implement, with various short enumerate
    75		// reads at the right places.
    76		return []string{"sha1"}, nil
    77	}
Website layout inspired by memcached.
Content by the authors.