Package: redgrease
RedGreaseRedGrease is a Python package and set of tools to facilitate development againstRedisin general andRedis Gearsin particular.It may help you create:Advanced analytical queries,Event based and streaming data processing,Custom Redis commands and interactions,And much, much more...... all written in Python and running distributed ON your Redis nodes.Read theDocumentationInstallationClient- I.e. Package used by application and/or during dev.Runtime- I.e. Package installed on the Redis engine.Quick Example:importredgreaseasrdgrconn=rdgr.RedisGears(host='localhost',port=30001)# count for each genre how many times it appearsresults=(rdgr.KeysReader().keys(type='hash').map(lambdakey:rdgr.cmd.hget(key,'genres')).filter(lambdax:x!='\\N').flatmap(lambdax:x.split(',')).map(str.strip).countby().run(on=conn))forresinresults:print(f"{res['key']::<15s}{res['value']}")RedGrease consists of the followinig, components:A Redis / Redis Gears client, which is an extended version of theredisclient, but with additional pythonic functions, mapping closely (1-to-1) to the Redis Gears command set (e.g.RG.PYEXECUTE,RG.GETRESULT,RG.TRIGGER,RG.DUMPREGISTRATIONSetc), outlinedhereimportredgreasegear_script=...# Some vanilla Gear script string, a GearFunction object or a script file path.rg=redgrease.RedisGears()rg.gears.pyexecute(gear_script)# <--Wrappers for theruntime functions(e.g.GearsBuilder,GB,atomic,execute,logetc) that are automatically loaded into the serverruntime environment. These placeholder versions providedocstrings,auto completionandtype hintsduring development, and does not clash with the actual runtime, i.e does not require redgrease to be installed on the server.Server side Redis commands, allowing forallRedis (v.6) commands to be executed on serverside as if using a Redis 'client' class, instead of 'manually' invoking theexecute(). It is basically theredisclient, but withexecute_command()rewired to use the Gears-nativeexecute()instead under the hood.importredgreasedefdownload_image(annotation):img_id=annotation["image_id"]img_key=f"image:{img_id}"ifredgrease.cmd.hexists(img_key,"image_data"):# <- hexists# image already downloadedreturnimg_keyredgrease.log(f"Downloadign image for annotation:{annotation}")image_url=redgrease.cmd.hget(img_key,"url")# <- hgetresponse=requests.get(image_url)redgrease.cmd.hset(img_key,"image_data",bytes(response.content))# <- hsetreturnimg_key# Redis connection (with Gears)connection=redgrease.RedisGears()# Automatically download corresponding image, whenever an annotation is created.image_keys=(redgrease.KeysReader().values(type="hash",event="hset").foreach(download_image,requirements=["requests"]).register("annotation:*",on=connection))'First class'GearFunction objects, inspired by the remote builders of the officialredisgears-pyclient, but with some differences.records=redgrease.KeysReader().records(type="hash")# <- fun 1 : hash-recodsrecord_listener=(# <- fun 2, "extents" fun 1records.foreach(schedule).register(key_pattern,eventTypes=["hset"]))count_by_status=(# <- fun 3, also "extends" fun 1records.countby(lambdar:r.value.get("status","unknown")).map(lambdar:{r["key"]:r["value"]}).aggregate({},lambdaa,r:dict(a,**r)).run(key_pattern))process_records=(# <- fun 4redgrease.StreamReader().values()# <- Sugar.foreach(process,requirements=["numpy"]).register("to_be_processed"))# Instantiate client objectsserver=redgrease.RedisGears()# Different ways of executingserver.gears.pyexecute(record_listener)process_records.on(server)count=count_by_status.on(server):warning: As with the official package, this require that the server runtime Python version matches the client runtime that defined the function. As of writing this is Only for Python 3.7. But don't worry, both "vanilla" and RedGrease flavoured Gear functions can still be excuted by file.CLI toolrunning and or loading of Gears scripts onto a Redis Gears cluster. Particularls useful for "trigger-based" CommandReader Gears.
It also provides a simple form of 'hot-reloading' of Redis Gears scripts, by continously monitoring directories containing Redis Gears scripts and automatically 'pyexecute' them on a Redis Gear instance if it detects modifications.
The purpose is mainly to streamline development of 'trigger-style' Gear scripts by providing a form of hot-reloading functionality.redgrease --server 10.0.2.21 --watch scripts/This will 'pyexecute' the gears scripts in the 'scripts' directory against the server. It will also watch the directors for changes and re-execute the scripts if they have been modified.Other boilerplate or otherwise functions and utilities (redgrease.utils), that are commonly used in gears. e.g:A recordrecordfunction  that can be used to transform the defaultKeysReaderdict to anRecordsobject with the appropriate attributes.CommandReader + Trigger function decorator, that makes custom Redis Commands really easy.Helpers to aid debugging and/ or testing of gears....Additional feature suggestions appriciated.Docker images with redgrease pre-installed as well as, hopefully, variants for all python versions 3.6 or later (Work-in-Progress).Example usage:importredgreaseimportredgrease.utilsrelevant_usr_fields={"active":bool,"permissions":redgrease.utils.list_parser(str),}# # "Open" Gear function# Extracting a dict for every 'active' useractive_users=(redgrease.KeysOnlyReader().map(lambdakey:redgrease.cmd.hmget(key,*relevant_usr_fields.keys())).map(lambdaudata:redgrease.utils.to_dict(udata,keys=relevant_usr_fields.keys(),val_transform=relevant_usr_fields)).filter(lambdausr:usr["active"]))# # "Open" Gear function re-use# Count the number of active usersactive_user_count=active_users.count()# Get all the distinct user permissionsall_issued_permissions=active_users.flatmap(lambdausr:usr["permissions"]).distinct()# # Redis Client w. Gears-features can be created separatelyr=redgrease.RedisGears()# # Two ways of running:# With 'pyexecute' ...count=r.gears.pyexecute(active_user_count.run("user:*"))# ... or using the 'on' methodpermissions=all_issued_permissions.run("user:*").on(r)# Result values are directly accessibleprint(f"Count:{count}")ifcount>100:print("So many users!")print(permissions)if"root"inpermissions:print("Someone has root permissions")# Errors can be accessed tooifcount.errors:print(f"Errors counting users:{count.errors}")ifpermissions.errors:print(f"Errors collecting permissions:{permissions.errors}")InstallationRedgrease may be installed either as a developmet tool only, a client library and/or as a runtime library on the Redis Gears server.
It can be installed with different 'extras' dependencies depending on preferred usage.Client InstallationInstallaton for development and/or client application environment.In the environment where you develop your Gears scripts, simply install 'redgrease' with pip3, as usual:python3 -m pip install redgrease[all]This installs all the dependencies, allowing for the full features set.reagrease[cli]: Installs dependencies for the CLIRuntime InstallationInstallation for the Redis Gears Runtime / Server.Server RequirementsFirstly, the Redis Engine must be running the Redis Gears module.
The easiest way to get started is to run published Docker images:Single engine setupdocker run -p 6379:6379 redislabs/redisgearsThree master node cluster setupdocker run -p 30001:30001 -p 30002:30002 -p 30003:30003 redislabs/rgclusterFor more advanced deployments of Redis with Gears, please refer to theofficial Gears installation documentation.Redgrease Runtime PackageAs for RedGrease, it is recommended to use theredgrease[runtime]package as a server side dependency.
This installs dependencies for the all the server side features such as server side Redis commands and the runtime for gears constructed with the Remote Gears Builder.The easiest way of installing the latest stable runtime package is by simply setting theenforce_redgreaseargument ofpyexecutetoTrue.
Redgrease will also be automatically enforced when executing any dynamically constructed GearFunction objects.importredgreaserg=redgrease.RedisGears()rg.gears.pyexecute(enforce_redgrease=True)NOTE:Its possible to pin the versions insideenforce_redgrese, seeredgrease.requirements.PackageOptionfor more details.ExtrasThe current 3rd party packages in theruntimeextras are:attrs- For parsing composite Gears response structures into attrs objectsredis- Needed for server-side Redis commandscludpickle- Needed for the "Remote" gears (similar to the officialredisgears-pyclient)Note on the runtime environmentIf the only thing you need is theredgreaseclient, documentation, type hints and the loader CLI for development of conventional Gears scripts (i.e that only use the standard commands and loaded as strings),then the RedGrease package is not strictly required to be installedin the Redis Gears Python Runtime environment (i.e. on the server).You can in this case, simply remove theredgreaseimport clause from your script, after development, but beforepyexecutingthem as per theRedis Gears documentation. Such scripts will still run perfectly fine withoutredgreasein Redis Gears Environment.A minimal install, without any 3rd party dependencies, which is pretty much only the syntactic sugar and runtime placeholders, can be installed using the bareredgreasepackage.This might be useful if you really don't want the 3rd party packages in the server runtime but still want to use theredgreasesugar.You can also use the RedGrease watcher or loader CLI to automate loading your scripts as well as requirements from a normalrequirements.txtfiles, as outlinedhereUsage / DocumentationThe documention is work-in-progress, but the latest and greatest version is available here:https://redgrease.readthedocs.ioGo read the docs!TestingTests are separate from the package, but are available in theGitHub repo.git clone https://github.com/lyngon/redgreaseIn order to run the tests,Dockeris required to be installed in order to spin up fresh Redis instances, on demand for the tests.Pytest and quite a number of its add-ons, as well astox, is also needed to run the tests properly. All tests, including development, requirements are best installed through:cd redgrease/
python3 -m venv .venv
source .venv/bin/activate
pip install -r src/requirements-dev.txtThen the test can be run with:pytestNOTE:Running the tests takes very long, because a new fresh Redis instance is spun upfor each test, just to ensure no risk of cross-contamination. This may be optimized, as many tests are actually independent, but it's left like this for now.Why This?The need for this arose from wanting to prototype the concepts for a new Redis module, using Gears CommandReaders and triggers instead of having to write a full fledged module in C.Initially RedGrease has been just a very simple module, with placeholders for the default Redis gears runtime functions, with type hints and docstrings, just to make it more convenient and less error prone to write Gears functions.Then the loader CLI was created, in order to further speed up the rapid development cycle.Then the server-side Redisclientcommands function was added to minimize errors (e.g. misspelled command strings).Then the client was added ... and before long it started to get a life of its own.Note that this means RedGrease package is primarily intended to be an aid fordevelopmentof Gears scripts, and was not originally intended to be used in any "production" software.This intent has now changed, and the new goal is now to make Redgrease a production grade package for Redis Gears.
Granted, there is still quite some way to go to get there, so your support and feedback is greatly appreciated.If you like this project, or want professional support, please considersponsoring.