endpoint.go 2.4 KB

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