fix: dir duplicate creation (close #1687)

This commit is contained in:
Noah Hsu 2022-09-19 13:43:23 +08:00
parent 5548ab62ac
commit d8dc8d8623

View File

@ -181,42 +181,49 @@ func Other(ctx context.Context, storage driver.Driver, args model.FsOtherArgs) (
} }
} }
var mkdirG singleflight.Group[interface{}]
func MakeDir(ctx context.Context, storage driver.Driver, path string) error { func MakeDir(ctx context.Context, storage driver.Driver, path string) error {
if storage.Config().CheckStatus && storage.GetStorage().Status != WORK { if storage.Config().CheckStatus && storage.GetStorage().Status != WORK {
return errors.Errorf("storage not init: %s", storage.GetStorage().Status) return errors.Errorf("storage not init: %s", storage.GetStorage().Status)
} }
path = utils.StandardizePath(path) path = utils.StandardizePath(path)
// check if dir exists key := Key(storage, path)
f, err := Get(ctx, storage, path) _, err, _ := mkdirG.Do(key, func() (interface{}, error) {
if err != nil { // check if dir exists
if errs.IsObjectNotFound(err) { f, err := Get(ctx, storage, path)
parentPath, dirName := stdpath.Split(path) if err != nil {
err = MakeDir(ctx, storage, parentPath) if errs.IsObjectNotFound(err) {
if err != nil { parentPath, dirName := stdpath.Split(path)
return errors.WithMessagef(err, "failed to make parent dir [%s]", parentPath) err = MakeDir(ctx, storage, parentPath)
if err != nil {
return nil, errors.WithMessagef(err, "failed to make parent dir [%s]", parentPath)
}
parentDir, err := Get(ctx, storage, parentPath)
// this should not happen
if err != nil {
return nil, errors.WithMessagef(err, "failed to get parent dir [%s]", parentPath)
}
err = storage.MakeDir(ctx, parentDir, dirName)
if err == nil {
ClearCache(storage, parentPath)
}
return nil, errors.WithStack(err)
} else {
return nil, errors.WithMessage(err, "failed to check if dir exists")
} }
parentDir, err := Get(ctx, storage, parentPath)
// this should not happen
if err != nil {
return errors.WithMessagef(err, "failed to get parent dir [%s]", parentPath)
}
err = storage.MakeDir(ctx, parentDir, dirName)
if err == nil {
ClearCache(storage, parentPath)
}
return errors.WithStack(err)
} else { } else {
return errors.WithMessage(err, "failed to check if dir exists") // dir exists
if f.IsDir() {
return nil, nil
} else {
// dir to make is a file
return nil, errors.New("file exists")
}
} }
} else { })
// dir exists return err
if f.IsDir() {
return nil
} else {
// dir to make is a file
return errors.New("file exists")
}
}
} }
func Move(ctx context.Context, storage driver.Driver, srcPath, dstDirPath string) error { func Move(ctx context.Context, storage driver.Driver, srcPath, dstDirPath string) error {