Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 10 | Comments: 37

filter by tags archive

ChallengeThe directory tree

time to read 3 min | 428 words

Since people seems to really enjoy posts like this, here is another one. This time it is an interesting issue that I dealt with today.

Given a set of versioned file, you need to cache them locally. Note that IPersistentCache semantics means that if you put a value in it, is is always going to remain there.

Here is the skeleton:

public interface IPersistentCache
{
	void Set(string key, params string[] items);
	string[] Get(string key);
}

public enum Recursion
{
	None,
	OneLevel,
	Full
}

public class VersionedFile
{
	public int Version;
	public string Name;
}

public class FileSystemCache : IFileSystemCache 
{
	IPersistentCache cache;
	
	public FileSystemCache(IPersistentCache cahce)
	{
		this.cache = cache;
	}
	
	public void Add(VersionedFile[] files)
	{
		// to do
	}

	public string[] ListFilesAndFolders(string root, int version, Recursion recursion)
	{
		// to do
	}
	
}

How would you implement this? Note that your only allowed external dependency is the ICache interface.

The usage is something like this:

// given 
var fsc = new FileSystemCache(cache);
fsc.Add(new []
{
      new VersionFile{Version = 1, Name = "/"},
      new VersionFile{Version = 1, Name = "/foo"},
      new VersionFile{Version = 1, Name = "/foo/bar"},
      new VersionFile{Version = 1, Name = "/foo/bar/text.txt"},
});
fsc.Add(new []
{

      new VersionFile{Version = 2, Name = "/"},
      new VersionFile{Version = 2, Name = "/foo"},
      new VersionFile{Version = 2, Name = "/foo/bar"},
      new VersionFile{Version = 2, Name = "/foo/bar/text.txt"},
      new VersionFile{Version = 2, Name = "/test.txt"},
});

// then 
fsc.ListFilesAndFolders("/", 1, Recursion.None) == { "/" } 

fsc.ListFilesAndFolders("/", 1, Recursion.OneLevel) == { "/", "/foo", } 

fsc.ListFilesAndFolders("/", 2, Recursion.OneLevel) == { "/", "/foo", "test.txt" } 

fsc.ListFilesAndFolders("/", 1, Recursion.Full) == { "/", "/foo", "/foo/bar", "/foo/bar/text.txt"}  

You can assume that all paths are '/' separated and they always starts with '/'.

More posts in "Challenge" series:

  1. (28 Apr 2015) What is the meaning of this change?
  2. (26 Sep 2013) Spot the bug
  3. (27 May 2013) The problem of locking down tasks…
  4. (17 Oct 2011) Minimum number of round trips
  5. (23 Aug 2011) Recent Comments with Future Posts
  6. (02 Aug 2011) Modifying execution approaches
  7. (29 Apr 2011) Stop the leaks
  8. (23 Dec 2010) This code should never hit production
  9. (17 Dec 2010) Your own ThreadLocal
  10. (03 Dec 2010) Querying relative information with RavenDB
  11. (29 Jun 2010) Find the bug
  12. (23 Jun 2010) Dynamically dynamic
  13. (28 Apr 2010) What killed the application?
  14. (19 Mar 2010) What does this code do?
  15. (04 Mar 2010) Robust enumeration over external code
  16. (16 Feb 2010) Premature optimization, and all of that…
  17. (12 Feb 2010) Efficient querying
  18. (10 Feb 2010) Find the resource leak
  19. (21 Oct 2009) Can you spot the bug?
  20. (18 Oct 2009) Why is this wrong?
  21. (17 Oct 2009) Write the check in comment
  22. (15 Sep 2009) NH Prof Exporting Reports
  23. (02 Sep 2009) The lazy loaded inheritance many to one association OR/M conundrum
  24. (01 Sep 2009) Why isn’t select broken?
  25. (06 Aug 2009) Find the bug fixes
  26. (26 May 2009) Find the bug
  27. (14 May 2009) multi threaded test failure
  28. (11 May 2009) The regex that doesn’t match
  29. (24 Mar 2009) probability based selection
  30. (13 Mar 2009) C# Rewriting
  31. (18 Feb 2009) write a self extracting program
  32. (04 Sep 2008) Don't stop with the first DSL abstraction
  33. (02 Aug 2008) What is the problem?
  34. (28 Jul 2008) What does this code do?
  35. (26 Jul 2008) Find the bug fix
  36. (05 Jul 2008) Find the deadlock
  37. (03 Jul 2008) Find the bug
  38. (02 Jul 2008) What is wrong with this code
  39. (05 Jun 2008) why did the tests fail?
  40. (27 May 2008) Striving for better syntax
  41. (13 Apr 2008) calling generics without the generic type
  42. (12 Apr 2008) The directory tree
  43. (24 Mar 2008) Find the version
  44. (21 Jan 2008) Strongly typing weakly typed code
  45. (28 Jun 2007) Windsor Null Object Dependency Facility

