feat(retriever): activate OpenSearch k-NN driver (PR 3 of 3)
Phase 3 (#1440) gate flip. PR 1 (#1445) + PR 2a (#1481) + PR 2b (#1482) laid the type prep + driver skeleton + read/write paths as gated dead code; this PR wires every activation surface so opensearch becomes a registerable VectorStore engine. Activation wiring - internal/types: validEngineTypes / GetVectorStoreTypes (with HNSW bounds + knn_engine enum + Immutable hints) / retrieverEngineMapping / buildEnvStoreForDriver — every gated surface now recognises "opensearch". IndexConfig grows four omitempty HNSW fields (HNSWM / HNSWEFConstruction / HNSWEFSearch / KNNEngine), keeping other engines' serialised config byte-identical. - internal/container: createOpenSearchEngine + the switch case in createEngineServiceFromStore; the RETRIEVE_DRIVER=opensearch env path in initRetrieveEngineRegistry; NewEngineFactory now closes over the AuditLogService (the EngineFactory type itself is unchanged). - internal/application/service/vectorstore_healthcheck.go: a testOpenSearchConnection case so CreateStore's connectivity probe accepts opensearch instead of returning 400. - internal/application/repository/retriever/opensearch/transport.go: NewOpenSearchClient is exported so the factory and env path can build the TLS-hardened client; healthcheck.go reuses the unexported probeVersion / probeKNNPlugin for the service-layer probe. Service-layer validation - validateOpenSearchIndexConfig validates the HNSW caps (m 2-100, ef_construction 2-4096, ef_search 1-10000, knn_engine ∈ lucene|faiss). Shards/replicas continue to be enforced by the flat ValidateIndexConfig. Create-only: UpdateStore mutates the name only. - validateConnectionConfig requires addr for opensearch. Sync implementations (stubs.go shrinks) - CopyIndices (copy.go) mirrors the Elasticsearch / Qdrant pattern — search → BatchSave with the source_id remap for generated questions — so dim/keyword routing and the source_id contract come from BatchSave for free. embeddingMap is keyed by the *target* SourceID because OpenSearch's BatchSave looks up embeddings by SourceID (lookupEmbedding), not by chunk_id (the ES driver's convention). Pagination is from/size; copies larger than max_result_window (default 10000) need the scroll-based async path that lands later. - BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID (bulk_update.go) group the input by target value and issue one _update_by_query per group over the cross-dim <base>_* pattern. Caller values flow through bound script params only — never string-interpolated into the Painless source — closing the script-injection surface. - inspectByQueryResponse (byquery.go) mirrors inspectBulkResponse: the full failure reason goes to the debug log only; the returned error carries the bounded id + type. - UpdateByQueryParams.Refresh is *bool in opensearch-go v4.6.0 (the same shape as DeleteByQuery's quirk), so refresh=wait_for is not expressible; we use refresh=true. Driver-owned audit (DIP) - A new opensearch.AuditSink interface (with nopSink + WithAuditSink functional option) lets the driver emit opensearch.index_created and opensearch.reindex_executed events without importing any service package — the service layer implements the interface. NewRepository takes opts, so existing 4-arg test call sites keep compiling unchanged. - internal/container/audit_sink.go bridges AuditSink to AuditLogService. When the context carries no tenant (the env-path registration ctx during boot, for example) the adapter skips the emit with a warning rather than silently writing tenant_id=0, which would collide with the system-scope sentinel. Frontend + polish - FieldSchema (frontend/src/api/vector-store.ts) gains min/max/enum/ immutable. VectorStoreSettings.vue is now schema-driven: a closed `enum` renders a t-select; number inputs use the schema's `:min`/`:max` and fall back to the legacy replica-vs-shard heuristic only when the schema does not pin them; a danger-coloured warning fires when insecure_skip_verify is toggled on (the switch and warning are wrapped in a vertical stack so the warning sits on its own row below the switch). - i18n: labels for hnsw_m / hnsw_ef_construction / hnsw_ef_search / knn_engine / insecure_skip_verify plus the warning copy in en-US, ko-KR, zh-CN, ru-RU. - docker-compose.dev.yml: an opensearch profile (single-node 3.3.2 with security plugin disabled for dev only). OpenSearch Dashboards lives in a separate, opt-in opensearch-ui profile so the heavy UI container is not forced up alongside the cluster (the driver e2e is fully curl-verifiable against :9200). The new docs/dev/opensearch-integration-test.md covers the end-to-end exercise and the single-node guidance (set replicas=0 to keep the cluster Green). Gating-guard tests flipped - The "OpenSearch is NOT in validEngineTypes / mapping / types list / env builder / stubs" guard tests from PR 1 / PR 2 are replaced by their positive counterparts in this PR. The test suite was the activation checklist; the activation flip is its diff. Backward compatibility - Additive everywhere. IndexConfig's new HNSW fields are omitempty so other engines' serialised config is byte-identical. Existing Elasticsearch / Qdrant / Milvus / Weaviate / Doris / TencentVectorDB stores are untouched. No migrations. Test plan - go build ./... clean - go vet ./... clean - gofmt -l clean on touched files - go test ./... — only TestOssEnsureBucket_CreateFails (Aliyun OSS endpoint), the docreader gRPC tests, and the doris SQL-shape tests fail; all three are pre-existing on upstream/main and untouched by this PR. - New tests across internal/types, opensearch, service and container — including a full end-to-end env-path test that exercises initRetrieveEngineRegistry with RETRIEVE_DRIVER=opensearch against an httptest cluster.
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/application/repository/retriever/opensearch"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// auditSinkAdapter bridges the OpenSearch driver's AuditSink (which the driver
|
||||
// owns so it imports no service package) to the service-layer AuditLogService.
|
||||
// This keeps the dependency one-way: the driver depends only on its own
|
||||
// AuditSink abstraction; the container implements it.
|
||||
type auditSinkAdapter struct {
|
||||
svc interfaces.AuditLogService
|
||||
}
|
||||
|
||||
// newAuditSinkAdapter returns an opensearch.AuditSink backed by svc. A nil svc
|
||||
// yields a sink whose emits are no-ops.
|
||||
func newAuditSinkAdapter(svc interfaces.AuditLogService) opensearch.AuditSink {
|
||||
return auditSinkAdapter{svc: svc}
|
||||
}
|
||||
|
||||
func (a auditSinkAdapter) EmitIndexCreated(ctx context.Context, alias string, dim int) {
|
||||
a.emit(ctx, types.AuditActionOpenSearchIndexCreated, alias,
|
||||
map[string]any{"alias": alias, "dim": dim})
|
||||
}
|
||||
|
||||
func (a auditSinkAdapter) EmitReindexExecuted(ctx context.Context, srcAlias, dstAlias string, docs int64) {
|
||||
a.emit(ctx, types.AuditActionOpenSearchReindexExecuted, dstAlias,
|
||||
map[string]any{"src_alias": srcAlias, "dst_alias": dstAlias, "docs": docs})
|
||||
}
|
||||
|
||||
// emit writes one audit entry. It skips (with a warning) when the context
|
||||
// carries no tenant — driver events can fire from background task contexts
|
||||
// (e.g. lazy index creation under an async copy task), and writing tenant_id=0
|
||||
// would collide with the system-scope sentinel and corrupt the audit trail.
|
||||
func (a auditSinkAdapter) emit(ctx context.Context, action types.AuditAction, target string, detail map[string]any) {
|
||||
if a.svc == nil {
|
||||
return
|
||||
}
|
||||
tid, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s: no tenant in context, skipping audit (target=%s)", action, target)
|
||||
return
|
||||
}
|
||||
// Details is a typed JSON blob — only bounded, non-secret fields. Never
|
||||
// include cluster reason strings or connection secrets.
|
||||
b, err := json.Marshal(detail)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s: marshal details failed: %v", action, err)
|
||||
b = []byte("{}")
|
||||
}
|
||||
if err := a.svc.Log(ctx, &types.AuditLog{
|
||||
TenantID: tid,
|
||||
Action: action,
|
||||
TargetType: "opensearch_index",
|
||||
TargetID: target,
|
||||
Details: types.JSON(b),
|
||||
}); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("[audit] %s emit failed: %v", action, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// fakeAuditSvc records Log calls.
|
||||
type fakeAuditSvc struct {
|
||||
logged []*types.AuditLog
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeAuditSvc) Log(_ context.Context, e *types.AuditLog) error {
|
||||
f.logged = append(f.logged, e)
|
||||
return f.err
|
||||
}
|
||||
func (f *fakeAuditSvc) LogDenied(context.Context, *gin.Context, uint64, string, string, types.TenantRole) error {
|
||||
return nil
|
||||
}
|
||||
func (f *fakeAuditSvc) List(context.Context, uint64, *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (f *fakeAuditSvc) Purge(context.Context, int) (int64, error) { return 0, nil }
|
||||
|
||||
func ctxWithTenant(id uint64) context.Context {
|
||||
return context.WithValue(context.Background(), types.TenantIDContextKey, id)
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_EmitsWithTenant(t *testing.T) {
|
||||
f := &fakeAuditSvc{}
|
||||
sink := newAuditSinkAdapter(f)
|
||||
|
||||
sink.EmitIndexCreated(ctxWithTenant(42), "weknora_768", 768)
|
||||
if len(f.logged) != 1 {
|
||||
t.Fatalf("want 1 audit entry, got %d", len(f.logged))
|
||||
}
|
||||
e := f.logged[0]
|
||||
if e.TenantID != 42 {
|
||||
t.Errorf("tenant: want 42, got %d", e.TenantID)
|
||||
}
|
||||
if e.Action != types.AuditActionOpenSearchIndexCreated {
|
||||
t.Errorf("action: want %s, got %s", types.AuditActionOpenSearchIndexCreated, e.Action)
|
||||
}
|
||||
if e.Details == nil {
|
||||
t.Error("details should be populated")
|
||||
}
|
||||
|
||||
sink.EmitReindexExecuted(ctxWithTenant(7), "src", "dst", 9)
|
||||
if len(f.logged) != 2 || f.logged[1].Action != types.AuditActionOpenSearchReindexExecuted {
|
||||
t.Errorf("reindex audit not recorded: %+v", f.logged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_SkipsWithoutTenant(t *testing.T) {
|
||||
f := &fakeAuditSvc{}
|
||||
sink := newAuditSinkAdapter(f)
|
||||
// background ctx carries no tenant → adapter must skip (never write tenant=0)
|
||||
sink.EmitIndexCreated(context.Background(), "weknora_768", 768)
|
||||
sink.EmitReindexExecuted(context.Background(), "a", "b", 1)
|
||||
if len(f.logged) != 0 {
|
||||
t.Errorf("want 0 audit entries without tenant, got %d", len(f.logged))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuditSinkAdapter_NilServiceNoPanic(t *testing.T) {
|
||||
sink := newAuditSinkAdapter(nil)
|
||||
sink.EmitIndexCreated(ctxWithTenant(1), "x", 1) // must not panic
|
||||
}
|
||||
@@ -40,6 +40,7 @@ import (
|
||||
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
|
||||
milvusRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/milvus"
|
||||
neo4jRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/neo4j"
|
||||
openSearchRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/opensearch"
|
||||
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
|
||||
@@ -785,10 +786,16 @@ func initFileService(cfg *config.Config) (interfaces.FileService, error) {
|
||||
// Returns:
|
||||
// - Configured retrieval engine registry
|
||||
// - Error if initialization fails
|
||||
func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.RetrieveEngineRegistry, error) {
|
||||
func initRetrieveEngineRegistry(
|
||||
db *gorm.DB, cfg *config.Config, auditSvc interfaces.AuditLogService,
|
||||
) (interfaces.RetrieveEngineRegistry, error) {
|
||||
registry := retriever.NewRetrieveEngineRegistry()
|
||||
retrieveDriver := strings.Split(os.Getenv("RETRIEVE_DRIVER"), ",")
|
||||
log := logger.GetLogger(context.Background())
|
||||
// Audit sink for OpenSearch driver events (index created / reindex). Driver
|
||||
// events fire under a tenant-scoped ctx at indexing time; the env-path
|
||||
// registration ctx below has no tenant, so those emits self-skip.
|
||||
auditSink := newAuditSinkAdapter(auditSvc)
|
||||
|
||||
if slices.Contains(retrieveDriver, "postgres") {
|
||||
postgresRepo := postgresRepo.NewPostgresRetrieveEngineRepository(db)
|
||||
@@ -854,6 +861,29 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
|
||||
}
|
||||
}
|
||||
|
||||
if slices.Contains(retrieveDriver, "opensearch") {
|
||||
cc := &types.ConnectionConfig{
|
||||
Addr: os.Getenv("OPENSEARCH_ADDR"),
|
||||
Username: os.Getenv("OPENSEARCH_USERNAME"),
|
||||
Password: os.Getenv("OPENSEARCH_PASSWORD"),
|
||||
InsecureSkipVerify: strings.EqualFold(os.Getenv("OPENSEARCH_INSECURE_SKIP_VERIFY"), "true"),
|
||||
}
|
||||
client, err := openSearchRepo.NewOpenSearchClient(cc)
|
||||
if err != nil {
|
||||
log.Errorf("Create opensearch client failed: %v", err)
|
||||
} else if repo, err := openSearchRepo.NewRepository(
|
||||
context.Background(), client, "", nil, openSearchRepo.WithAuditSink(auditSink),
|
||||
); err != nil {
|
||||
log.Errorf("Create opensearch repository failed: %v", err)
|
||||
} else if err := registry.Register(
|
||||
retriever.NewKVHybridRetrieveEngine(repo, types.OpenSearchRetrieverEngineType),
|
||||
); err != nil {
|
||||
log.Errorf("Register opensearch retrieve engine failed: %v", err)
|
||||
} else {
|
||||
log.Infof("Register opensearch retrieve engine success")
|
||||
}
|
||||
}
|
||||
|
||||
if slices.Contains(retrieveDriver, "qdrant") {
|
||||
qdrantHost := os.Getenv("QDRANT_HOST")
|
||||
if qdrantHost == "" {
|
||||
@@ -1061,7 +1091,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
|
||||
}
|
||||
// ─── DB store registration (byStoreID) ───
|
||||
if storeReg, ok := registry.(*retriever.RetrieveEngineRegistry); ok {
|
||||
loadDBStoresIntoRegistry(storeReg, db, cfg)
|
||||
loadDBStoresIntoRegistry(storeReg, db, cfg, auditSink)
|
||||
}
|
||||
|
||||
return registry, nil
|
||||
@@ -1069,7 +1099,9 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
|
||||
|
||||
// loadDBStoresIntoRegistry loads VectorStore records from DB and registers them
|
||||
// in the registry's byStoreID map. Failures are logged and skipped (non-fatal).
|
||||
func loadDBStoresIntoRegistry(storeRegistry interfaces.StoreRegistry, db *gorm.DB, cfg *config.Config) {
|
||||
func loadDBStoresIntoRegistry(
|
||||
storeRegistry interfaces.StoreRegistry, db *gorm.DB, cfg *config.Config, auditSink openSearchRepo.AuditSink,
|
||||
) {
|
||||
ctx := context.Background()
|
||||
log := logger.GetLogger(ctx)
|
||||
|
||||
@@ -1086,7 +1118,7 @@ func loadDBStoresIntoRegistry(storeRegistry interfaces.StoreRegistry, db *gorm.D
|
||||
|
||||
log.Infof("Loading %d vector store(s) from database", len(stores))
|
||||
for _, store := range stores {
|
||||
svc, err := createEngineServiceFromStore(ctx, store, db, cfg)
|
||||
svc, err := createEngineServiceFromStore(ctx, store, db, cfg, auditSink)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to create engine for store %s (%s): %v", store.ID, store.Name, err)
|
||||
continue
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
|
||||
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
|
||||
milvusRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/milvus"
|
||||
openSearchRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/opensearch"
|
||||
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
|
||||
@@ -35,21 +36,27 @@ import (
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
)
|
||||
|
||||
// NewEngineFactory returns an EngineFactory function closed over db and cfg.
|
||||
// Registered in dig and injected into VectorStoreService for dynamic registry updates.
|
||||
func NewEngineFactory(db *gorm.DB, cfg *config.Config) interfaces.EngineFactory {
|
||||
// NewEngineFactory returns an EngineFactory function closed over db, cfg, and
|
||||
// an audit sink (built from the AuditLogService). Registered in dig and
|
||||
// injected into VectorStoreService for dynamic registry updates. The
|
||||
// EngineFactory type itself is unchanged — the audit sink is captured in the
|
||||
// closure rather than added to the signature.
|
||||
func NewEngineFactory(db *gorm.DB, cfg *config.Config, auditSvc interfaces.AuditLogService) interfaces.EngineFactory {
|
||||
sink := newAuditSinkAdapter(auditSvc)
|
||||
return func(ctx context.Context, store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
return createEngineServiceFromStore(ctx, store, db, cfg)
|
||||
return createEngineServiceFromStore(ctx, store, db, cfg, sink)
|
||||
}
|
||||
}
|
||||
|
||||
// createEngineServiceFromStore creates a RetrieveEngineService from a VectorStore's config.
|
||||
// This is the DB store counterpart of the env-based initialization in initRetrieveEngineRegistry.
|
||||
// auditSink may be nil (audit becomes a no-op).
|
||||
func createEngineServiceFromStore(
|
||||
ctx context.Context,
|
||||
store types.VectorStore,
|
||||
db *gorm.DB,
|
||||
cfg *config.Config,
|
||||
auditSink openSearchRepo.AuditSink,
|
||||
) (interfaces.RetrieveEngineService, error) {
|
||||
switch store.EngineType {
|
||||
case types.PostgresRetrieverEngineType:
|
||||
@@ -68,11 +75,40 @@ func createEngineServiceFromStore(
|
||||
return createSQLiteEngine(store, db)
|
||||
case types.TencentVectorDBRetrieverEngineType:
|
||||
return createTencentVectorDBEngine(store)
|
||||
case types.OpenSearchRetrieverEngineType:
|
||||
return createOpenSearchEngine(ctx, store, auditSink)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported engine type: %s", store.EngineType)
|
||||
}
|
||||
}
|
||||
|
||||
// createOpenSearchEngine builds an OpenSearch k-NN retrieve engine. Mirrors
|
||||
// createElasticsearchV8Engine but uses the driver's TLS-hardened client
|
||||
// constructor and injects the audit sink. NewRepository probes the cluster
|
||||
// (version + k-NN plugin), so an unreachable cluster fails here at
|
||||
// registration rather than on first query.
|
||||
func createOpenSearchEngine(
|
||||
ctx context.Context, store types.VectorStore, auditSink openSearchRepo.AuditSink,
|
||||
) (interfaces.RetrieveEngineService, error) {
|
||||
client, err := openSearchRepo.NewOpenSearchClient(&store.ConnectionConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create opensearch client: %w", err)
|
||||
}
|
||||
// Env stores share the cluster without a per-store index prefix; DB stores
|
||||
// fold their (>=16-char) ID into the index name. NewRepository enforces the
|
||||
// length rule, so map env-store IDs to "".
|
||||
storeID := store.ID
|
||||
if types.IsEnvStoreID(storeID) {
|
||||
storeID = ""
|
||||
}
|
||||
repo, err := openSearchRepo.NewRepository(ctx, client, storeID, &store.IndexConfig,
|
||||
openSearchRepo.WithAuditSink(auditSink))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create opensearch repository: %w", err)
|
||||
}
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.OpenSearchRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
func createPostgresEngine(store types.VectorStore, db *gorm.DB) (interfaces.RetrieveEngineService, error) {
|
||||
if store.ConnectionConfig.UseDefaultConnection {
|
||||
repo := postgresRepo.NewPostgresRetrieveEngineRepository(db)
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package container
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// osClusterHandler simulates an OpenSearch cluster for the driver's
|
||||
// construction probe: GET / (version) + /_cat/plugins (k-NN on every node).
|
||||
func osClusterHandler(distribution, number string, knnInstalled bool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/_cat/plugins" {
|
||||
if knnInstalled {
|
||||
_, _ = w.Write([]byte(`[{"name":"node-1","component":"opensearch-knn"}]`))
|
||||
} else {
|
||||
_, _ = w.Write([]byte(`[{"name":"node-1","component":"opensearch-sql"}]`))
|
||||
}
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"version":{"distribution":"` + distribution + `","number":"` + number + `"}}`))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenSearchEngine_WiresClientAndRepo(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "3.3.2", true))
|
||||
defer ts.Close()
|
||||
|
||||
store := types.VectorStore{
|
||||
ID: "", // env-style (no index prefix)
|
||||
EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL},
|
||||
}
|
||||
svc, err := createOpenSearchEngine(context.Background(), store, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("createOpenSearchEngine: %v", err)
|
||||
}
|
||||
if svc == nil {
|
||||
t.Fatal("want non-nil engine service")
|
||||
}
|
||||
if svc.EngineType() != types.OpenSearchRetrieverEngineType {
|
||||
t.Errorf("engine type: want opensearch, got %s", svc.EngineType())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateOpenSearchEngine_RejectsBadCluster(t *testing.T) {
|
||||
// Elasticsearch distribution must be rejected at construction.
|
||||
ts := httptest.NewServer(osClusterHandler("elasticsearch", "8.10.4", true))
|
||||
defer ts.Close()
|
||||
_, err := createOpenSearchEngine(context.Background(),
|
||||
types.VectorStore{EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL}}, nil)
|
||||
if err == nil {
|
||||
t.Error("elasticsearch cluster should be rejected at engine creation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateEngineServiceFromStore_OpenSearchCaseReached(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "2.11.0", true))
|
||||
defer ts.Close()
|
||||
svc, err := createEngineServiceFromStore(context.Background(),
|
||||
types.VectorStore{EngineType: types.OpenSearchRetrieverEngineType,
|
||||
ConnectionConfig: types.ConnectionConfig{Addr: ts.URL}},
|
||||
nil, &config.Config{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("createEngineServiceFromStore (opensearch case): %v", err)
|
||||
}
|
||||
if svc == nil || svc.EngineType() != types.OpenSearchRetrieverEngineType {
|
||||
t.Errorf("opensearch case not wired correctly: %v", svc)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInitRetrieveEngineRegistry_OpenSearchEnvPath exercises the
|
||||
// RETRIEVE_DRIVER=opensearch env-path registration block end to end.
|
||||
func TestInitRetrieveEngineRegistry_OpenSearchEnvPath(t *testing.T) {
|
||||
ts := httptest.NewServer(osClusterHandler("opensearch", "3.3.2", true))
|
||||
defer ts.Close()
|
||||
|
||||
// In-memory DB: the vector_stores table is absent, so loadDBStores logs
|
||||
// and returns (non-fatal) — only the env-path block matters here.
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open in-mem db: %v", err)
|
||||
}
|
||||
|
||||
t.Setenv("RETRIEVE_DRIVER", "opensearch")
|
||||
t.Setenv("OPENSEARCH_ADDR", ts.URL)
|
||||
|
||||
registry, err := initRetrieveEngineRegistry(db, &config.Config{}, &fakeAuditSvc{})
|
||||
if err != nil {
|
||||
t.Fatalf("initRetrieveEngineRegistry: %v", err)
|
||||
}
|
||||
if _, err := registry.GetRetrieveEngineService(types.OpenSearchRetrieverEngineType); err != nil {
|
||||
t.Errorf("opensearch engine not registered via env path: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user