endpoint.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package server
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/langgenius/dify-plugin-daemon/internal/db"
  5. "github.com/langgenius/dify-plugin-daemon/internal/service"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  7. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  8. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  9. )
  10. // DifyPlugin supports register and use endpoint to improve the plugin's functionality
  11. // you can use it to do some magics, looking forward to your imagination, Ciallo~(∠·ω< )⌒
  12. // - Yeuoly
  13. // EndpointHandler is a function type that can be used to handle endpoint requests
  14. type EndpointHandler func(ctx *gin.Context, hook_id string, path string)
  15. func (app *App) Endpoint() func(c *gin.Context) {
  16. return func(c *gin.Context) {
  17. hook_id := c.Param("hook_id")
  18. path := c.Param("path")
  19. if app.endpointHandler != nil {
  20. app.endpointHandler(c, hook_id, path)
  21. } else {
  22. app.EndpointHandler(c, hook_id, path)
  23. }
  24. }
  25. }
  26. func (app *App) EndpointHandler(ctx *gin.Context, hook_id string, path string) {
  27. endpoint, err := db.GetOne[models.Endpoint](
  28. db.Equal("hook_id", hook_id),
  29. )
  30. if err == db.ErrDatabaseNotFound {
  31. ctx.JSON(404, gin.H{"error": "endpoint not found"})
  32. return
  33. }
  34. if err != nil {
  35. log.Error("get endpoint error %v", err)
  36. ctx.JSON(500, gin.H{"error": "internal server error"})
  37. return
  38. }
  39. // get plugin installation
  40. plugin_installation, err := db.GetOne[models.PluginInstallation](
  41. db.Equal("plugin_id", endpoint.PluginID),
  42. db.Equal("tenant_id", endpoint.TenantID),
  43. )
  44. if err != nil {
  45. ctx.JSON(404, gin.H{"error": "plugin installation not found"})
  46. return
  47. }
  48. plugin_unique_identifier, err := plugin_entities.NewPluginUniqueIdentifier(
  49. plugin_installation.PluginUniqueIdentifier,
  50. )
  51. if err != nil {
  52. ctx.JSON(400, gin.H{"error": "invalid plugin unique identifier"})
  53. return
  54. }
  55. // check if plugin exists in current node
  56. if !app.cluster.IsPluginOnCurrentNode(plugin_unique_identifier) {
  57. app.redirectPluginInvokeByPluginIdentifier(ctx, plugin_unique_identifier)
  58. } else {
  59. service.Endpoint(ctx, &endpoint, &plugin_installation, path)
  60. }
  61. }