Comments

Thomas Krause

So there is no way I can override a value in IPersistentCache? e.g. I can't do:

cache.Set("a", "test");

cache.Set("a", "nother test");

Without this limitation it should be easier. I use the path to the directory or file to be cached as a key in IPersistentCache and put the path + version to the file as a single item in its value arrays (with some separator like ":"). Then I add the item to the parent directory's item array (again path + version).

Of course adding this item means getting the complete array, building another array and setting this as the new value, which is far from ideal, but you could propably make this more performant by growing the array in larger sizes and setting items in the returned instance directly (if Get doesn't return a clone, but the actual instance of the array).

Another issue with this solution is that you have to enumerate through all versions of files in a directory even if you don't need them.

Other than that the lookup is simply done by getting the values for the path specified in ListFilesAndFolders enumerating them and depending on the recursion mode make further lookups for subdirectories.

Without the possibility to override a value in the cache, you could still simulate something like this with some sort of convention. For example, the first 2 entries are stored in key "PATHNAME", the next 4 are stored in "PATHNAME:2", the next 8 in "PATHNAME:3" ...

But Of course this requires further lookups and is ugly as hell...

Interesting challenge however, I'm excited to see your solution.

Ayende Rahien

Thomas,

Each key have a single unique value.

You can do:

cache.Set("a", "test");

cache.Set("a", "nother test");

and then cache.Get("a") would return "another test".

You are in the right path.

Joshua McKinney

what's your target perf for Add / List? O(?)

Ayende Rahien

O(1), I init the list with the 101 capacity, so it should do no memory alloc

Mark Henke

I know this does not meet all of your requirements, but to help ease my easily-confused brain, here is a rough draft, unit tested based upon your usage data. Note that when you say "no external dependencies" I assume that means no list processing, and my array experience is weak at best.

public class FileSystemCache : IFileSystemCache

{

    IPersistentCache cache;


    public FileSystemCache(IPersistentCache cache)

    {

        this.cache = cache;

    }


    public void Add(VersionedFile[] files)

    {

        foreach (VersionedFile root in files)

        {

            string[] paths = new string[files.Length];

            int files_processed = 0;


            foreach (VersionedFile child in files)

            {

                if (path_is_root(root, child))

                {

                    paths[files_processed] = child.Name;

                    files_processed++;

                }

            }


            this.cache.Set(get_key(root.Name,root.Version), paths);

        }

    }


    private static bool path_is_root(VersionedFile root, VersionedFile      child)

    {

        return root.Version == child.Version &&    child.Name.Contains(root.Name);

    }


    public string[] ListFilesAndFolders(string root, int version, Recursion recursion)

    {

        string[] files = this.cache.Get( get_key(root, version));

        int max_depth = get_max_depth(files.Length, recursion);

        string[] files_to_return = new string[files.Length];

        int files_processed = 0;


        foreach (string file_path in files)

        {

            if (get_depth(root, file_path) <= max_depth)

            {

                files_to_return[files_processed] = file_path;

                files_processed++;

            }

        }


        return files_to_return;

    }


    private static string get_key(string root, int version)

    {

        return root + ":" + version;

    }


    public int get_depth(string root, string child)

    {

        char[] delimiter = new char[] { '/' };

        return (child.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).Length - root.Split(delimiter, StringSplitOptions.RemoveEmptyEntries).Length);

    }


    private int get_max_depth(int number_of_files, Recursion recursion)

    {

        switch (recursion)

        {

            case Recursion.None:

                return 0;

            case Recursion.OneLevel:

                return 1;

            default:

                return number_of_files;

        }

    }


}
alberto

I have posted a solution at my website, <a href="http://sharpbites.blogspot.com/2008/04/ayendes-challenge-2-directory-tree.html>here . :)

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

  1. Production postmortem: The case of the memory eater and high load - about one day from now
  2. Production postmortem: The case of the lying configuration file - 3 days from now
  3. Production postmortem: The industry at large - 4 days from now
  4. The insidious cost of allocations - 5 days from now
  5. Find the bug: The concurrent memory buster - 6 days from now

And 4 more posts are pending...

There are posts all the way to Sep 10, 2015

RECENT SERIES

  1. Find the bug (5):
    20 Apr 2011 - Why do I get a Null Reference Exception?
  2. Production postmortem (10):
    14 Aug 2015 - The case of the man in the middle
  3. What is new in RavenDB 3.5 (7):
    12 Aug 2015 - Monitoring support
  4. Career planning (6):
    24 Jul 2015 - The immortal choices aren't
View all series

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats