Cancel or Overwrite a Timer

    +

    Goal: Demonstrate the functionality for canceling or overwriting an Eventing Timer.

    Implementation: Create a JavaScript function that contains an OnUpdate handler and a Timer callback function. The handler listens for mutations or data-changes within a specified source bucket. When any document within the bucket is created or modified, the handler executes a user-defined routine. In this example, we rely on a control document which if mutated controls whether a Timer will be created, canceled, or overwritten.

    • Test 1: The control document is created or mutated in such a way a Timer is created and fires approximately 60 seconds in the future at which point a document is written to another bucket. The original control document, in the source bucket, is not changed.

    • Test 2: The control document is mutated in such a way that any existing Timer with the reference of the control document’s id (meta.id) is canceled. This has no effect if the Timer created has already fired.

    • Test 3: The control document is mutated in such a way that any existing Timer with the reference of the control document’s id (meta.id) is overwritten. This is equivalent to canceling a timer that already exists, and then creating a new Timer that will fire approximately 60 seconds in the future.

    Preparations (Common)

    For this example, three buckets 'source', 'target', and 'metadata', are required. Note the metadata bucket for Eventing can be shared with other Eventing functions. Make all three buckets with minimum size of 100MB.

    For steps to create buckets, see Create a Bucket.

    The 'metadata' bucket is for the sole use of the Eventing system. Do not add, modify, or delete documents from this bucket. In addition do not drop or flush or delete the bucket while you have any deployed Eventing functions.

    Setup:

    1. Access the Couchbase Web Console > Buckets page.

      • You should see the following once you have created your buckets:

        cancel overwrite timer 01 buckets
    2. Click the Documents link of the source bucket.

      • You should see no user records.

        cancel overwrite timer 01 documents
      • Click Add Document in the upper right banner.

      • In the Add Document dialog, specify the name type_of_interest::1 as the New Document ID.

        cancel overwrite timer 01 add document
      • Click Save. In the Edit Document dialog, the following text is displayed:

        {
        "click": "to edit",
        "with JSON": "there are no reserved field names"
        }
      • Replace the above text with the following JSON document via copy and paste.

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": false,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 1
        }
        cancel overwrite timer 01 docdata
      • Click Save.

    3. From the Couchbase Web Console > Eventing page, click ADD FUNCTION, to add a new Function. The ADD FUNCTION dialog appears.

    4. In the ADD FUNCTION dialog, for individual Function elements provide the below information:

      • For the Source Bucket drop-down, select source.

      • For the Metadata Bucket drop-down, select metadata.

      • Enter cancel_overwrite_timer as the name of the Function you are creating in the Function Name text-box.

      • [Optional Step] Enter text Explore creating, canceling, and overwriting timers, in the Description text-box.

      • For the Settings option, use the default values.

      • For the Bindings option, add just one binding.

        • For the binding, select the "bucket alias", specify tgt_bkt as the "alias name" of the bucket, select target as the associated bucket, and select "read and write".

      • After configuring your settings the ADD FUNCTION dialog should look like this:

        cancel overwrite timer 01 settings
    5. After providing all the required information in the ADD FUNCTION dialog, click Next: Add Code. The cancel_overwrite_timer dialog appears.

      • The cancel_overwrite_timer dialog initially contains a placeholder code block. You will substitute your actual cancel_overwrite_timer code in this block.

        cancel overwrite timer 02 editor with default
      • Copy the following Function, and paste it in the placeholder code block of cancel_overwrite_timer dialog.

        function DocTimerCallback(context) {
           log('From DocTimerCallback: timer fired', context);
        
           // Create a new document as per our received context in another bucket
           tgt_bkt[context.docId] = context; // upsert the context as our new doc
        }
        
        function OnUpdate(doc,meta) {
           // You would typically filter to mutations of interest
           if (doc.type != 'type_of_interest') return;
        
           // You would typically look at some key conditions to decide what to do
           if (doc.needed_condition === true && doc.cancel_timer === false) {
               if (doc.overwrite_timer === true) {
                 log('From OnUpdate: overwriting timer with same reference', meta.id);
               } else {
                 log('From OnUpdate: creating timer', meta.id);
               }
               // Create a timestamp 60 seconds from now
               var oneMinuteFromNow = new Date(); // Get current time & add 60 sec. to it.
               oneMinuteFromNow.setSeconds(oneMinuteFromNow.getSeconds() + 60);
        
               // Create a document to use as out for our context
               var context = {docId : meta.id, random_text : "arbitrary text", "tmr_time_to_fire": oneMinuteFromNow};
               createTimer(DocTimerCallback, oneMinuteFromNow, meta.id, context);
            }
            if (doc.cancel_timer === true && doc.overwrite_timer === false) {
               // Cancel an existing timer (if it is active) by reference meta.id
               if (cancelTimer(DocTimerCallback, meta.id)) {
                   log('From OnUpdate: cancel request, timer was canceled',meta.id);
               } else {
                   log('From OnUpdate: cancel request, no such timer may have fired',meta.id);
               }
            }
            if (doc.cancel_timer === true && doc.overwrite_timer === true) {
                log('From OnUpdate: both cancel and overwrite, will ignore',meta.id);
            }
        }

        After pasting, the screen appears as displayed below:

        cancel overwrite timer 03 editor with code
      • Click Save.

      • To return to the Eventing screen, click the '< back to Eventing' link (below the editor) or click Eventing tab.

    6. The OnUpdate routine specifies that when a change occurs to data within the bucket, actions will be processed according to the field within the document. First we ignore all documents that do not have a doc.type of "type_of_interest" this is the control document. Next we use the field as "needed_condition", "cancel_timer", and "overwrite_timer" to determine which action we take.

      • If "needed_condition" is true and both "cancel_timer", and "overwrite_timer" are false we will create a Timer that will fire approximately 60 seconds in the future.

      • If "needed_condition" is true and "cancel_timer" is true we will cancel the existing Timer.

      • If "needed_condition" is true and "overwrite_timer" is true we will overwrite the existing Timer with a new one (assuming that our Timer is still active) which will fire approximately 60 seconds in the future.

      • If both "cancel_timer" and "overwrite_timer" are true it is considered an error and no action is taken.

      • In the event a Timer created by this Function fires the callback DocTimerCallback executes and will write a new document with the same KEY (as the "source" bucket) into the "destination" bucket.

    7. From the Eventing screen, click the cancel_overwrite_timer function to select it, then click Deploy.

      • In the Confirm Deploy Function dialog, select Everything from the Feed boundary option.

      • Click Deploy Function.

    8. The Eventing function is deployed and starts running within a few seconds. From this point, the defined Function is executed on all existing documents and will also more importantly it will also run on subsequent mutations.

    Test 1: Create a Timer and allow the Timer to Fire

    1. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document type_of_interest::1 — it should look like:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": false,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 1
        }

        Change "needed_condition" to true to create a mutation, then click Save. This will create a mutation and then the Function will generate a Timer. The control document is now:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 1
        }
    2. Access the Couchbase Web Console > Eventing page and click on the Function cancel_overwrite_timer then click the "Log" link for Deployed Function cancel_overwrite_timer to view the activity.

      • Here we see from the Application log that we created a timer.

        2020-08-03T12:46:02.941-07:00 [INFO] "From OnUpdate: creating timer" "type_of_interest::1"
        cancel overwrite timer 04 log active1
    3. Close the Function Log dialog, then wait about 80 seconds and click the "Log" link for the Deployed Function cancel_overwrite_timer to view the activity again.

      • Here we see the timer fired and executed the callback DocTimerCallback near our scheduled time.

        2020-08-03T12:47:03.925-07:00 [INFO] "From DocTimerCallback: timer fired" {"docId":"type_of_interest::1","random_text":"arbitrary text","tmr_time_to_fire":"2020-08-03T19:47:02.941Z"}
        cancel overwrite timer 04 log fired1
    4. Now, to check the results of the callback, access the Couchbase Web Console > Buckets page and click the Documents link of the target bucket.

      • Edit the new document type_of_interest::1 and you will see the data written by the Timer’s callback:

        {
          "docId": "type_of_interest::1",
          "random_text": "arbitrary text",
          "tmr_time_to_fire": "2020-08-03T19:47:02.941Z"
        }
      • Click Cancel to close the editor.

    5. Click the trash can icon to delete the document, then click Continue to confirm the deletion.

    Test 2: Create a Timer then Cancel the Timer:

    1. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document type_of_interest::1 — it should look like this:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 1
        }

        Change "a_number" to 2 to create a mutation, then click Save. The control document is now:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 2
        }
    2. Access the Couchbase Web Console > Eventing page and if necessary select the Function cancel_overwrite_timer, then click the "Log" link for Deployed Function to view the activity. Here we see from the Application log that we once again created a timer.

      2020-08-03T12:50:40.441-07:00 [INFO] "From OnUpdate: creating timer" "type_of_interest::1"
    3. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document type_of_interest::1 — it should look like this:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 2
        }

        Change "cancel_timer" to true to create a mutation, then click Save. The control document is now:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": true,
          "overwrite_timer": false,
          "a_number": 2
        }
    4. Access the Couchbase Web Console > Eventing page and if necessary select the Function cancel_overwrite_timer, then click the "Log" link for Deployed Function to view the activity.

      • Here we see from the Application log the timer was canceled and will never fire.

        2020-08-03T12:51:16.841-07:00 [INFO] "From OnUpdate: cancel request, timer was canceled" "type_of_interest::1"

    Test 3: Create a Timer then Overwrite the Timer

    1. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document type_of_interest::1 — it should look like this:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": false,
          "cancel_timer": true,
          "overwrite_timer": false,
          "a_number": 2
        }

        Change "cancel_timer" to false to create a mutation, then click Save. This will create a mutation and then the Function will generate a Timer. The control document is now:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 2
        }
    2. Access the Couchbase Web Console > Eventing page and if necessary select the Function cancel_overwrite_timer, then click the "Log" link for Deployed Function to view the activity.

      • Here we see from the Application log that we created a timer.

        2020-08-03T12:52:18.641-07:00 [INFO] "From OnUpdate: creating timer" "type_of_interest::1"
    3. Access the Couchbase Web Console > Buckets page and click the Documents link of the source bucket.

      • Edit the control document type_of_interest::1 — it should look like this:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": false,
          "a_number": 2
        }

        Change "overwrite_timer" to true to create a mutation, then click Save. The control document is now:

        {
          "type": "type_of_interest",
          "id": 1,
          "needed_condition": true,
          "cancel_timer": false,
          "overwrite_timer": true,
          "a_number": 2
        }
    4. Access the Couchbase Web Console > Eventing page and if necessary select the Function cancel_overwrite_timer, then click the "Log" link for Deployed Function to view the activity.

      • Here we see from the Application log the timer was overwritten and will fire at a later time.

        2020-08-03T12:52:50.441-07:00 [INFO] "From OnUpdate: overwriting timer with same reference" "type_of_interest::1"
    5. [Optional] mutate the document several times by changing "a_number" — this will overwrite the timer multiple times.

    6. Wait about 80 seconds and click the "Log" link for Deployed Function cancel_overwrite_timer to view the activity.

      • Here we see the timer fired and executed the callback DocTimerCallback near our scheduled time.

        2020-08-03T12:53:56.925-07:00 [INFO] "From DocTimerCallback: timer fired" {"docId":"type_of_interest::1","random_text":"arbitrary text","tmr_time_to_fire":"2020-08-03T19:53:50.441Z"}
    7. Now, to check the results of the callback, access the Couchbase Web Console > Buckets page and click the Documents link of the target bucket.

      • Edit the new document type_of_interest::1 and you will see the data written by the Timer’s callback:

        {
          "docId": "type_of_interest::1",
          "random_text": "arbitrary text",
          "tmr_time_to_fire": "2020-08-03T19:53:50.441Z"
        }
      • Click Cancel to close the editor.

    8. Click the trash can icon to delete the document, then click Continue to confirm the deletion.

    Cleanup:

    To clean up, go to the Eventing portion of the UI and undeploy the Function cancel_overwrite_timer. This will remove the 2048 documents for each function from the 'metadata' bucket (in the Bucket view of the UI). Remember you may only delete the 'metadata' bucket if there are no deployed Eventing functions.