Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add simple key-value store to the builders #480

Merged
merged 3 commits into from
Feb 28, 2023
Merged

Conversation

ivokub
Copy link
Collaborator

@ivokub ivokub commented Feb 20, 2023

With new gadgets, we may have some state we want to store over different calls. Instead of using singletons (essentially global variables), we instead add a map[any]any to the builders which allow to store builder-local variables.

To prevent overuse of the map, we dont publish the methods publicly in the frontend.API, but instead embed an instance in the builders themselves. If a gadget wants to use the storage, then they first have to type-assert the frontend.API instance to kvstore.Store and then on the new variable call SetKeyValue and GetKeyValue.

Another great aspect of having any keys is that we can use any comparable types (comparable because map implementation requires so). This allows us to avoid any collisions by enforcing that the keys are of different type. See the example below:

type gadgetKey struct{}

func (c *Circuit) Define(api frontend.API) error {
    kv, ok := api.(kvstore.Store)
    if !ok {
        return fmt.Errorf("api doesn't implement Store")
    }
    kv.SetKeyValue(gadgetKey{}, "aaa") // only this package can set this key as they do not have the type
    // ...
    res := kv.GetKeyValue(gadgetKey{}) //
    // use res = "aaa"
}

In the previous example, we could also have for example type gadgetKey int and then have different values for the keys if the gadget needs to store different values.

Initially I thought about just using context.Context as it provides similar features, but it doesn't seem to fit in our use cases. See comments in #472.

@ivokub ivokub added this to the v0.9.0 milestone Feb 20, 2023
@ivokub ivokub requested a review from Tabaie February 20, 2023 23:27
@ivokub ivokub self-assigned this Feb 20, 2023
Copy link
Contributor

@Tabaie Tabaie left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice! I for one find this very useful for GKR and Commitments

@Tabaie Tabaie merged commit 70b3acf into develop Feb 28, 2023
@Tabaie Tabaie deleted the feat/kvstore branch February 28, 2023 18:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants