{"id":13772304,"url":"https://github.com/Optibus/playback","last_synced_at":"2025-05-11T04:31:17.832Z","repository":{"id":39581750,"uuid":"328385785","full_name":"Optibus/playback","owner":"Optibus","description":"Record your service operations in production and replay them locally at any time in a sandbox","archived":false,"fork":false,"pushed_at":"2024-05-29T11:50:12.000Z","size":312,"stargazers_count":103,"open_issues_count":3,"forks_count":12,"subscribers_count":22,"default_branch":"main","last_synced_at":"2024-05-30T01:11:59.457Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Optibus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-10T13:10:12.000Z","updated_at":"2024-08-03T17:05:47.933Z","dependencies_parsed_at":"2024-01-13T00:38:45.816Z","dependency_job_id":"809e2af6-8f32-4ab4-b27d-b1cb8a84d39c","html_url":"https://github.com/Optibus/playback","commit_stats":{"total_commits":203,"total_committers":16,"mean_commits":12.6875,"dds":0.541871921182266,"last_synced_commit":"c09d376be28db50fceff287cf1ae153bff7d94b1"},"previous_names":[],"tags_count":65,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Optibus%2Fplayback","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Optibus%2Fplayback/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Optibus%2Fplayback/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Optibus%2Fplayback/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Optibus","download_url":"https://codeload.github.com/Optibus/playback/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253518941,"owners_count":21921074,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T17:01:02.399Z","updated_at":"2025-05-11T04:31:17.820Z","avatar_url":"https://github.com/Optibus.png","language":"Python","readme":"# playback [![CircleCI](https://circleci.com/gh/Optibus/playback.svg?branch=main\u0026style=shield)](https://circleci.com/gh/Optibus/playback) [![codecov](https://codecov.io/gh/Optibus/playback/branch/main/graph/badge.svg?branch=main\u0026token=CA8OMGPFQT)](https://codecov.io/gh/Optibus/playback) [![PyPi Version](https://badge.fury.io/py/playback-studio.svg)](https://pypi.python.org/pypi/playback-studio/) [![Python Versions](https://img.shields.io/pypi/pyversions/playback-studio.svg)](https://pypi.python.org/pypi/playback-studio/)\n\nA Python decorator-based framework that lets you \"record\" and \"replay\" operations (e.g. API requests, workers consuming jobs from queues).\n\na java-script / type script [version](https://github.com/Optibus/playback-ts) is in the works\n\n## Main uses\n\n* Regression testing - replay recorded production traffic on modified code before pushing it\n* Debug production issues locally\n* Access many \"real data\" scenarios to test/validate new features/behaviours\n\nThe framework intercepts all decorated inputs and outputs throughout the recorded operation, which are used later to replay the exact operation in a controlled isolated sandbox, as well as to compare the output of the recorded operation vs the replayed operation.\n\n## Background\nThe motivation for this framework was to be able to test new code changes on actual data from production while doing it not in production, when the\nalternative of canary deployment is not a viable option.\nSome examples when this might happen include:\n* When detecting a regression is based on intimate knowledge of the service output\n* When the service amount of possible input permutations is large while the number of users per permutation is low, resulting\n  in a statistical sample that is not large enough to rely on in production in order to detect regression early enough\n  to rollback\n\nOn top of this, the ability for the developer to check and get an accurate comparison of his/her code vs production then\ndebug it during development increases productivity by detecting issues right away.\nThe quality of the released code improves significantly by covering many edge cases that are hard to predict in tests.\n\n## Features\n* Create a standalone \"recording\" of each intercepted operation, with all the relevant inputs and outputs, and save it\n  to AWS S3\n* Replay a recorded operation anywhere via code execution\n* Run an extensive comparison of recorded vs replayed operations\n\n# Installation\n`pip install playback-studio`\n\n# Examples\nThere are two examples as part of this repo you can check out under the [examples](examples) directory:\n* [basic service operation](examples/basic_service_operation.py/) - a simple example for in memory operation\n* [Flask based service](examples/flask) - an end to end flask based example with persistent recording\n\n# Usage and examples - interception and replay\n## Intercepting an operation\nIn order to intercept an operation, you need to explicitly declare the recorded operation entry point by decorating it with\nthe `TapeRecorder.operation` decorator and explicitly declare what inputs and outputs need to be intercepted by using\nthe `TapeRecorder.intercept_input` and `TapeRecorder.intercept_output` decorators, as demonstrated below:\n```python\nfrom flask import request\ntape_cassette = S3TapeCassette('production-recordings', region='us-east-1', read_only=False)\ntape_recorder = TapeRecorder(tape_cassette)\ntape_recorder.enabled_recording()\n\n\nclass ServiceOperation(object):\n\n    ...\n\n    @tape_recorder.operation()\n    def execute(self):\n        \"\"\"\n        Executes the operation and return the key of where the result is stored\n        \"\"\"\n        data = self.get_request_data()\n        result = self.do_something_with_input(data)\n        storage_key = self.store_result(result)\n        return storage_key\n\n    @tape_recorder.intercept_input(alias='service_operation.get_request_data')\n    def get_request_data(self):\n        \"\"\"\n        Reads the required input for the operation\n        \"\"\"\n        # Get request data from flask\n        return request.data\n\n    @tape_recorder.intercept_output(alias='service_operation.store_result')\n    def store_result(self, result):\n        \"\"\"\n        Stores the operation result and return the key that can be used to fetch the result\n        \"\"\"\n        result_key = self.put_result_in_mongo(result)\n        return result_key\n```\n\n## Locally Cached S3 Tape Cassette\nThe `CachedReadOnlyS3TapeCassette` class serves as an alternative to `S3TapeCassette`, enabling the storage of recordings locally. By providing a local path (or defaulting to `/tmp/recordings_cache`), it eliminates the need for constant access to AWS S3. In the event of a cache failure, the class gracefully falls back to its parent `S3TapeCassette`, attempting to fetch the original recording data directly from S3 as needed.\n```\ntape_cassette = CachedReadOnlyS3TapeCassette('production-recordings', region='us-east-1', read_only=True, local_path=`/tmp/recordings_cache`, use_cache=True)\n```\nNotice that CachedReadOnlyS3TapeCassette is used in a read_only state only and you can refresh your recording id cache by calling it with use_cache=False \n\n## Replaying an intercepted operation\nIn order to replay an operation, you need the specific recording ID. Typically, you would add this information to your\nlogs output. Later, we will demonstrate how to look for recording IDs using search filters, the `Equalizer`, and the\n`PlaybackStudio`\n```python\ntape_cassette = S3TapeCassette('production-recordings', region='us-east-1')\ntape_recorder = TapeRecorder(tape_cassette)\n\ndef playback_function(recording):\n    \"\"\"\n    Given a recording, starts the execution of the recorded operation\n    \"\"\"\n    operation_class = recording.get_metadata()[TapeRecorder.OPERATION_CLASS]\n    return operation_class().execute()\n\n# Will replay recorded operation, injecting and capturing needed data in all of the intercepted inputs and outputs\ntape_recorder.play(recording_id, playback_function)\n```\n\n# Framework classes - recording and replaying\n## `TapeRecorder` class\nThis class is used to \"record\" an operation and \"replay\" (rerun) the recorded operation on any code version.\nThe recording is done by placing different decorators that intercept the operation and its inputs and outputs by using\ndecorators.\n### `operation` decorator\n```python\ndef operation(self, metadata_extractor=None)\n```\nDecorates the operation entry point. Every decorated input and output that is being executed within this scope is being\nintercepted and recorded or replayed, depending on whether the current context is recording or playback.\n\n* `metadata_extractor` - an optional function that can be used to add\nmetadata to the recording. The metadata can be used as a search filter when fetching recordings, hence it can be used\nto add properties specific to the operation received parameters that make sense to filter by when you wish to replay\nthe operation.\n\n### `intercept_input` decorator\n```python\ndef intercept_input(self, alias, alias_params_resolver=None, data_handler=None, capture_args=None, run_intercepted_when_missing=True)\n```\nDecorates a function that acts as an input to the operation. The result of the function is the recorded input, and the\ncombined passed arguments and alias are used as the key that uniquely identifies the input. Upon playback, an invocation to\nthe intercepted method will fetch the input from the recording by combining the passed arguments and alias as the\nlookup key. If no recorded value is found, a `RecordingKeyError` will be raised.\n\n* `alias` - Input alias, used to uniquely identify the input function, hence the name should be unique across all\n  relevant inputs this operation can reach. This should be renamed as it will render previous recording useless\n* `alias_params_resolver` - Optional function that resolve parameters inside alias if such are given. This is useful when\n  you have the same input method invoked many times with the same arguments on different class instances\n* `data_handler` - Optional data handler that prepares and restores the input data for and from the recording when default\n  pickle serialization is not enough. This needs to be an implementation of `InputInterceptionDataHandler` class\n* `capture_args` - If a list is given, it will annotate which arg indices and/or names should be captured as part of\n  the intercepted key (invocation identification). If None, all args are captured\n* `run_intercepted_when_missing` - If no matching content is found on recording during playback, run the original intercepted \n  method. This is useful when you want to use existing recording to play a code flow where this interception didn't exist\n\nWhen intercepting a static method, `static_intercept_input` should be used.\n\n### `intercept_output` decorator\n```python\ndef intercept_output(self, alias, data_handler=None, fail_on_no_recorded_result=True)\n```\nDecorates a function that acts as an output of the operation. The parameters passed to the function are recorded as\nthe output and the return value is recorded as well. The alias combined with the invocation number are used as the key that\nuniquely identifies this output. Upon playback, an invocation to the intercepted method will construct the same\nidentification key and capture the outputs again (which can be used later to compare against the recorded output), and\nthe recorded return value will be returned.\n\n* `alias` - Output alias, used to uniquely identify the input function, hence the name should be unique across all\n  relevant inputs this operation can reach. This should be renamed as it will render previous recording useless\n* `data_handler` - Optional data handler that prepares and restores the output data for and from the recording when\n  default pickle serialization is not enough. This needs to be an implementation of `OutputInterceptionDataHandler` class\n* `fail_on_no_recorded_result` - Whether to fail if there is no recording of a result or return None.\n  Setting this to False is useful when there are already pre-existing recordings and this is a new output interception\n  where we want to be able to playback old recordings and the return value of the output is not actually used.\n  Defaults to True\n\nThe return value of the operation is always intercepted as an output implicitly using\n`TapeRecorder.OPERATION_OUTPUT_ALIAS` as the output alias.\n\nWhen intercepting a static method, `static_intercept_output` should be used.\n\n## `TapeCassette` class\nAn abstract class that acts as a storage driver for TapeRecorder to store and fetch recordings, the class has three main\nmethods that need to be implemented.\n```python\ndef get_recording(self, recording_id)\n```\nGet recording is stored under the given ID\n\n```python\ndef create_new_recording(self, category)\n ```\nCreates a new recording object that is used by the tape recorded\n* `category` - Specifies under which category to create the recording and represent the operation type\n\n```python\ndef iter_recording_ids(self, category, start_date=None, end_date=None, metadata=None, limit=None)\n```\nCreates an iterator of recording IDs matching the given search parameters\n* `category` - Specifies in which category to look for recordings\n* `start_date` - Optional earliest date of when recordings were captured\n* `end_date` - Optional latest date of when recordings were captured\n* `metadata` - Optional dictionary to filter captured metadata by\n* `limit` - Optional limit on how many matching recording IDs to fetch\n\nThe framework comes with two built-in implementations:\n* `InMemoryTapeCassette` - Saves recording in a dictionary, its main usage is for tests\n* `S3TapeCassette` - Saves recording in AWS S3 bucket\n### `S3TapeCassette` class\n```python\n# Instantiate the cassette connected to bucket 'production-recordings'\n# under region 'us-east-1' in read/write mode\ntape_cassette = S3TapeCassette('production-recordings', region='us-east-1', read_only=False)\n```\nInstantiating this class relies on being able to connect to AWS S3 from the current terminal/process and have read/write\naccess to the given bucket (for playback, only read access is needed).\n```python\ndef __init__(self, bucket, key_prefix='', region=None, transient=False, read_only=True,\n             infrequent_access_kb_threshold=None, sampling_calculator=None)\n```\n* `bucket` - AWS S3 bucket name\n* `key_prefix` - Each recording is saved under two keys, one containing full data and the other just for fast lookup\n  and filtering of recordings. The key structure used for recording is\n  'tape_recorder_recordings/{key_prefix}\u003cfull/metadata\u003e/{id}', this gives the option to add a prefix to the key\n* `region` - This value is propagated to the underline boto client\n* `transient` - If this is a transient cassette, all recording under the given prefix will be deleted when closed\n  (only if not read-only). This is useful for testing purposes and clean-up after tests\n* `read_only` - If True, this cassette can only be used to fetch recordings and not to create new ones.\n  Any write operations will raise an assertion.\n* `infrequent_access_kb_threshold` - Threshold in KB. When above the threshhold, the object will be saved in STANDARD_IA\n  (infrequent access storage class), None means never (default)\n* `sampling_calculator` - Optional sampling ratio calculator function. Before saving the recording, this\n  function will be triggered with (category, recording_size, recording)\n  and the function should return a number between 0 and 1 which specifies its sampling rate\n\n# Usage and examples - comparing replayed vs recorded operations\n## Using the Equalizer\nIn order to run a comparison, we can use the `Equalizer` class and provide it with relevant playable recordings.\nIn this example, we will look for five recordings from the last week using the `find_matching_recording_ids` function.\nThe `Equalizer` relies on:\n* `playback_function` to replay the recorded operation\n* `result_extractor` to extract the result that we want to compare from the captured outputs\n* `comparator` to compare the extracted result\n```python\n# Creates an iterator over relevant recordings which are ready to be played\nlookup_properties = RecordingLookupProperties(start_date=datetime.utcnow() - timedelta(days=7),\n                                              limit=5)\nrecording_ids = find_matching_recording_ids(tape_recorder,\n                                            ServiceOperation.__name__,\n                                            lookup_properties)\n\n\ndef result_extractor(outputs):\n    \"\"\"\n    Given recording or playback outputs, find the relevant output which is the result that\n    needs to be compared\n    \"\"\"\n    # Find the relevant captured output\n    output = next(o for o in outputs if 'service_operation.store_result' in o.key)\n    # Return the captured first arg as the result that needs to be compared\n    return output.value['args'][0]\n\n\ndef comparator(recorded_result, replay_result):\n    \"\"\"\n    Compare the operation captured output result\n    \"\"\"\n    if recorded_result == replay_result:\n        return ComparatorResult(EqualityStatus.Equal, \"Value is {}\".format(recorded_result))\n    return ComparatorResult(EqualityStatus.Different,\n                            \"{recorded_result} != {replay_result}\".format(\n                                recorded_result=recorded_result, replay_result=replay_result))\n\n\ndef player(recording_id):\n    return tape_recorder.play(recording_id, playback_function)\n\n\n# Run comparison and output comparison result using the Equalizer\nequalizer = Equalizer(recording_ids, player, result_extractor, comparator)\n\nfor comparison_result in equalizer.run_comparison():\n    print('Comparison result {recording_id} is: {result}'.format(\n        recording_id=comparison_result.playback.original_recording.id,\n        result=comparison_result.comparator_status))\n```\n\n# Framework classes - comparing replayed vs recorded operations\n## `Equalizer` class\nThe `Equalizer` is used to replay multiple recordings of a single operation and conduct a comparison between the\nrecorded results (outputs) vs the replayed results. Underline it uses the `TapeRecorder` to replay the\noperations and the `TapeCassette` to look for and fetch relevant recordings.\n\n```python\ndef __init__(self, recording_ids, player, result_extractor, comparator,\n             comparison_data_extractor=None, compare_execution_config=None)\n```\n* `recording_ids` - An iterator of recording IDs to play and compare the results\n* `player` - A function that plays a recording given an ID\n* `result_extractor` - A function used to extract the results that need to be compared from the recording and playback\n  outputs\n* `comparator` - A function used to create the comparison result by comparing the recorded vs replayed result\n* `comparison_data_extractor` - A function used to extract optional data from the recording that will be passed to the\n  comparator\n* `compare_execution_config` -  A configuration specific to the comparison execution flow\n\nFor more context, you can look at the [basic service operation](examples/basic_service_operation.py/) example.\n\n## Usage and examples - comparing multiple recorded vs replayed operations in one flow\nWhen a code change may affect multiple operations, or when you want to have a general regression job running, you can use\nthe `PlaybackStudio` and `EqualizerTuner` to run multiple operations together and aggregate the results.\nMoreover, the `EqualizerTuner` can be used as a factory to create the relevant plugin functions required to set up an\n`Equalizer` to run a comparison of a specific operation.\n\n```python\n# Will run 10 playbacks per category\nlookup_properties = RecordingLookupProperties(start_date, limit=10)\ncatagories = ['ServiceOperationA', 'ServiceOperationB']\nequalizer_tuner = MyEqualizerTuner()\n\nstudio = PlaybackStudio(categories, equalizer_tuner, tape_recorder, lookup_properties)\ncategories_comparison = studio.play()\n```\nImplementing an `EqualizerTuner`\n```python\nclass MyEqualizerTuner(EqualizerTuner):\n    def create_category_tuning(self, category):\n        if category == 'ServiceOperationA':\n            return EqualizerTuning(operation_a_playback_function,\n                                   operation_a_result_extractor,\n                                   operation_a_comparator)\n        if category == 'ServiceOperationB':\n            return EqualizerTuning(operation_b_playback_function,\n                                   operation_b_result_extractor,\n                                   operation_b_comparator)\n```\n\n# Framework classes - comparing replayed vs recorded operations\n## `PlaybackStudio` class\nThe studio runs many playbacks for one or more categories (operations), and uses the `Equalizer` to conduct a comparison\nbetween the recorded outputs and the playback outputs.\n\n```python\ndef __init__(self, categories, equalizer_tuner, tape_recorder, lookup_properties=None,\n             recording_ids=None, compare_execution_config=None)\n```\n* `categories` - The categories (operations) to conduct comparison for\n* `equalizer_tuner` - Given a category, returns a corresponding equalizer tuning to be used for playback and comparison\n* `tape_recorder` - The tape recorder that will be used to play the recordings\n* `lookup_properties` - Optional `RecordingLookupProperties` used to filter recordings by\n* `recording_ids` - Optional specific recording IDs. If given, the `categories` and `lookup_properties` are ignored and\n  only the given recording IDs will be played\n* `compare_execution_config` -  A configuration specific to the comparison execution flow\n\n## `EqualizerTuner` class\nAn abstract class that is used to create an `EqualizerTuning` per category that contains the correct plugins (functions)\nrequired to play the operation and compare its results.\n\n```python\ndef create_category_tuning(self, category)\n```\nCreate a new `EqualizerTuning` for the given category\n\n```python\nclass EqualizerTuning(object):\n    def __init__(self, playback_function, result_extractor, comparator,\n                 comparison_data_extractor=None):\n        self.playback_function = playback_function\n        self.result_extractor = result_extractor\n        self.comparator = comparator\n        self.comparison_data_extractor = comparison_data_extractor\n```\n\n# Contributions\nFeel free to send pull requests and raise issues. Make sure to add/modify tests to cover your changes.\nPlease squash your commits in the pull request to one commit. If there is a good logical reason to break it into\nfew commits, multiple pull requests are preferred unless there is a good logical reason to bundle the commits to the\nsame pull request.\n\nPlease note that as of now this framework is compatible with both Python 2 and 3, hence any changes should\nkeep that. We use the ״six״ framework to help keep this support.\n\nTo contribute, please review our [contributing policy](https://github.com/Optibus/playback/blob/main/CONTRIBUTING.md).\n\n## Running tests\nTests are automatically run in the CI flow using CircleCI. In order to run them locally, you should install the\ndevelopment requirements:\n`pip install -e .[dev]`\nand then run `pytest tests`.\n","funding_links":[],"categories":["Rest API Testing","Python"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FOptibus%2Fplayback","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FOptibus%2Fplayback","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FOptibus%2Fplayback/lists"}