Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions pkg/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package store

import (
"context"
"encoding/json"
"io"

"github.com/interuss/stacktrace"
Expand Down Expand Up @@ -31,6 +32,27 @@ type OperationHandler[R any] struct {
IsReadOnly bool
}

// EncodeJSON is a general-purpose OperationHandler.Encode that marshals the request as JSON.
// TODO: remove once all operations use custom encoders / decoders.
func EncodeJSON(request OperationRequest) ([]byte, error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Checking how it used in #1597, can't those be actually attached instead to OperationHandler, and T be an additional type parameter of OperationHandler?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This wouldn't work since the registry is defined as a map:
var Registry = map[string]dssstore.OperationHandler[repos.Repository]{}
and we would need to provide a specific request type there.

However, since we expect to have custom encoding, I think it's okay to leave things as they are now. I extracted the json encoding and decoding methods in this PR to make things simpler for the naive implementation and for the transition to the optimized encoding.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In that case please add in both function docs a TODO mentioning that.

buf, err := json.Marshal(request)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to marshal %q request", request.OperationID())
}
return buf, nil
}

// DecodeJSON is a general-purpose OperationHandler.Decode that unmarshals JSON into a new T.
// T must be a pointer to a struct type that implements OperationRequest.
// TODO: remove once all operations use custom encoders / decoders.
func DecodeJSON[T OperationRequest](buf []byte) (OperationRequest, error) {
req := new(T)
if err := json.Unmarshal(buf, req); err != nil {
return nil, stacktrace.Propagate(err, "failed to unmarshal request")
}
return *req, nil
}
Comment thread
MariemBaccari marked this conversation as resolved.

// TransactWithResult wraps Store.Transact and casts the result to ResultType, avoiding a cast at every call site.
func TransactWithResult[R any, ResultType any](ctx context.Context, store Store[R], request OperationRequest) (ResultType, error) {
var empty ResultType
Expand Down
Loading