You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "joellubi (via GitHub)" <gi...@apache.org> on 2024/02/28 22:31:01 UTC

[PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

joellubi opened a new pull request, #40284:
URL: https://github.com/apache/arrow/pull/40284

   refactor and add stateless sessions
   
   move server session to own module
   
   factor out into separate files
   
   
   <!--
   Thanks for opening a pull request!
   If this is your first pull request you can find detailed information on how 
   to contribute here:
     * [New Contributor's Guide](https://arrow.apache.org/docs/dev/developers/guide/step_by_step/pr_lifecycle.html#reviews-and-merge-of-the-pull-request)
     * [Contributing Overview](https://arrow.apache.org/docs/dev/developers/overview.html)
   
   
   If this is not a [minor PR](https://github.com/apache/arrow/blob/main/CONTRIBUTING.md#Minor-Fixes). Could you open an issue for this pull request on GitHub? https://github.com/apache/arrow/issues/new/choose
   
   Opening GitHub issues ahead of time contributes to the [Openness](http://theapacheway.com/open/#:~:text=Openness%20allows%20new%20users%20the,must%20happen%20in%20the%20open.) of the Apache Arrow project.
   
   Then could you also rename the pull request title in the following format?
   
       GH-${GITHUB_ISSUE_ID}: [${COMPONENT}] ${SUMMARY}
   
   or
   
       MINOR: [${COMPONENT}] ${SUMMARY}
   
   In the case of PARQUET issues on JIRA the title also supports:
   
       PARQUET-${JIRA_ISSUE_ID}: [${COMPONENT}] ${SUMMARY}
   
   -->
   
   ### Rationale for this change
   
   Brings Go implementation in parity with recent session management additions to Java and C++: #34865
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   ### What changes are included in this PR?
   
   TODO
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   ### Are these changes tested?
   
   Yes, both integration and unit tests are included
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   ### Are there any user-facing changes?
   Yes, session management RPC as well as middleware implementations are included. Functionality is entirely additive
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please uncomment the line below and explain which changes are breaking.
   -->
   <!-- **This PR includes breaking changes to public APIs.** -->
   
   <!--
   Please uncomment the line below (and provide explanation) if the changes fix either (a) a security vulnerability, (b) a bug that caused incorrect or invalid data to be produced, or (c) a bug that causes a crash (even when the API contract is upheld). We use this to highlight fixes to issues that may affect users without their knowledge. For this reason, fixing bugs that cause errors don't count, since those are usually obvious.
   -->
   <!-- **This PR contains a "Critical Fix".** -->


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509269058


##########
go/arrow/flight/session/cookies.go:
##########
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package session
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"google.golang.org/grpc/metadata"
+)
+
+func GetIncomingCookieByName(ctx context.Context, name string) (http.Cookie, error) {
+	md, ok := metadata.FromIncomingContext(ctx)
+	if !ok {
+		return http.Cookie{}, fmt.Errorf("no metadata found for incoming context")
+	}

Review Comment:
   AFAIK the only existing cookie middleware is client-side. There is _some_ duplicated logic between the client and server cookie handling, but the semantics are overall different enough that we'd be unlikely to get much code reuse out of factoring the common code.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509627880


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   I think this is a good discussion potentially but I agree that this is an issue scoped to the implementation, which doesn't seem to be an issue for us on the Go side currently. I'm going to merge this as it looks pretty well covered and handled to me here but feel free to continue this discussion even with this PR merged if desired.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508391764


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,240 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// For more details on the Flight Session Specification, see:
+// https://arrow.apache.org/docs/format/FlightSql.html#flight-server-session-management
+//
+// [NewServerSessionMiddleware] manages sessions using cookies, so any client would need its own
+// middleware/support for storing and sending those cookies. The cookies may be stateful or stateless:
+//
+//   - [NewStatefulServerSessionManager] implements stateful cookies.
+//
+//   - [NewStatelessServerSessionManager] implements stateless cookies.
+//
+// See details of either implementation for caveats and recommended usage scenarios.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {

Review Comment:
   Thanks for the callout, didn't realize there was a convention. Updated this now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "indigophox (via GitHub)" <gi...@apache.org>.
indigophox commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509608618


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// The existing middleware implementation uses cookies, so any client would need middleware/support for storing and sending those cookies.
+// Both stateful and stateless session cookie implementations are provided.
+// The default stateful implementation persists sessions in-memory, but a custom SessionStore may be provided for more durable persistence.
+// Stateless session cookies may be used with no additional infrastructure, but they are not encrypted and should not contain sensitive information.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues
+type ServerSession interface {
+	// An identifier for the session that the server can use to reconstruct
+	// the session state on future requests. It is the responsibility of
+	// each implementation to define the token's semantics.
+	Token() string
+	// Get session option value by name, or nil if it does not exist
+	GetSessionOption(name string) *flight.SessionOptionValue
+	// Get a copy of the session options
+	GetSessionOptions() map[string]*flight.SessionOptionValue
+	// Set session option by name to given value
+	SetSessionOption(name string, value *flight.SessionOptionValue)
+	// Idempotently remove name from this session
+	EraseSessionOption(name string)
+	// Close the session
+	Close() error
+	// Report whether the session has been closed
+	Closed() bool
+}
+
+// Handles session lifecycle management
+type ServerSessionManager interface {
+	// Create a new, empty ServerSession
+	CreateSession(ctx context.Context) (ServerSession, error)
+	// Get the current ServerSession, if one exists
+	GetSession(ctx context.Context) (ServerSession, error)
+	// Cleanup any resources associated with the current ServerSession
+	CloseSession(session ServerSession) error
+}
+
+// Implementation of common session behavior. Intended to be extended
+// by specific session implementations.
+type serverSession struct {
+	closed bool
+
+	options map[string]*flight.SessionOptionValue
+	mu      sync.RWMutex
+}
+
+func (session *serverSession) GetSessionOption(name string) *flight.SessionOptionValue {
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	value, found := session.options[name]
+	if !found {
+		return nil
+	}
+
+	return value
+}
+
+func (session *serverSession) GetSessionOptions() map[string]*flight.SessionOptionValue {
+	options := make(map[string]*flight.SessionOptionValue, len(session.options))
+
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	for k, v := range session.options {
+		options[k] = proto.Clone(v).(*flight.SessionOptionValue)
+	}
+
+	return options
+}
+
+func (session *serverSession) SetSessionOption(name string, value *flight.SessionOptionValue) {
+	if value.GetOptionValue() == nil {
+		session.EraseSessionOption(name)
+		return
+	}
+
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	session.options[name] = value
+}
+
+func (session *serverSession) EraseSessionOption(name string) {
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	delete(session.options, name)
+}
+
+func (session *serverSession) Close() error {
+	session.options = nil
+	session.closed = true
+	return nil
+}
+
+func (session *serverSession) Closed() bool {
+	return session.closed
+}
+
+// Create new instance of CustomServerMiddleware implementing server session persistence.
+//
+// The provided manager can be used to customize session implementation/behavior.
+// If no manager is provided, a stateful in-memory, goroutine-safe implementation is used.
+func NewServerSessionMiddleware(manager ServerSessionManager) *serverSessionMiddleware {
+	// Default manager

Review Comment:
   The shipped middleware classes for C++ and Java both provide their own option value store, presently without the option to inject a separate k:v store implementation—although that could be accomplished via a subclass of the provided middleware factory.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "indigophox (via GitHub)" <gi...@apache.org>.
indigophox commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509593351


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @joellubi ultimately this is scoped to the implementation, so anyone building an app against this can do as they please.  The shipped ServerSessionMiddleware just handles the internals; the actual RPC handler can do whatever the app author wants.  I am hoping we can close on #40071 fairly soon (before 16.0.0 code freeze?) so the full functionality can be restored.  I'll resume the discussion over there and hopefully that can get wrapped up with the existing solution or another one.
   
   My other thought for an if-we-have-to-go-down-that-road workaround is for the middleware to internally flag the token as invalidated, so it can expire it next time it's presented instead of outright treating it as invalid, or alternatively (say you're calling SetSessionOptions) just clobber it with a new token for a new session as appropriate.  But again this is dumping work into a temporary hack while we sort out the root issue with middleware handling behaviour.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "indigophox (via GitHub)" <gi...@apache.org>.
indigophox commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508316968


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @joellubi is correct here and the fix also checks out.  Looks like from my commit history that I typoed this while hastily updating the code to work around and omit functionality affected by #40071.  This used to be covered in integration testing but was temporarily removed as the aforementioned issue breaks the ability (in C++) to correctly invalidate sessions (on the server side) when the CloseSession Action is called.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "jduo (via GitHub)" <gi...@apache.org>.
jduo commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508306339


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @indigophox 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508390918


##########
go/arrow/flight/server.go:
##########
@@ -54,15 +55,86 @@ type (
 	Result                          = flight.Result
 	CancelFlightInfoResult          = flight.CancelFlightInfoResult
 	CancelStatus                    = flight.CancelStatus
+	SessionOptionValue              = flight.SessionOptionValue
+	SetSessionOptionsRequest        = flight.SetSessionOptionsRequest
+	SetSessionOptionsResult         = flight.SetSessionOptionsResult
+	SetSessionOptionsResultError    = flight.SetSessionOptionsResult_Error
+	GetSessionOptionsRequest        = flight.GetSessionOptionsRequest
+	GetSessionOptionsResult         = flight.GetSessionOptionsResult
+	CloseSessionRequest             = flight.CloseSessionRequest
+	CloseSessionResult              = flight.CloseSessionResult
 	Empty                           = flight.Empty
 )
 
 // Constants for Action types
 const (
 	CancelFlightInfoActionType    = "CancelFlightInfo"
 	RenewFlightEndpointActionType = "RenewFlightEndpoint"
+	SetSessionOptionsActionType   = "SetSessionOptions"
+	GetSessionOptionsActionType   = "GetSessionOptions"
+	CloseSessionActionType        = "CloseSession"
 )
 
+const (
+	// The set option error is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	SetSessionOptionsResultErrorUnspecified = flight.SetSessionOptionsResult_UNSPECIFIED
+	// The given session option name is invalid.
+	SetSessionOptionsResultErrorInvalidName = flight.SetSessionOptionsResult_INVALID_NAME
+	// The session option value or type is invalid.
+	SetSessionOptionsResultErrorInvalidValue = flight.SetSessionOptionsResult_INVALID_VALUE
+	// The session option cannot be set.
+	SetSessionOptionsResultErrorError = flight.SetSessionOptionsResult_ERROR
+)
+
+const (
+	// The close session status is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	CloseSessionResultUnspecified = flight.CloseSessionResult_UNSPECIFIED
+	// The session close request is complete.
+	CloseSessionResultClosed = flight.CloseSessionResult_CLOSED
+	// The session close request is in progress. The client may retry the request.
+	CloseSessionResultClosing = flight.CloseSessionResult_CLOSING
+	// The session is not closeable.
+	CloseSessionResultNotCloseable = flight.CloseSessionResult_NOT_CLOSEABLE
+)
+
+func NewSessionOptionValues(options map[string]any) (map[string]*flight.SessionOptionValue, error) {

Review Comment:
   Updated



##########
go/arrow/flight/server.go:
##########
@@ -54,15 +55,86 @@ type (
 	Result                          = flight.Result
 	CancelFlightInfoResult          = flight.CancelFlightInfoResult
 	CancelStatus                    = flight.CancelStatus
+	SessionOptionValue              = flight.SessionOptionValue
+	SetSessionOptionsRequest        = flight.SetSessionOptionsRequest
+	SetSessionOptionsResult         = flight.SetSessionOptionsResult
+	SetSessionOptionsResultError    = flight.SetSessionOptionsResult_Error
+	GetSessionOptionsRequest        = flight.GetSessionOptionsRequest
+	GetSessionOptionsResult         = flight.GetSessionOptionsResult
+	CloseSessionRequest             = flight.CloseSessionRequest
+	CloseSessionResult              = flight.CloseSessionResult
 	Empty                           = flight.Empty
 )
 
 // Constants for Action types
 const (
 	CancelFlightInfoActionType    = "CancelFlightInfo"
 	RenewFlightEndpointActionType = "RenewFlightEndpoint"
+	SetSessionOptionsActionType   = "SetSessionOptions"
+	GetSessionOptionsActionType   = "GetSessionOptions"
+	CloseSessionActionType        = "CloseSession"
 )
 
+const (
+	// The set option error is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	SetSessionOptionsResultErrorUnspecified = flight.SetSessionOptionsResult_UNSPECIFIED
+	// The given session option name is invalid.
+	SetSessionOptionsResultErrorInvalidName = flight.SetSessionOptionsResult_INVALID_NAME
+	// The session option value or type is invalid.
+	SetSessionOptionsResultErrorInvalidValue = flight.SetSessionOptionsResult_INVALID_VALUE
+	// The session option cannot be set.
+	SetSessionOptionsResultErrorError = flight.SetSessionOptionsResult_ERROR
+)
+
+const (
+	// The close session status is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	CloseSessionResultUnspecified = flight.CloseSessionResult_UNSPECIFIED
+	// The session close request is complete.
+	CloseSessionResultClosed = flight.CloseSessionResult_CLOSED
+	// The session close request is in progress. The client may retry the request.
+	CloseSessionResultClosing = flight.CloseSessionResult_CLOSING
+	// The session is not closeable.
+	CloseSessionResultNotCloseable = flight.CloseSessionResult_NOT_CLOSEABLE
+)
+
+func NewSessionOptionValues(options map[string]any) (map[string]*flight.SessionOptionValue, error) {
+	sessionOptions := make(map[string]*flight.SessionOptionValue, len(options))
+	for key, val := range options {
+		optval, err := NewSessionOptionValue(val)
+		if err != nil {
+			return nil, err
+		}
+		sessionOptions[key] = &optval
+	}
+
+	return sessionOptions, nil
+}
+
+func NewSessionOptionValue(value any) (flight.SessionOptionValue, error) {

Review Comment:
   Updated



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509626320


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// The existing middleware implementation uses cookies, so any client would need middleware/support for storing and sending those cookies.
+// Both stateful and stateless session cookie implementations are provided.
+// The default stateful implementation persists sessions in-memory, but a custom SessionStore may be provided for more durable persistence.
+// Stateless session cookies may be used with no additional infrastructure, but they are not encrypted and should not contain sensitive information.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues
+type ServerSession interface {
+	// An identifier for the session that the server can use to reconstruct
+	// the session state on future requests. It is the responsibility of
+	// each implementation to define the token's semantics.
+	Token() string
+	// Get session option value by name, or nil if it does not exist
+	GetSessionOption(name string) *flight.SessionOptionValue
+	// Get a copy of the session options
+	GetSessionOptions() map[string]*flight.SessionOptionValue
+	// Set session option by name to given value
+	SetSessionOption(name string, value *flight.SessionOptionValue)
+	// Idempotently remove name from this session
+	EraseSessionOption(name string)
+	// Close the session
+	Close() error
+	// Report whether the session has been closed
+	Closed() bool
+}
+
+// Handles session lifecycle management
+type ServerSessionManager interface {
+	// Create a new, empty ServerSession
+	CreateSession(ctx context.Context) (ServerSession, error)
+	// Get the current ServerSession, if one exists
+	GetSession(ctx context.Context) (ServerSession, error)
+	// Cleanup any resources associated with the current ServerSession
+	CloseSession(session ServerSession) error
+}
+
+// Implementation of common session behavior. Intended to be extended
+// by specific session implementations.
+type serverSession struct {
+	closed bool
+
+	options map[string]*flight.SessionOptionValue
+	mu      sync.RWMutex
+}
+
+func (session *serverSession) GetSessionOption(name string) *flight.SessionOptionValue {
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	value, found := session.options[name]
+	if !found {
+		return nil
+	}
+
+	return value
+}
+
+func (session *serverSession) GetSessionOptions() map[string]*flight.SessionOptionValue {
+	options := make(map[string]*flight.SessionOptionValue, len(session.options))
+
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	for k, v := range session.options {
+		options[k] = proto.Clone(v).(*flight.SessionOptionValue)
+	}
+
+	return options
+}
+
+func (session *serverSession) SetSessionOption(name string, value *flight.SessionOptionValue) {
+	if value.GetOptionValue() == nil {
+		session.EraseSessionOption(name)
+		return
+	}
+
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	session.options[name] = value
+}
+
+func (session *serverSession) EraseSessionOption(name string) {
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	delete(session.options, name)
+}
+
+func (session *serverSession) Close() error {
+	session.options = nil
+	session.closed = true
+	return nil
+}
+
+func (session *serverSession) Closed() bool {
+	return session.closed
+}
+
+// Create new instance of CustomServerMiddleware implementing server session persistence.
+//
+// The provided manager can be used to customize session implementation/behavior.
+// If no manager is provided, a stateful in-memory, goroutine-safe implementation is used.
+func NewServerSessionMiddleware(manager ServerSessionManager) *serverSessionMiddleware {
+	// Default manager

Review Comment:
   Okay given this I think this default here is fine. It's already in the docs explaining that if nil is provided they know what they will get back so i think we're good here. Anyone who wants to have a custom implementation could simply implement the `ServerSessionManager` interface themselves rather than using one of the ones we are providing.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509533629


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @indigophox As I was writing this, the following idea occurred to me:
   
   What if in the meantime while the C++ issue is getting resolved, we changed the C++ implementation to respond with `CloseSessionResult_NOT_CLOSEABLE` to all `CloseSessionRequest`'s? Admittedly that's not exactly what I imagined that result status would end up being used for, but it's kind of accurate right now and most importantly it gives _some_ information to clients to be able recover the edge case gracefully.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509533629


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @indigophox As I was writing this, the following idea occurred to me:
   
   What if, in the meantime while the C++ issue is getting resolved, we changed the C++ implementation to respond with `CloseSessionResult_NOT_CLOSEABLE` to all `CloseSessionRequest`'s? Admittedly that's not exactly what I imagined that result status would end up being used for, but it's kind of accurate right now and most importantly it gives _some_ information to clients to be able recover the edge case gracefully.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1507588548


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// The existing middleware implementation uses cookies, so any client would need middleware/support for storing and sending those cookies.
+// Both stateful and stateless session cookie implementations are provided.
+// The default stateful implementation persists sessions in-memory, but a custom SessionStore may be provided for more durable persistence.
+// Stateless session cookies may be used with no additional infrastructure, but they are not encrypted and should not contain sensitive information.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues
+type ServerSession interface {
+	// An identifier for the session that the server can use to reconstruct
+	// the session state on future requests. It is the responsibility of
+	// each implementation to define the token's semantics.
+	Token() string
+	// Get session option value by name, or nil if it does not exist
+	GetSessionOption(name string) *flight.SessionOptionValue
+	// Get a copy of the session options
+	GetSessionOptions() map[string]*flight.SessionOptionValue
+	// Set session option by name to given value
+	SetSessionOption(name string, value *flight.SessionOptionValue)
+	// Idempotently remove name from this session
+	EraseSessionOption(name string)
+	// Close the session
+	Close() error
+	// Report whether the session has been closed
+	Closed() bool
+}
+
+// Handles session lifecycle management
+type ServerSessionManager interface {
+	// Create a new, empty ServerSession
+	CreateSession(ctx context.Context) (ServerSession, error)
+	// Get the current ServerSession, if one exists
+	GetSession(ctx context.Context) (ServerSession, error)
+	// Cleanup any resources associated with the current ServerSession
+	CloseSession(session ServerSession) error
+}
+
+// Implementation of common session behavior. Intended to be extended
+// by specific session implementations.
+type serverSession struct {
+	closed bool
+
+	options map[string]*flight.SessionOptionValue
+	mu      sync.RWMutex
+}
+
+func (session *serverSession) GetSessionOption(name string) *flight.SessionOptionValue {
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	value, found := session.options[name]
+	if !found {
+		return nil
+	}
+
+	return value
+}
+
+func (session *serverSession) GetSessionOptions() map[string]*flight.SessionOptionValue {
+	options := make(map[string]*flight.SessionOptionValue, len(session.options))
+
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	for k, v := range session.options {
+		options[k] = proto.Clone(v).(*flight.SessionOptionValue)
+	}
+
+	return options
+}
+
+func (session *serverSession) SetSessionOption(name string, value *flight.SessionOptionValue) {
+	if value.GetOptionValue() == nil {
+		session.EraseSessionOption(name)
+		return
+	}
+
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	session.options[name] = value
+}
+
+func (session *serverSession) EraseSessionOption(name string) {
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	delete(session.options, name)
+}
+
+func (session *serverSession) Close() error {
+	session.options = nil
+	session.closed = true
+	return nil
+}
+
+func (session *serverSession) Closed() bool {
+	return session.closed
+}
+
+// Create new instance of CustomServerMiddleware implementing server session persistence.
+//
+// The provided manager can be used to customize session implementation/behavior.
+// If no manager is provided, a stateful in-memory, goroutine-safe implementation is used.
+func NewServerSessionMiddleware(manager ServerSessionManager) *serverSessionMiddleware {
+	// Default manager

Review Comment:
   Is this the right default? Does it make sense to have a default at all or should we require users to specify the session manager?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508106790


##########
go/arrow/flight/client.go:
##########
@@ -421,3 +424,87 @@ func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEn
 	}
 	return &renewedEndpoint, nil
 }
+
+func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = SetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result SetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}
+	return &result, nil
+}
+
+func (c *client) GetSessionOptions(ctx context.Context, request *GetSessionOptionsRequest, opts ...grpc.CallOption) (*GetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = GetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result GetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}

Review Comment:
   could we replace these with a helper function that implements this using generics since the only difference between these methods are the types?



##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   was this a test that was failing that this fixes?



##########
go/arrow/flight/session/cookies.go:
##########
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package session
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"google.golang.org/grpc/metadata"
+)
+
+func GetIncomingCookieByName(ctx context.Context, name string) (http.Cookie, error) {
+	md, ok := metadata.FromIncomingContext(ctx)
+	if !ok {
+		return http.Cookie{}, fmt.Errorf("no metadata found for incoming context")
+	}

Review Comment:
   should this get tied in with the Cookie middleware somehow?



##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// The existing middleware implementation uses cookies, so any client would need middleware/support for storing and sending those cookies.
+// Both stateful and stateless session cookie implementations are provided.
+// The default stateful implementation persists sessions in-memory, but a custom SessionStore may be provided for more durable persistence.
+// Stateless session cookies may be used with no additional infrastructure, but they are not encrypted and should not contain sensitive information.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues
+type ServerSession interface {
+	// An identifier for the session that the server can use to reconstruct
+	// the session state on future requests. It is the responsibility of
+	// each implementation to define the token's semantics.
+	Token() string
+	// Get session option value by name, or nil if it does not exist
+	GetSessionOption(name string) *flight.SessionOptionValue
+	// Get a copy of the session options
+	GetSessionOptions() map[string]*flight.SessionOptionValue
+	// Set session option by name to given value
+	SetSessionOption(name string, value *flight.SessionOptionValue)
+	// Idempotently remove name from this session
+	EraseSessionOption(name string)
+	// Close the session
+	Close() error
+	// Report whether the session has been closed
+	Closed() bool
+}
+
+// Handles session lifecycle management
+type ServerSessionManager interface {
+	// Create a new, empty ServerSession
+	CreateSession(ctx context.Context) (ServerSession, error)
+	// Get the current ServerSession, if one exists
+	GetSession(ctx context.Context) (ServerSession, error)
+	// Cleanup any resources associated with the current ServerSession
+	CloseSession(session ServerSession) error
+}
+
+// Implementation of common session behavior. Intended to be extended
+// by specific session implementations.
+type serverSession struct {
+	closed bool
+
+	options map[string]*flight.SessionOptionValue
+	mu      sync.RWMutex
+}
+
+func (session *serverSession) GetSessionOption(name string) *flight.SessionOptionValue {
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	value, found := session.options[name]
+	if !found {
+		return nil
+	}
+
+	return value
+}
+
+func (session *serverSession) GetSessionOptions() map[string]*flight.SessionOptionValue {
+	options := make(map[string]*flight.SessionOptionValue, len(session.options))
+
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	for k, v := range session.options {
+		options[k] = proto.Clone(v).(*flight.SessionOptionValue)
+	}
+
+	return options
+}
+
+func (session *serverSession) SetSessionOption(name string, value *flight.SessionOptionValue) {
+	if value.GetOptionValue() == nil {
+		session.EraseSessionOption(name)
+		return
+	}
+
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	session.options[name] = value
+}
+
+func (session *serverSession) EraseSessionOption(name string) {
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	delete(session.options, name)
+}
+
+func (session *serverSession) Close() error {
+	session.options = nil
+	session.closed = true
+	return nil
+}
+
+func (session *serverSession) Closed() bool {
+	return session.closed
+}
+
+// Create new instance of CustomServerMiddleware implementing server session persistence.
+//
+// The provided manager can be used to customize session implementation/behavior.
+// If no manager is provided, a stateful in-memory, goroutine-safe implementation is used.
+func NewServerSessionMiddleware(manager ServerSessionManager) *serverSessionMiddleware {
+	// Default manager

Review Comment:
   @lidavidm Was a default defined or specified for handling with FlightSQL sessions?



##########
go/arrow/flight/client.go:
##########
@@ -421,3 +424,87 @@ func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEn
 	}
 	return &renewedEndpoint, nil
 }
+
+func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = SetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result SetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}
+	return &result, nil

Review Comment:
   Should we do `return &result, ReadUntilEOF(stream)` ?



##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,240 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// For more details on the Flight Session Specification, see:
+// https://arrow.apache.org/docs/format/FlightSql.html#flight-server-session-management
+//
+// [NewServerSessionMiddleware] manages sessions using cookies, so any client would need its own
+// middleware/support for storing and sending those cookies. The cookies may be stateful or stateless:
+//
+//   - [NewStatefulServerSessionManager] implements stateful cookies.
+//
+//   - [NewStatelessServerSessionManager] implements stateless cookies.
+//
+// See details of either implementation for caveats and recommended usage scenarios.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {

Review Comment:
   Conventions say it should start with the name of the function:
   
   `NewSessionContext returns a copy of the provided context containing the provided ServerSession`



##########
go/arrow/flight/server.go:
##########
@@ -54,15 +55,86 @@ type (
 	Result                          = flight.Result
 	CancelFlightInfoResult          = flight.CancelFlightInfoResult
 	CancelStatus                    = flight.CancelStatus
+	SessionOptionValue              = flight.SessionOptionValue
+	SetSessionOptionsRequest        = flight.SetSessionOptionsRequest
+	SetSessionOptionsResult         = flight.SetSessionOptionsResult
+	SetSessionOptionsResultError    = flight.SetSessionOptionsResult_Error
+	GetSessionOptionsRequest        = flight.GetSessionOptionsRequest
+	GetSessionOptionsResult         = flight.GetSessionOptionsResult
+	CloseSessionRequest             = flight.CloseSessionRequest
+	CloseSessionResult              = flight.CloseSessionResult
 	Empty                           = flight.Empty
 )
 
 // Constants for Action types
 const (
 	CancelFlightInfoActionType    = "CancelFlightInfo"
 	RenewFlightEndpointActionType = "RenewFlightEndpoint"
+	SetSessionOptionsActionType   = "SetSessionOptions"
+	GetSessionOptionsActionType   = "GetSessionOptions"
+	CloseSessionActionType        = "CloseSession"
 )
 
+const (
+	// The set option error is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	SetSessionOptionsResultErrorUnspecified = flight.SetSessionOptionsResult_UNSPECIFIED
+	// The given session option name is invalid.
+	SetSessionOptionsResultErrorInvalidName = flight.SetSessionOptionsResult_INVALID_NAME
+	// The session option value or type is invalid.
+	SetSessionOptionsResultErrorInvalidValue = flight.SetSessionOptionsResult_INVALID_VALUE
+	// The session option cannot be set.
+	SetSessionOptionsResultErrorError = flight.SetSessionOptionsResult_ERROR
+)
+
+const (
+	// The close session status is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	CloseSessionResultUnspecified = flight.CloseSessionResult_UNSPECIFIED
+	// The session close request is complete.
+	CloseSessionResultClosed = flight.CloseSessionResult_CLOSED
+	// The session close request is in progress. The client may retry the request.
+	CloseSessionResultClosing = flight.CloseSessionResult_CLOSING
+	// The session is not closeable.
+	CloseSessionResultNotCloseable = flight.CloseSessionResult_NOT_CLOSEABLE
+)
+
+func NewSessionOptionValues(options map[string]any) (map[string]*flight.SessionOptionValue, error) {

Review Comment:
   godoc comment?



##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,240 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// For more details on the Flight Session Specification, see:
+// https://arrow.apache.org/docs/format/FlightSql.html#flight-server-session-management
+//
+// [NewServerSessionMiddleware] manages sessions using cookies, so any client would need its own
+// middleware/support for storing and sending those cookies. The cookies may be stateful or stateless:
+//
+//   - [NewStatefulServerSessionManager] implements stateful cookies.
+//
+//   - [NewStatelessServerSessionManager] implements stateless cookies.
+//
+// See details of either implementation for caveats and recommended usage scenarios.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues

Review Comment:
   ```suggestion
   // ServerSession is a container for named SessionOptionValues
   ```



##########
go/arrow/flight/server.go:
##########
@@ -54,15 +55,86 @@ type (
 	Result                          = flight.Result
 	CancelFlightInfoResult          = flight.CancelFlightInfoResult
 	CancelStatus                    = flight.CancelStatus
+	SessionOptionValue              = flight.SessionOptionValue
+	SetSessionOptionsRequest        = flight.SetSessionOptionsRequest
+	SetSessionOptionsResult         = flight.SetSessionOptionsResult
+	SetSessionOptionsResultError    = flight.SetSessionOptionsResult_Error
+	GetSessionOptionsRequest        = flight.GetSessionOptionsRequest
+	GetSessionOptionsResult         = flight.GetSessionOptionsResult
+	CloseSessionRequest             = flight.CloseSessionRequest
+	CloseSessionResult              = flight.CloseSessionResult
 	Empty                           = flight.Empty
 )
 
 // Constants for Action types
 const (
 	CancelFlightInfoActionType    = "CancelFlightInfo"
 	RenewFlightEndpointActionType = "RenewFlightEndpoint"
+	SetSessionOptionsActionType   = "SetSessionOptions"
+	GetSessionOptionsActionType   = "GetSessionOptions"
+	CloseSessionActionType        = "CloseSession"
 )
 
+const (
+	// The set option error is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	SetSessionOptionsResultErrorUnspecified = flight.SetSessionOptionsResult_UNSPECIFIED
+	// The given session option name is invalid.
+	SetSessionOptionsResultErrorInvalidName = flight.SetSessionOptionsResult_INVALID_NAME
+	// The session option value or type is invalid.
+	SetSessionOptionsResultErrorInvalidValue = flight.SetSessionOptionsResult_INVALID_VALUE
+	// The session option cannot be set.
+	SetSessionOptionsResultErrorError = flight.SetSessionOptionsResult_ERROR
+)
+
+const (
+	// The close session status is unknown. Servers should avoid
+	// using this value (send a NOT_FOUND error if the requested
+	// FlightInfo is not known). Clients can retry the request.
+	CloseSessionResultUnspecified = flight.CloseSessionResult_UNSPECIFIED
+	// The session close request is complete.
+	CloseSessionResultClosed = flight.CloseSessionResult_CLOSED
+	// The session close request is in progress. The client may retry the request.
+	CloseSessionResultClosing = flight.CloseSessionResult_CLOSING
+	// The session is not closeable.
+	CloseSessionResultNotCloseable = flight.CloseSessionResult_NOT_CLOSEABLE
+)
+
+func NewSessionOptionValues(options map[string]any) (map[string]*flight.SessionOptionValue, error) {
+	sessionOptions := make(map[string]*flight.SessionOptionValue, len(options))
+	for key, val := range options {
+		optval, err := NewSessionOptionValue(val)
+		if err != nil {
+			return nil, err
+		}
+		sessionOptions[key] = &optval
+	}
+
+	return sessionOptions, nil
+}
+
+func NewSessionOptionValue(value any) (flight.SessionOptionValue, error) {

Review Comment:
   Godoc comment?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "indigophox (via GitHub)" <gi...@apache.org>.
indigophox commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508318481


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   Notably if you continue on with the same client cookie middleware in any integration test after closing the session from the client, calls are going to get failed out by the C++ server session middleware because the client cookie middleware will submit a now-invalid session token (that the server was unable to invalidate) with the request headers.  This is fixable pending #40071.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508393306


##########
go/arrow/flight/client.go:
##########
@@ -421,3 +424,87 @@ func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEn
 	}
 	return &renewedEndpoint, nil
 }
+
+func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = SetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result SetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}
+	return &result, nil
+}
+
+func (c *client) GetSessionOptions(ctx context.Context, request *GetSessionOptionsRequest, opts ...grpc.CallOption) (*GetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = GetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result GetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}

Review Comment:
   I did come across a slight issue where the function signature of `CancelFlightInfo` probably wasn't what it should've been. It was copying the return value rather than returning a pointer. I fixed this to align with the other handlers as well as anywhere I tracked down usage.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509206318


##########
go/arrow/flight/session/cookies.go:
##########
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package session
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"google.golang.org/grpc/metadata"
+)
+
+func GetIncomingCookieByName(ctx context.Context, name string) (http.Cookie, error) {
+	md, ok := metadata.FromIncomingContext(ctx)
+	if !ok {
+		return http.Cookie{}, fmt.Errorf("no metadata found for incoming context")
+	}

Review Comment:
   Should it replace the existing cookie middleware?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509345959


##########
go/arrow/flight/session/cookies.go:
##########
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package session
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"google.golang.org/grpc/metadata"
+)
+
+func GetIncomingCookieByName(ctx context.Context, name string) (http.Cookie, error) {
+	md, ok := metadata.FromIncomingContext(ctx)
+	if !ok {
+		return http.Cookie{}, fmt.Errorf("no metadata found for incoming context")
+	}

Review Comment:
   Fair enough, that makes sense.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509351090


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @joellubi Can you add a corresponding fix to the client middleware that matches #40071 which @indigophox mentioned? Or at minimum, file a follow-up issue for this so we don't forget it



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "zeroshade (via GitHub)" <gi...@apache.org>.
zeroshade merged PR #40284:
URL: https://github.com/apache/arrow/pull/40284


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "conbench-apache-arrow[bot] (via GitHub)" <gi...@apache.org>.
conbench-apache-arrow[bot] commented on PR #40284:
URL: https://github.com/apache/arrow/pull/40284#issuecomment-1974242926

   After merging your PR, Conbench analyzed the 5 benchmarking runs that have been run so far on merge-commit 81c9d30be32058d51583caf22a2ff61b7d7c82cc.
   
   There were no benchmark performance regressions. 🎉
   
   The [full Conbench report](https://github.com/apache/arrow/runs/22196485000) has more details. It also includes information about 3 possible false positives for unstable benchmarks that are known to sometimes produce them.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "lidavidm (via GitHub)" <gi...@apache.org>.
lidavidm commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508149968


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// The existing middleware implementation uses cookies, so any client would need middleware/support for storing and sending those cookies.
+// Both stateful and stateless session cookie implementations are provided.
+// The default stateful implementation persists sessions in-memory, but a custom SessionStore may be provided for more durable persistence.
+// Stateless session cookies may be used with no additional infrastructure, but they are not encrypted and should not contain sensitive information.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues
+type ServerSession interface {
+	// An identifier for the session that the server can use to reconstruct
+	// the session state on future requests. It is the responsibility of
+	// each implementation to define the token's semantics.
+	Token() string
+	// Get session option value by name, or nil if it does not exist
+	GetSessionOption(name string) *flight.SessionOptionValue
+	// Get a copy of the session options
+	GetSessionOptions() map[string]*flight.SessionOptionValue
+	// Set session option by name to given value
+	SetSessionOption(name string, value *flight.SessionOptionValue)
+	// Idempotently remove name from this session
+	EraseSessionOption(name string)
+	// Close the session
+	Close() error
+	// Report whether the session has been closed
+	Closed() bool
+}
+
+// Handles session lifecycle management
+type ServerSessionManager interface {
+	// Create a new, empty ServerSession
+	CreateSession(ctx context.Context) (ServerSession, error)
+	// Get the current ServerSession, if one exists
+	GetSession(ctx context.Context) (ServerSession, error)
+	// Cleanup any resources associated with the current ServerSession
+	CloseSession(session ServerSession) error
+}
+
+// Implementation of common session behavior. Intended to be extended
+// by specific session implementations.
+type serverSession struct {
+	closed bool
+
+	options map[string]*flight.SessionOptionValue
+	mu      sync.RWMutex
+}
+
+func (session *serverSession) GetSessionOption(name string) *flight.SessionOptionValue {
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	value, found := session.options[name]
+	if !found {
+		return nil
+	}
+
+	return value
+}
+
+func (session *serverSession) GetSessionOptions() map[string]*flight.SessionOptionValue {
+	options := make(map[string]*flight.SessionOptionValue, len(session.options))
+
+	session.mu.RLock()
+	defer session.mu.RUnlock()
+	for k, v := range session.options {
+		options[k] = proto.Clone(v).(*flight.SessionOptionValue)
+	}
+
+	return options
+}
+
+func (session *serverSession) SetSessionOption(name string, value *flight.SessionOptionValue) {
+	if value.GetOptionValue() == nil {
+		session.EraseSessionOption(name)
+		return
+	}
+
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	session.options[name] = value
+}
+
+func (session *serverSession) EraseSessionOption(name string) {
+	session.mu.Lock()
+	defer session.mu.Unlock()
+	delete(session.options, name)
+}
+
+func (session *serverSession) Close() error {
+	session.options = nil
+	session.closed = true
+	return nil
+}
+
+func (session *serverSession) Closed() bool {
+	return session.closed
+}
+
+// Create new instance of CustomServerMiddleware implementing server session persistence.
+//
+// The provided manager can be used to customize session implementation/behavior.
+// If no manager is provided, a stateful in-memory, goroutine-safe implementation is used.
+func NewServerSessionMiddleware(manager ServerSessionManager) *serverSessionMiddleware {
+	// Default manager

Review Comment:
   No. It's up to the server implementation. The only requirement is that the client faithfully pass back cookies.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508392171


##########
go/arrow/flight/session/session.go:
##########
@@ -0,0 +1,240 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package session provides server middleware and reference implementations for Flight session management.
+//
+// For more details on the Flight Session Specification, see:
+// https://arrow.apache.org/docs/format/FlightSql.html#flight-server-session-management
+//
+// [NewServerSessionMiddleware] manages sessions using cookies, so any client would need its own
+// middleware/support for storing and sending those cookies. The cookies may be stateful or stateless:
+//
+//   - [NewStatefulServerSessionManager] implements stateful cookies.
+//
+//   - [NewStatelessServerSessionManager] implements stateless cookies.
+//
+// See details of either implementation for caveats and recommended usage scenarios.
+package session
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net/http"
+	"sync"
+
+	"github.com/apache/arrow/go/v16/arrow/flight"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+)
+
+var ErrNoSession error = errors.New("flight: server session not present")
+
+type sessionMiddlewareKey struct{}
+
+// Return a copy of the provided context containing the provided ServerSession
+func NewSessionContext(ctx context.Context, session ServerSession) context.Context {
+	return context.WithValue(ctx, sessionMiddlewareKey{}, session)
+}
+
+// Retrieve the ServerSession from the provided context if it exists.
+// An error indicates that the session was not found in the context.
+func GetSessionFromContext(ctx context.Context) (ServerSession, error) {
+	session, ok := ctx.Value(sessionMiddlewareKey{}).(ServerSession)
+	if !ok {
+		return nil, ErrNoSession
+	}
+	return session, nil
+}
+
+// Container for named SessionOptionValues

Review Comment:
   Updated



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508389654


##########
go/arrow/flight/client.go:
##########
@@ -421,3 +424,87 @@ func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEn
 	}
 	return &renewedEndpoint, nil
 }
