The State Management module provides powerful persistent state capabilities with atomic operations, distributed locks, and TTL (Time To Live) functionality. All data is stored locally using SQLite with WAL mode for maximum performance and reliability.
-- Set valuesstate.set("app_version","v1.2.3")state.set("user_count",1000)state.set("config",{debug=true,max_connections=100})-- Get valueslocalversion=state.get("app_version")localcount=state.get("user_count")localconfig=state.get("config")-- Get with default valuelocaltheme=state.get("ui_theme","dark")-- Check existenceifstate.exists("app_version")thenlog.info("App version is configured")end-- Delete keystate.delete("old_key")
-- Set with TTL (60 seconds)state.set("session_token","abc123",60)-- Set TTL for existing keystate.set_ttl("user_session",300)-- 5 minutes-- Check remaining TTLlocalttl=state.get_ttl("session_token")log.info("Token expires in "..ttl.." seconds")
-- Add items to liststate.list_push("deployment_queue",{app="frontend",version="v2.1.0",environment="staging"})-- Check list sizelocalqueue_size=state.list_length("deployment_queue")log.info("Items in queue: "..queue_size)-- Process list (pop removes last item)whilestate.list_length("deployment_queue")>0dolocaldeployment=state.list_pop("deployment_queue")log.info("Processing deployment: "..deployment.app)-- Process deployment...end
-- Try to acquire lock (no waiting)locallock_acquired=state.try_lock("deployment_lock",30)-- 30 seconds TTLiflock_acquiredthen-- Critical workstate.unlock("deployment_lock")end-- Lock with wait and timeoutlocalacquired=state.lock("database_migration",60)-- wait up to 60sifacquiredthen-- Execute migrationstate.unlock("database_migration")end-- Critical section with automatic lock managementstate.with_lock("critical_section",function()log.info("Executing critical operation...")-- Update global counterlocalcounter=state.increment("global_counter",1)-- Update timestampstate.set("last_operation",os.time())log.info("Critical operation completed - counter: "..counter)-- Lock is automatically released when function returnsreturn"operation_success"end,15)-- 15 second timeout
-- Helper function for cachingfunctionget_cached_data(cache_key,fetch_function,ttl)localcached=state.get(cache_key)ifcachedthenlog.info("Cache hit: "..cache_key)returncachedendlog.info("Cache miss: "..cache_key.." - fetching...")localdata=fetch_function()state.set(cache_key,data,ttlor300)-- 5 minutes defaultreturndataend-- Usage in taskslocalfetch_user_data=task("fetch_user_data"):description("Fetch user data with intelligent caching"):command(function(this,params)localuser_data=get_cached_data("user:123:profile",function()-- Simulate expensive fetchreturn{name="Alice",email="alice@example.com",preferences={"dark_mode","notifications"}}end,600)-- Cache for 10 minuteslog.info("User data: "..data.to_json(user_data))returntrue,"User data retrieved"end):build()localdata_processing=workflow.define("data_processing"):description("Data processing workflow with caching"):version("1.0.0"):tasks({fetch_user_data})
functioncheck_rate_limit(identifier,max_requests,window_seconds)localkey="rate_limit:"..identifierlocalcurrent_count=state.get(key,0)ifcurrent_count>=max_requeststhenreturnfalse,"Rate limit exceeded"end-- Increment counterifcurrent_count==0then-- First request in windowstate.set(key,1,window_seconds)else-- Increment existing counterstate.increment(key,1)endreturntrue,"Request allowed"end-- Usage in taskslocalmake_api_call=task("make_api_call"):description("Make API call with rate limiting"):command(function(this,params)localallowed,msg=check_rate_limit("api_calls",100,3600)-- 100 calls/hourifnotallowedthenlog.error(msg)returnfalse,msgend-- Make API calllog.info("Making API call...")returntrue,"API call completed"end):build()localapi_tasks=workflow.define("api_tasks"):description("API tasks workflow with rate limiting"):version("1.0.0"):tasks({make_api_call})