|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package plugins |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "sync" |
| 23 | + "time" |
| 24 | + |
| 25 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 26 | + |
| 27 | + logutil "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/util/logging" |
| 28 | +) |
| 29 | + |
| 30 | +const ( |
| 31 | + // stalenessThreshold defines the threshold for considering data as stale. |
| 32 | + // if data of a request hasn't been read/write in the last "stalenessThreshold", it is considered as stale data |
| 33 | + // and will be cleaned in the next cleanup cycle. |
| 34 | + stalenessThreshold = time.Minute * 5 |
| 35 | + // cleanupInterval defines the periodic interval that the cleanup go routine uses to check for stale data. |
| 36 | + cleanupInterval = time.Minute |
| 37 | +) |
| 38 | + |
| 39 | +// NewPluginState initializes a new PluginState and returns its pointer. |
| 40 | +func NewPluginState(ctx context.Context) *PluginState { |
| 41 | + pluginState := &PluginState{} |
| 42 | + go pluginState.cleanup(ctx) |
| 43 | + return pluginState |
| 44 | +} |
| 45 | + |
| 46 | +// PluginState provides a mechanism for plugins to store and retrieve arbitrary data by multiple extension points. |
| 47 | +// Data stored by the plugin in one extension point can be written, read or altered by another extension point. |
| 48 | +// The data stored in PluginState is always stored in the context of a given request. |
| 49 | +// If the data hasn't been accessed during "stalenessThreshold", it is cleaned by a cleanup internal mechanism. |
| 50 | +// |
| 51 | +// Note: PluginState uses a sync.Map to back the storage, because it is thread safe. |
| 52 | +// It's aimed to optimize for the "write once and read many times" scenarios. |
| 53 | +type PluginState struct { |
| 54 | + // key: RequestID, value: map[StateKey]StateData |
| 55 | + storage sync.Map |
| 56 | + // key: RequestID, value: time.Time |
| 57 | + requestToLastAccessTime sync.Map |
| 58 | +} |
| 59 | + |
| 60 | +// Read retrieves data with the given "key" in the context of "requestID" from PluginState. |
| 61 | +// If the key is not present, ErrNotFound is returned. |
| 62 | +func (s *PluginState) Read(requestID string, key StateKey) (StateData, error) { |
| 63 | + s.requestToLastAccessTime.Store(requestID, time.Now()) |
| 64 | + stateMap, ok := s.storage.Load(requestID) |
| 65 | + if !ok { |
| 66 | + return nil, ErrNotFound |
| 67 | + } |
| 68 | + |
| 69 | + stateData := stateMap.(map[StateKey]StateData) |
| 70 | + if value, ok := stateData[key]; ok { |
| 71 | + return value, nil |
| 72 | + } |
| 73 | + |
| 74 | + return nil, ErrNotFound |
| 75 | +} |
| 76 | + |
| 77 | +// Write stores the given "val" in PluginState with the given "key" in the context of the given "requestID". |
| 78 | +func (s *PluginState) Write(requestID string, key StateKey, val StateData) { |
| 79 | + s.requestToLastAccessTime.Store(requestID, time.Now()) |
| 80 | + var stateData map[StateKey]StateData |
| 81 | + stateMap, ok := s.storage.Load(requestID) |
| 82 | + if ok { |
| 83 | + stateData = stateMap.(map[StateKey]StateData) |
| 84 | + } else { |
| 85 | + stateData = map[StateKey]StateData{} |
| 86 | + } |
| 87 | + |
| 88 | + stateData[key] = val |
| 89 | + |
| 90 | + s.storage.Store(requestID, stateData) |
| 91 | +} |
| 92 | + |
| 93 | +// Delete deletes data associated with the given requestID. |
| 94 | +// It is possible to call Delete explicitly when the handling of a request is completed |
| 95 | +// or alternatively, if the request failed during its processing, a cleanup goroutine will |
| 96 | +// clean data of stale requests. |
| 97 | +func (s *PluginState) Delete(requestID string) { |
| 98 | + s.storage.Delete(requestID) |
| 99 | + s.requestToLastAccessTime.Delete(requestID) |
| 100 | +} |
| 101 | + |
| 102 | +// cleanup periodically deletes data associated with the given requestID. |
| 103 | +func (s *PluginState) cleanup(ctx context.Context) { |
| 104 | + ticker := time.NewTicker(cleanupInterval) |
| 105 | + defer ticker.Stop() |
| 106 | + for { |
| 107 | + select { |
| 108 | + case <-ctx.Done(): |
| 109 | + log.FromContext(ctx).V(logutil.DEFAULT).Info("Shutting down plugin state cleanup") |
| 110 | + return |
| 111 | + case <-ticker.C: |
| 112 | + s.requestToLastAccessTime.Range(func(k, v any) bool { |
| 113 | + requestID := k.(string) |
| 114 | + lastAccessTime := v.(time.Time) |
| 115 | + if time.Since(lastAccessTime) > stalenessThreshold { |
| 116 | + s.Delete(requestID) // cleanup stale requests (this is safe in sync.Map) |
| 117 | + } |
| 118 | + return true |
| 119 | + }) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | +} |
| 124 | + |
| 125 | +// ReadPluginStateKey retrieves data with the given key from PluginState and asserts it to type T. |
| 126 | +// Returns an error if the key is not found or the type assertion fails. |
| 127 | +func ReadPluginStateKey[T StateData](state *PluginState, requestID string, key StateKey) (T, error) { |
| 128 | + var zero T |
| 129 | + |
| 130 | + raw, err := state.Read(requestID, key) |
| 131 | + if err != nil { |
| 132 | + return zero, err |
| 133 | + } |
| 134 | + |
| 135 | + val, ok := raw.(T) |
| 136 | + if !ok { |
| 137 | + return zero, fmt.Errorf("unexpected type for key %q: got %T", key, raw) |
| 138 | + } |
| 139 | + |
| 140 | + return val, nil |
| 141 | +} |
0 commit comments