Redis

This example demonstrates defining a custom Lambda Trigger that subscribes to a Redis pub+sub channel. It then demonstrates a Lambda that responds.

Initial Provisioning

graph LR;

cli --> control_plane;
console --> control_plane;
control_plane <-- tunnel --> agent;

subgraph user_edge[User Edge]
cli[CLI];
console[Console];
end

subgraph cloud[Cloud <small>api.on-prem.net</small>]
control_plane[Control Plane];
end

subgraph device_edge[Device Edge]
agent[Agent];
end

Subsequent Autonomous Edge Operation

graph TB;

agent --> trigger[Lambda Trigger];
trigger --> lambda1;
trigger --> lambda2;
trigger --> lambda3;
redis -- subscribe --> trigger;

subgraph device_edge[Device Edge]
agent;
redis[(Redis)]
end

subgraph agent[Agent]
trigger;
lambda1[Lambda 1];
lambda2[Lambda 2];
lambda3[Lambda 3];
end

Define the lambda trigger

$ onprem generate xid
ck86ttgdr07e6c71dnjg
# my_redis_subscribe.yaml
id: ck86ttgdr07e6c71dnjg
kind: LambdaTriggerType
name: my_redis_subscribe_trigger_type
description: >
  Trigger lambdas when a Redis pub+sub event fires.
runsAtControlPlane: false
runsAtDevices: true
scriptContentType: text/x-lua
script: >
  local redis = require('redis')
  local socket = require('socket')

  local M = {}

  function M.init(context)
    local redis_client = redis.connect('my-redis', 6379)
    assert(redis_client:ping())
    context['redis_client'] = redis_client
  end

  function M.run(context)
    local redis_client = context.redis_client
    local channels = {'foo', 'bar'}
    for msg, abort in redis_client:pubsub({subscribe=channels}) do
      local event = {
        timestamp = socket.gettime(),
        msg = msg
      }
      coroutine.yield(event)
    end
  end

  return M

Upload it to the control plane

$ onprem apply ./my_redis_subscribe.yaml

It will now show up in the cloud console.

Cloud Console

And it will also now show up as one of the trigger choices when editing a Lambda.

Editing a Lambda

Configure a Lambda to respond

$ onprem generate xid
ck871o8dr07ebbbn2h30
# respond_to_redis_events.yaml
id: ck871o8dr07ebbbn2h30
kind: Lambda
name: respond_to_redis_events
description: >
  Respond to events received from Redis pub+sub channel.
runAt:
  deviceId: ci2fabp32ckvhk1g9qe0
triggerTypeId: ck86ttgdr07e6c71dnjg
scriptContentType: text/x-lua
script: >
  local M={}
  function M.handler(event, context)
    -- TODO do something with the event here
    return event
  end
  return M
$ onprem apply respond_to_redis_events.yaml

Manually Trigger

$ redis-cli publish foo 123