Skip to content

Investigate creating new interface for file/sparql store backends #63

Closed

Description

@jvherweg

We should look into generalizing ResourceStore behaviour. E.g. if one of them rejects setting a Representation at a certain URI because there already is a container there, we want this to be consistent across stores. One idea is to have a DataResourceStore which handles all this behaviour and takes as input a DataAccessor (names totally up for change). DataAccessors would then have functions such as hasResource, createContainer, setResource, etc. which can be used to implement the behaviour. In the case of a file data accessor for example, hasResource would be implemented by fs.lstat, while in the case of a sparql backend it would be an ASK query.

The main question is if this can be done (cleanly) without losing any functionality. We would have to investigate which functions would all be needed and to make sure there is no drastic change in efficiency because of this.

Some potential issues I though of (but there probably are plenty more):

  • Probably need a different function to write a Representation and its metadata since metadata is always going to be a Quad array while a Representation can be anything (unless there is some way to also handle this in the DataResourceStore).
  • SPARQL stores only accept Quad streams as Representation, so there still needs to be a way to handle cases like this.
  • PATCH/modifyResource calls probably still have to be sent directly to the accessor since in the case of SPARQL these get sent directly to the endpoint.

Activity

  1. added
    ☀️ enhancement
    on Aug 20, 2020
  2. smessie commented on Aug 20, 2020

    @smessie
    Member

    I've worked this idea out a bit further and come to the following:

    class DataResourceStore implements ResourceStore
        baseRequestURI: string;
        dataAccessor: string;
    
        constructor(baseRequestURI: string, dataAccessor: DataAccessor)
    
        // In this abstracted implementation I have always placed the functions that this method of the dataAccessor could/should possibly call.
        addResource {
          - ensureValidationContainerPath( ..., path.endsWith('/'))
          - getResourceType
          - createContainer
          - setResource
        }
        setRepresentation {
          - ensureValidationContainerPath( ..., true)
          - getResourceType
          - createContainer
          - setResource
        }
        deleteResource {
          - getResourceType
          - deleteResource
          - deleteContainer
        }
        getRepresentation {
          - getResourceType
          - getResourceRepresentation
          - getContainerRepresentation
        }
        modifyResource {
          - modifyResource
       }
    interface DataAccessor
        // Below are the common functions that require a specific implementation for the different stores.
    
        // This could reuse the LinkTypes.ts and return LINK_TYPE_LDPC, LINK_TYPE_LDPR, or null for something
        // else (like if a path is nor a directory nor a file in the filesystem), or undefined if path does not exist yet.
        getResourceType(path: string)
        createContainer(path: string, containerName: string, metadata?: Quad[])
        setResource(path: string, resourceName: string, data: Readable, metadata?: Quad[])
        ensureValidContainerPath(path: string, allowRecursiveCreation: boolean)
        deleteResource(path: string)
        deleteContainer(path: string)
        modifyResource(path: string, patch: Patch)
        getResourceRepresentation(path: string)
        getContainerRepresentation(path: string)
    class FileStore implements DataAccessor
    // Implements the methods from DataAccessor
    class SparqlStore implements DataAccessor
    // Implements the methods from DataAccessor

    When I worked this out, I immediately came across some advantages and disadvantages.
    Advantages:

    • The behaviour in all stores will be the same because based on the input the same functions are always called from the DataAccessor.
    • Adjusting the behaviour at a later stage only has to be done once.
    • Storage details are further abstracted from the behaviour. This can clarify the high-level view.

    Disadvantages:

    • It can be more difficult to follow what happens in detail because some things are unnecessarily broken down. For example, to create a general behaviour, for the recursive creation of a container, there must be a function to create a container per container while in the file system, this can easily be done in one go with mkdir(path, { recursive: true }).
    • Another example of inefficiency is having to calculate the file status (Stats) twice in getRepresentation because generalization in getRepresentation does not return the Stats, but a more generic result that says what type of path it is, after which in getResourceRepresentation and getContainerRepresentation, these Stats must be retrieved again.
      I don't have a full implementation for the sparql store yet, so inefficiencies may arise there as well.

    In the stores, it quickly becomes storage specific, so not much more than just the initial behaviour can be jointly determined based on the input (headers).


    Another solution would be to move more common code to the InteractionController so that the same operations are written only once there.

    As an example, for getRepresentation of the FileResourceStore, the following code might also be moved to the InteractionController as it only depends on the input and is not storage specific.
    https://github.com/solid/community-server/blob/aa510bc6b8a604044b94cfc5bc756a3d280466b8/src/storage/FileResourceStore.ts#L147-L162

    In that case only these storage specific function calls will remain based on what we get back from the InteractionController.
    https://github.com/solid/community-server/blob/aa510bc6b8a604044b94cfc5bc756a3d280466b8/src/storage/FileResourceStore.ts#L164-L169

  3. RubenVerborgh commented on Aug 21, 2020

    @RubenVerborgh
    Member

    (After offline discussion with @smessie and @joachimvh):

    • Let's pursue the second option, in which we inject a reusable object into ResourceStore implementations; file-based and SPARQL-based implementations would then directly implement ResourceStore such that they remain in control. This ensures that the steps are executed correctly across stores; we still need to test for every store that they invoke the correct steps.
    • Possibly, let's use inheritance to provide a base class for ResourceStore that already calls the correct steps. Inheriting classes can still override.
  4. smessie commented on Aug 21, 2020

    @smessie
    Member

    In working out the second option, I come up with the following (2a):

    Method and class names are suggestive, the class ResourceStoreController could also extend the InteractionController instead of passing an instance through its constructor (2b).

    class ResourceStoreController
        baseRequestURI: string
        interactionController: InteractionController
        supportedDataTypes: Set<string>
    
        constructor(baseRequestURI: string, interactionController: InteractionController, supportedDataTypes: Set<string>)
    
        getBehaviourAddResource(representation: Representation): SetBehaviour
            return { isContainer: boolean, newIdentifier: string }
    
        getBehaviourSetRepresentation(identifier: ResourceIdentifier, representation: Representation): SetBehaviour
            return { isContainer: boolean, newIdentifier: string }
    
        validateDeletePath(path: string): void
            throws MethodNotAllowedError
    
        parseIdentifier(identifier: ResourceIdentifier): string
            throws NotFoundHttpError

    The behaviour of deleteResource and getRepresentation is difficult to generalize because it depends on the ResourceType to which the incoming URI points (resource/container/non-existent) which is immediately storage specific.


    The third option is the use of inheritance, which has the advantage that we can generalize the behaviour of deleteResource and getRepresentation using abstract functions.
    This could result in the following (names are again suggestive):

    abstract class BaseResourceStore
        baseRequestURI: string
        interactionController: InteractionController
        supportedDataTypes: Set<string>
    
        constructor(baseRequestURI: string, interactionController: InteractionController, supportedDataTypes: Set<string>)
    
        addResource
          /* Implements the behaviour just as it would be defined in `getBehaviourAddResource`. */
    
        setRepresentation
          /* Implements the behaviour just as it would be defined in `getBehaviourSetRepresentation`. */
    
        deleteResource
          /* Uses the abstract functions declared below to implement a generic behaviour. */
    
        getRepresentation
          /* Uses the abstract functions declared below to implement a generic behaviour. */
    
        (abstract) modifyRepresentation
          /* Requires further research if similar behaviour can be generalized when implemented by multiple stores,
    but for now perhaps an abstract function still being implemented by the stores. */
    
        validateDeletePath(path: string): void
            throws MethodNotAllowedError
    
        parseIdentifier(identifier: ResourceIdentifier): string
            throws NotFoundHttpError
    
        abstract getResourceType(path: string): string | undefined;
    
        abstract deleteSpecificResource(resourcePath: string): Promise<void>;
    
        abstract deleteContainer(containerPath: string): Promise<void>;
    
        abstract getResourceRepresentation(resourcePath: string): Promise<Representation>;
    
        abstract getContainerRepresentation(containerPath: string): Promise<Representation>;

    For example, the SPARQL store could overwrite the getRepresentation method because it requires the same implementation regardless of whether it is a container or a resource (if we store its children in the container graph and not in its corresponding metadata graph).

  5. RubenVerborgh commented on Aug 21, 2020

    @RubenVerborgh
    Member

    Good! Quick quesions:

    • What does validateDeletePath do?
    • What does SetBehaviour look like?
  6. RubenVerborgh commented on Aug 21, 2020

    @RubenVerborgh
    Member

    Note: deleteSpecificResource can be deleteDocument (resources in LDP are either documents or containers).

  7. RubenVerborgh commented on Aug 21, 2020

    @RubenVerborgh
    Member

    parseIdentifier, we probably want to return { path, slug }.

  8. smessie commented on Aug 21, 2020

    @smessie
    Member
    • What does validateDeletePath do?

    I already have a local implementation of this, does this make it any clearer?

    /**
     * Check if the given path is a valid path to perform a delete operation on.
     * @param path - Path to check. Request URI without the base URI.
     *
     * @throws {@link MethodNotAllowedHttpError}
     * If the path points to the root container.
     */
    export const validateDeletePath = (path: string): void => {
      if (path === '' || ensureTrailingSlash(path) === '/') {
        throw new MethodNotAllowedHttpError('Cannot delete root container.');
      }
    };

    • What does SetBehaviour look like?

    Something like

    interface SetBehaviour {
        /**
         * Whether a new container or a resource should be created based on the given parameters.
         */
        isContainer: boolean;
    
        /**
         * The identifier path the new resource should have.
         */
        newIdentifier: string;
    }

    (The results of the functions in InteractionController).


    parseIdentifier, we probably want to return { path, slug }.

    I based myself on the current implementation used by FileResourceStore, SparqlResourceStore and SimpleResourceStore. We could extend it, but which slug do you mean? The slug is usually extracted from the Slug header in the RepresentationMetadata and has nothing to do with the identifier (except in the specific case of setRepresentation).

    Current implementation (to be rewritten without baseRequestURI being passed)
    /**
     * Strips the baseRequestURI from the identifier and checks if the stripped base URI matches the store's one.
     * @param identifier - Incoming identifier.
     * @param baseRequestURI - The base from the store.
     *
     * @throws {@link NotFoundHttpError}
     * If the identifier does not match the baseRequestURI path of the store.
     *
     * @returns A string representing the relative path.
     */
    export const parseIdentifier = (identifier: ResourceIdentifier, baseRequestURI: string): string => {
      if (!identifier.path.startsWith(baseRequestURI)) {
        throw new NotFoundHttpError();
      }
      return identifier.path.slice(baseRequestURI.length);
    };
  9. jvherweg commented on Aug 27, 2020

    @jvherweg
    MemberAuthor

    I had a more in-depth look into this and worked out the DataAccessor part out more extensively. Specifically, I wrote the entire DataResourceStore in pseudo-ish code to see what it would look like. The result of that which you can see here, with comments discussing some potential problems in there.

    There are some issues regarding efficiency but I think most can be resolved, and in the end the question is also how relevant these performance hits would be? In theory it would also be possible to have a PerformantFileResourceStore separate from this should that be really necessary, but then both would have to be maintained so probably back at square 1 there.

    In my opinion as I see it now it feels and looks quite clean and the additional inefficiency might be worth it. Additionally, converting the SimpleResourceStore to a complete InMemoryResourceStore should be quite easy with that format (which for me is a good indication of the advantages of this solution).

    Regarding the other 2 solutions, I haven't worked those out (yet?), but my opinions so far:

    Injecting a controller into the file/sparql stores:

    • I think this would be quite similar to what we already have. There are a few things from the file store that can probably be abstracted to such an external class, but there is only so much you can do when calling an independent external class.
    • Unless, and this is something I haven't worked out all yet but popped in my head, that class returns a behaviour object that contains a set of steps the store has to execute (an array of enums?).

    Inheriting from a DataResourceStore:

    • I don't think this is going to be the solution. The idea here is the the file/sparql store can override the methods if they can do it more efficiently, but in practice this is going to be every function I think so at that point the inheritance doesn't have much use left.
  10. RubenVerborgh commented on Sep 2, 2020

    @RubenVerborgh
    Member

    OK with your proposal at https://gist.github.com/joachimvh/e0e4cf89b5c889cfb81e331503c2af20

    I would just give DataAccessor method names that are on the low level, such as read[Data], write[Data], change[Data], delete[Data].

    Plus we need a detailed comment on DataResourceStore explaining how this design works, and its performance trade-off. (I would also name it DataAccessorBasedStore or so.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

☀️ enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions