-
Notifications
You must be signed in to change notification settings - Fork 308
feat(cache): cache the tenant model provider list in the daemon #780
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f9f6b2f
fix(parser): let UnmarshalJson return slice payloads
GareArc dce4300
feat(cache): cache tenant model installations in the daemon
GareArc eeb03c8
Update PLUGIN_MODEL_INSTALLATIONS_CACHE_TTL value
GareArc 26c4df3
Increase PluginModelInstallationsCacheTTL to 1440
GareArc 9347739
feat(cache): put the model installations cache behind a switch, off b…
GareArc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
internal/types/models/curd/model_installations_cache_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| package curd | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/langgenius/dify-plugin-daemon/internal/db" | ||
| "github.com/langgenius/dify-plugin-daemon/internal/types/models" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/entities/plugin_entities" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/utils/cache" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/utils/cache/helper" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const ( | ||
| CACHE_TEST_TENANT_ID = "3d9e7c11-5b2a-4f8d-9e01-7a6b5c4d3e2f" | ||
| CACHE_TEST_PLUGIN_UNIQUE_IDENTIFIER = "acme/vertex-connector:0.4.1@0123456789abcdef" | ||
| CACHE_TEST_PLUGIN_ID = "acme/vertex-connector" | ||
| CACHE_TEST_PAGE_FIELD = "1:256" | ||
| CACHE_TEST_SENTINEL = `[{"provider":"stale-entry"}]` | ||
| ) | ||
|
|
||
| func cleanupInstallPluginCacheTest(t *testing.T) { | ||
| t.Helper() | ||
| t.Cleanup(func() { | ||
| _ = db.DeleteByCondition(&models.PluginInstallation{TenantID: CACHE_TEST_TENANT_ID}) | ||
| _ = db.DeleteByCondition(&models.AIModelInstallation{TenantID: CACHE_TEST_TENANT_ID}) | ||
| _ = db.DeleteByCondition(&models.Plugin{ | ||
| PluginUniqueIdentifier: CACHE_TEST_PLUGIN_UNIQUE_IDENTIFIER, | ||
| }) | ||
| _, _ = cache.Del(helper.ModelInstallationsCacheKey(CACHE_TEST_TENANT_ID)) | ||
| }) | ||
| } | ||
|
|
||
| func seedModelInstallationsCache(t *testing.T) { | ||
| t.Helper() | ||
| require.NoError(t, cache.SetMapOneField( | ||
| helper.ModelInstallationsCacheKey(CACHE_TEST_TENANT_ID), | ||
| CACHE_TEST_PAGE_FIELD, | ||
| CACHE_TEST_SENTINEL, | ||
| )) | ||
| require.True(t, modelInstallationsCacheExists(t), "seed must land before the assertion is meaningful") | ||
| } | ||
|
|
||
| func modelInstallationsCacheExists(t *testing.T) bool { | ||
| t.Helper() | ||
| exists, err := cache.Exist(helper.ModelInstallationsCacheKey(CACHE_TEST_TENANT_ID)) | ||
| require.NoError(t, err) | ||
| return exists == 1 | ||
| } | ||
|
|
||
| func installCacheTestPlugin(declaration *plugin_entities.PluginDeclaration) error { | ||
| _, _, err := InstallPlugin( | ||
| CACHE_TEST_TENANT_ID, | ||
| plugin_entities.PluginUniqueIdentifier(CACHE_TEST_PLUGIN_UNIQUE_IDENTIFIER), | ||
| plugin_entities.PLUGIN_RUNTIME_TYPE_LOCAL, | ||
| declaration, | ||
| "test", | ||
| nil, | ||
| ) | ||
| return err | ||
| } | ||
|
|
||
| // The invalidation must also run when the transaction fails, otherwise a retry after a | ||
| // failed Redis DEL can never clear the cache: it aborts on ErrPluginAlreadyInstalled first. | ||
| func TestInstallPluginInvalidatesModelInstallationsCacheOnRetry(t *testing.T) { | ||
| cleanupInstallPluginCacheTest(t) | ||
|
|
||
| declaration := &plugin_entities.PluginDeclaration{ | ||
| Model: &plugin_entities.ModelProviderDeclaration{ | ||
| Provider: "declaration-provider", | ||
| }, | ||
| } | ||
|
|
||
| seedModelInstallationsCache(t) | ||
| require.NoError(t, installCacheTestPlugin(declaration)) | ||
| assert.False(t, modelInstallationsCacheExists(t), "a successful install must drop the tenant cache") | ||
|
|
||
| seedModelInstallationsCache(t) | ||
| require.ErrorIs(t, installCacheTestPlugin(declaration), ErrPluginAlreadyInstalled) | ||
| assert.False(t, modelInstallationsCacheExists(t), "a retry must still drop the tenant cache") | ||
| } | ||
|
|
||
| func TestInstallPluginLeavesModelInstallationsCacheAloneWithoutModel(t *testing.T) { | ||
| cleanupInstallPluginCacheTest(t) | ||
|
|
||
| seedModelInstallationsCache(t) | ||
| require.NoError(t, installCacheTestPlugin(&plugin_entities.PluginDeclaration{})) | ||
| assert.True(t, modelInstallationsCacheExists(t), "a plugin without a model must not invalidate") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| package helper | ||
|
|
||
| import ( | ||
| "errors" | ||
| "strconv" | ||
| "strings" | ||
| "sync/atomic" | ||
| "time" | ||
|
|
||
| "github.com/langgenius/dify-plugin-daemon/internal/db" | ||
| "github.com/langgenius/dify-plugin-daemon/internal/types/models" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/entities/plugin_entities" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/utils/cache" | ||
| "github.com/langgenius/dify-plugin-daemon/pkg/utils/log" | ||
| ) | ||
|
|
||
| const DEFAULT_MODEL_INSTALLATIONS_CACHE_TTL = 60 * time.Minute | ||
|
|
||
| var ( | ||
| modelInstallationsCacheEnabled atomic.Bool | ||
| modelInstallationsCacheTTL atomic.Int64 | ||
| ) | ||
|
|
||
| func SetModelInstallationsCacheEnabled(enabled bool) { | ||
| modelInstallationsCacheEnabled.Store(enabled) | ||
| } | ||
|
|
||
| func SetModelInstallationsCacheTTL(ttl time.Duration) { | ||
| if ttl <= 0 { | ||
| ttl = DEFAULT_MODEL_INSTALLATIONS_CACHE_TTL | ||
| } | ||
| modelInstallationsCacheTTL.Store(int64(ttl)) | ||
| } | ||
|
|
||
| func currentModelInstallationsCacheTTL() time.Duration { | ||
| if ttl := modelInstallationsCacheTTL.Load(); ttl > 0 { | ||
| return time.Duration(ttl) | ||
| } | ||
| return DEFAULT_MODEL_INSTALLATIONS_CACHE_TTL | ||
| } | ||
|
|
||
| type AIModelInstallationWithDeclaration struct { | ||
| models.AIModelInstallation | ||
|
|
||
| Declaration *plugin_entities.ModelProviderDeclaration `json:"declaration"` | ||
| } | ||
|
|
||
| func modelInstallationsCacheField(page int, pageSize int) string { | ||
| return strings.Join( | ||
| []string{ | ||
| strconv.Itoa(page), | ||
| strconv.Itoa(pageSize), | ||
| }, | ||
| ":", | ||
| ) | ||
| } | ||
|
|
||
| func CombinedListModelInstallations( | ||
| tenantId string, | ||
| page int, | ||
| pageSize int, | ||
| ) ([]AIModelInstallationWithDeclaration, error) { | ||
| if !modelInstallationsCacheEnabled.Load() { | ||
| return listModelInstallations(tenantId, page, pageSize) | ||
| } | ||
|
|
||
| cacheKey := ModelInstallationsCacheKey(tenantId) | ||
| cacheField := modelInstallationsCacheField(page, pageSize) | ||
|
|
||
| cached, err := cache.GetMapField[[]AIModelInstallationWithDeclaration](cacheKey, cacheField) | ||
| if err == nil { | ||
| return *cached, nil | ||
| } | ||
| if !errors.Is(err, cache.ErrNotFound) { | ||
| log.Warn("failed to read model installations cache", "key", cacheKey, "error", err) | ||
| } | ||
|
|
||
| data, err := listModelInstallations(tenantId, page, pageSize) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if err := cache.SetMapOneField(cacheKey, cacheField, data); err != nil { | ||
| log.Warn("failed to store model installations cache", "key", cacheKey, "error", err) | ||
| } else if _, err := cache.Expire(cacheKey, currentModelInstallationsCacheTTL()); err != nil { | ||
| log.Warn("failed to set model installations cache expiry", "key", cacheKey, "error", err) | ||
| } | ||
|
|
||
| return data, nil | ||
| } | ||
|
|
||
| func listModelInstallations( | ||
| tenantId string, | ||
| page int, | ||
| pageSize int, | ||
| ) ([]AIModelInstallationWithDeclaration, error) { | ||
| installations, err := db.GetAll[models.AIModelInstallation]( | ||
| db.Equal("tenant_id", tenantId), | ||
| db.Page(page, pageSize), | ||
| ) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| data := make([]AIModelInstallationWithDeclaration, 0, len(installations)) | ||
|
|
||
| for _, installation := range installations { | ||
| uniqueIdentifier := plugin_entities.PluginUniqueIdentifier(installation.PluginUniqueIdentifier) | ||
| runtimeType := plugin_entities.PLUGIN_RUNTIME_TYPE_LOCAL | ||
| if uniqueIdentifier.RemoteLike() { | ||
| runtimeType = plugin_entities.PLUGIN_RUNTIME_TYPE_REMOTE | ||
| } | ||
|
|
||
| declaration, err := CombinedGetPluginDeclaration(uniqueIdentifier, runtimeType) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| data = append(data, AIModelInstallationWithDeclaration{ | ||
| AIModelInstallation: installation, | ||
| Declaration: declaration.Model, | ||
| }) | ||
| } | ||
|
|
||
| return data, nil | ||
| } | ||
|
|
||
| func DeleteModelInstallationsCache(tenantId string) { | ||
| cacheKey := ModelInstallationsCacheKey(tenantId) | ||
| if _, err := cache.Del(cacheKey); err != nil { | ||
| log.Warn("failed to clear model installations cache", "key", cacheKey, "error", err) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.