Skip to content

Explicit resource management library (@matrixai/resources) #84

@CMCDragonkai

Description

@CMCDragonkai

I only discovered this proposal recently, it looks pretty cool.

But I built a resource management library required by our project Polykey (https://github.com/MatrixAI/js-polykey) inspired by python's with context and haskell's bracketing pattern in TS here: https://github.com/MatrixAI/js-resources

Some ideas from my library that might be interesting:

  1. Resources are always acquired in-order, and released in opposite order. Resources are also released in opposite order if during a sequence of resource acquisition, a certain resource failed to be acquired.
  2. Resource acquisition may be parameterised by prior resources acquired
     await withF(
       [
         async () => [async () => {}, 1],
         async ([a] = []) => [async () => {}, a + 1],
         async ([, b] = []) => [async () => {}, b + 1],
       ],
       async ([a, b, c]) => {
         expect(a).toBe(1);
         expect(b).toBe(2);
         expect(c).toBe(3);
       },
     );
    Originally this was based off the idea of letrec in various functional languages, but this was too difficult to make work in JavaScript's strict evaluation. So instead during the in-order sequence of resource acquisition, prior resources acquired can specialise subsequent resources acquired.
  3. Resource releasers are parameterised by errors thrown during resource usage, however they themselves do not need to rethrow the error, and they can ignore the error. This is important in some cases where releasing the resource changes depending on if there was an error during usage.
  4. The whole thing only uses arrow functions and async function generators. I did not use the async generator idiom explained in the README.md.
  5. The usage of withF and withG are optional. In certain situations, these bracketing abstractions are too limiting, such as during tail call recursion or when using while loops. In those cases, users are supposed to directly use ResourceAcquire and ResourceRelease types and can manage resources procedurally.
  6. It is intended that resource acquisition be compositional. So that some higher level resource can encapsulate the acquisition of multiple lower-level resources.

In our project, we are using all the features of the library, so everything has a usecase. See tests for further details.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions