question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Any example usage of `cleanup`?

See original GitHub issue

It will be nice to provide some example of using cleanup. I can’t understand why do we need it?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
robotlolitacommented, May 19, 2016

Quoting from a previous discussion on Gitter:

[cleanup] allows the task to declare how to collect its resources if you want to cancel its effects.

Imagine you write something like: race(delay(10), timeout(20000)), the task on the left will always complete first, which means that the task on the right should fail after 10 milliseconds. In this case, since both delay and timeout create new timers in the process, it’s important to remove those timers from the process and GC them, since otherwise a program like race(delay(10), timeout(2000)).fork(::console.log, ::console.log) would always run for 20 seconds.

In the current version of Task, this works in an awkward way (it’s going to be fixed in the redesign, to work like Siren’s Task https://github.com/siren-lang/siren/blob/master/runtime/src/Concurrency.siren):

  • A Task is an object of type: Task(α, β): new (computation: (reject: (α → Unit), resolve: (β → Unit)) → γ)[, cleanup: (γ → Unit)]

    That is, it takes two functions: “computation”, which is a function that takes two functions as arguments (reject and resolve). These functions are invoked to provide a value for the completion of the task.

  • computation is expected to return a value, of type γ. This value is referred to as “resources”, it contains a reference to the resources that were created by the computation (if any).

  • If the computation creates resources and returns those resources, you need to collect them. This is the role of cleanup. It takes whatever was returned by computation and destroys those resources (assuming this can be done). This could be a file handler, a timer (like in the case of delay and timeout there).

Given these, we can compose tasks with operations like race and know that our resources will be handled automatically and correctly for us (which is not something that can be done with Promises, for example). The awkward part is that the function running the Task (calling .fork) is the one that needs to deal with this right now, in the next version Task will handle this automatically as well.

The control.async module defines a few functions that make use of this, and the Task#concat method is basically race, so reading their source code might give you a more practical view of how this happens:

So you get:

const Task = require('data.task');

function delay(time) {
  return new Task((reject, resolve) => {
    return setTimeout(_ => resolve(), time)
  }, clearTimeout);
}

function timeout(time) {
  return new Task((reject, resolve) => {
    return setTimeout(_ => reject(), time)
  }, clearTimeout)
}

function noop() { }

function race(a, b) {
  const resourcesA = a.fork(cleanup, cleanup);
  const resourcesB = b.fork(cleanup, cleanup);

  function cleanup() {
    // Since this might run before we create all resources
    setTimeout(_ => {
      a.cleanup(resourcesA);
      b.cleanup(resourcesB);
    });
  }
}

Note that you shouldn’t store the resources in a lexical variable outside of the Task you’re creating (this is a bug in control.async rn), since running the task Twice, concurrently, would clobber the state and prevent some of the resources from being collected. Always return the resources from the Task’s computation function instead:

function tempFile(data) {
  let filename;
  return new Task((reject, resolve) => {
    filename = generateTempFilename();
    writeFile(filename, data, (error) => {
      if (error)  reject(error);
      else        resolve(filename);
    });
  }, () => removeFile(filename));
}

function cleanup() {
  setTimeout(_ => {
    task.cleanup(resourceA);
    task.cleanup(resourceB);
  });
}

const task = tempFile(someData);
const resourceA = task.fork(cleanup, cleanup);
const resourceB = task.fork(cleanup, cleanup);
// Now the first temporary file is still in the file system
// because the `filename` for that particular execution of the
// task was lost.
1reaction
robotlolitacommented, May 20, 2016

Creating and transforming Tasks stays the same:

const Task = require('folktale').data.task;

function delay(time) {
  return new Task((reject, resolve) => {
    return setTimeout(_ => resolve(), time)
  }, clearTimeout);
}

const helloIn10 = delay(10).map(v => "Hello!");

But instead of .fork() for running the tasks, you have a .run() method. The .run() method returns a TaskExecution object, which lets you cancel the task, or get the value of the task:

const execution = helloIn10.run();

// Cancelling a particular execution of a Task:
execution.cancel();

// Getting the value of executing a Task:
// (Future is a Monad, like Task, but it doesn't run any computation, 
// it just eventually provides a value)
execution.future().cata({
  Cancelled: _ => ...,
  Resolved: _ => ...,
  Rejected: _ => ...
});

// You can also use a promise, which lets you use async/await:
const value = await execution.promise();

TaskExecution objects take care of memoisation, providing futures, cancelling tasks, and collecting resources when the task finishes running or is cancelled, so this should make it easier for people to use Task.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Use cleanup in a sentence
The most voted sentence example for cleanup is The club needed a cleanup foll. ... They tend to shed some branches, so if...
Read more >
Cleanup Definition & Meaning - Merriam-Webster
1 of 3. noun. clean·​up ˈklēn-ˌəp. 1. : an act or instance of cleaning. The children helped with the cleanup. 2. : an...
Read more >
CLEAN UP (phrasal verb) definition and synonyms
Definition of CLEAN UP (phrasal verb): make a place tidy; wash someone; remove pollution from place or process; stop bad, unfair, or criminal...
Read more >
Cleanup Vs. Clean Up | Cleanup Definition & Meaning
When you need a term meaning (1) to make clean or orderly, or (2) to make oneself clean, use clean up—two words. In...
Read more >
Cleanup vs. Clean Up: How to Choose the Right Word
The noun "cleanup" (one word), sometimes written as "clean-up," refers to an event during which some type of cleaning takes place. For example, ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found