2022-07-07 18:56:59 +00:00
|
|
|
package sync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
|
2023-01-23 12:52:39 +00:00
|
|
|
"github.com/databricks/bricks/libs/sync/repofiles"
|
2022-10-04 22:12:57 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2022-07-07 18:56:59 +00:00
|
|
|
)
|
|
|
|
|
2022-10-04 22:12:57 +00:00
|
|
|
// See https://docs.databricks.com/resources/limits.html#limits-api-rate-limits for per api
|
|
|
|
// rate limits
|
|
|
|
const MaxRequestsInFlight = 20
|
|
|
|
|
2022-12-12 13:31:06 +00:00
|
|
|
func syncCallback(ctx context.Context, repoFiles *repofiles.RepoFiles) func(localDiff diff) error {
|
2022-09-14 15:50:29 +00:00
|
|
|
return func(d diff) error {
|
2022-10-04 22:12:57 +00:00
|
|
|
// Abstraction over wait groups which allows you to get the errors
|
|
|
|
// returned in goroutines
|
|
|
|
var g errgroup.Group
|
|
|
|
|
|
|
|
// Allow MaxRequestLimit maxiumum concurrent api calls
|
|
|
|
g.SetLimit(MaxRequestsInFlight)
|
|
|
|
|
2022-11-21 22:42:09 +00:00
|
|
|
for _, remoteName := range d.delete {
|
|
|
|
// Copy of remoteName created to make this safe for concurrent use.
|
|
|
|
// directly using remoteName can cause race conditions since the loop
|
|
|
|
// might iterate over to the next remoteName before the go routine function
|
2022-10-04 22:12:57 +00:00
|
|
|
// is evaluated
|
2022-11-21 22:42:09 +00:00
|
|
|
remoteNameCopy := remoteName
|
2022-10-04 22:12:57 +00:00
|
|
|
g.Go(func() error {
|
2022-12-12 13:31:06 +00:00
|
|
|
err := repoFiles.DeleteFile(ctx, remoteNameCopy)
|
2022-10-04 22:12:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-11-21 22:42:09 +00:00
|
|
|
log.Printf("[INFO] Deleted %s", remoteNameCopy)
|
2022-10-04 22:12:57 +00:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2022-12-12 13:31:06 +00:00
|
|
|
for _, localRelativePath := range d.put {
|
2022-11-21 22:42:09 +00:00
|
|
|
// Copy of localName created to make this safe for concurrent use.
|
2022-12-12 13:31:06 +00:00
|
|
|
localRelativePathCopy := localRelativePath
|
2022-10-04 22:12:57 +00:00
|
|
|
g.Go(func() error {
|
2022-12-12 13:31:06 +00:00
|
|
|
err := repoFiles.PutFile(ctx, localRelativePathCopy)
|
2022-10-04 22:12:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-12-12 13:31:06 +00:00
|
|
|
log.Printf("[INFO] Uploaded %s", localRelativePathCopy)
|
2022-10-04 22:12:57 +00:00
|
|
|
return nil
|
|
|
|
})
|
2022-09-14 15:50:29 +00:00
|
|
|
}
|
2022-10-04 22:12:57 +00:00
|
|
|
// wait for goroutines to finish and return first non-nil error return
|
|
|
|
// if any
|
|
|
|
if err := g.Wait(); err != nil {
|
|
|
|
return err
|
2022-09-14 15:50:29 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|