+
+func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = SetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result SetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}
+	return &result, nil

Review Comment:
   Yes, I made this change as part of the refactor to consolidate the logic for the action handlers



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508266351


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   Yes the C++ server scenario was failing when I added a test to the Go client scenario that attempts to close the currently open session. I'm not especially familiar with C++, but my understanding is that this was previously saying that "if the session DOES exist, then it is an error to close it" which seems backwards. Is my understanding accurate?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508392369


##########
go/arrow/flight/session/cookies.go:
##########
@@ -0,0 +1,80 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package session
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+
+	"google.golang.org/grpc/metadata"
+)
+
+func GetIncomingCookieByName(ctx context.Context, name string) (http.Cookie, error) {
+	md, ok := metadata.FromIncomingContext(ctx)
+	if !ok {
+		return http.Cookie{}, fmt.Errorf("no metadata found for incoming context")
+	}

Review Comment:
   What exactly do you mean by tying it in?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1508390624


##########
go/arrow/flight/client.go:
##########
@@ -421,3 +424,87 @@ func (c *client) RenewFlightEndpoint(ctx context.Context, request *RenewFlightEn
 	}
 	return &renewedEndpoint, nil
 }
+
+func (c *client) SetSessionOptions(ctx context.Context, request *SetSessionOptionsRequest, opts ...grpc.CallOption) (*SetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = SetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result SetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}
+	return &result, nil
+}
+
+func (c *client) GetSessionOptions(ctx context.Context, request *GetSessionOptionsRequest, opts ...grpc.CallOption) (*GetSessionOptionsResult, error) {
+	var err error
+	var action flight.Action
+	action.Type = GetSessionOptionsActionType
+	action.Body, err = proto.Marshal(request)
+	if err != nil {
+		return nil, err
+	}
+	stream, err := c.DoAction(ctx, &action, opts...)
+	if err != nil {
+		return nil, err
+	}
+	res, err := stream.Recv()
+	if err != nil {
+		return nil, err
+	}
+	var result GetSessionOptionsResult
+	err = proto.Unmarshal(res.Body, &result)
+	if err != nil {
+		return nil, err
+	}
+	err = ReadUntilEOF(stream)
+	if err != nil {
+		return nil, err
+	}

Review Comment:
   I was thinking the same as I was going through this. I went back and took a stab at it, let me know what you think.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #40284:
URL: https://github.com/apache/arrow/pull/40284#issuecomment-1970030980

   :warning: GitHub issue #40155 **has been automatically assigned in GitHub** to PR creator.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] GH-40155: [Go][FlightRPC][FlightSQL] Implement Session Management [arrow]

Posted by "joellubi (via GitHub)" <gi...@apache.org>.
joellubi commented on code in PR #40284:
URL: https://github.com/apache/arrow/pull/40284#discussion_r1509529296


##########
cpp/src/arrow/flight/sql/server_session_middleware.cc:
##########
@@ -80,7 +80,7 @@ class ServerSessionMiddlewareImpl : public ServerSessionMiddleware {
 
   Status CloseSession() override {
     const std::lock_guard<std::shared_mutex> l(mutex_);
-    if (static_cast<bool>(session_)) {
+    if (!static_cast<bool>(session_)) {

Review Comment:
   @zeroshade I think that in the case @indigophox mentioned the client middleware is actually behaving correctly. The problem with the C++ server middleware is that it's unable to invalidate the cookie for an existing session (i.e. it never sends `Set-Cookie: arrow_flight_session_id=<session-id>; Max-Age=0`) so the client keeps the cookie stored, as it should. Then the next time the client makes any request it sends the cookie (i.e. `Cookie: arrow_flight_session_id=<session-id>`) along with it, but the server has completely forgotten about that session and considers the token invalid.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org