endpoint.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "fmt"
  7. "sync/atomic"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. "github.com/langgenius/dify-plugin-daemon/internal/core/dify_invocation"
  11. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon"
  12. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon/access_types"
  13. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager"
  14. "github.com/langgenius/dify-plugin-daemon/internal/core/session_manager"
  15. "github.com/langgenius/dify-plugin-daemon/internal/db"
  16. "github.com/langgenius/dify-plugin-daemon/internal/service/install_service"
  17. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  18. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  19. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/requests"
  20. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  21. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  22. )
  23. func Endpoint(
  24. ctx *gin.Context,
  25. endpoint *models.Endpoint,
  26. plugin_installation *models.PluginInstallation,
  27. path string,
  28. ) {
  29. req := ctx.Request.Clone(context.Background())
  30. req.URL.Path = path
  31. var buffer bytes.Buffer
  32. err := req.Write(&buffer)
  33. if err != nil {
  34. ctx.JSON(500, gin.H{"error": err.Error()})
  35. }
  36. identifier, err := plugin_entities.NewPluginUniqueIdentifier(plugin_installation.PluginUniqueIdentifier)
  37. if err != nil {
  38. ctx.JSON(400, gin.H{"error": "Invalid plugin identifier, " + err.Error()})
  39. return
  40. }
  41. // fetch plugin
  42. manager := plugin_manager.Manager()
  43. runtime := manager.Get(identifier)
  44. if runtime == nil {
  45. ctx.JSON(404, gin.H{"error": "plugin not found"})
  46. return
  47. }
  48. // fetch endpoint declaration
  49. endpoint_declaration := runtime.Configuration().Endpoint
  50. if endpoint_declaration == nil {
  51. ctx.JSON(404, gin.H{"error": "endpoint declaration not found"})
  52. return
  53. }
  54. // decrypt settings
  55. settings, err := dify_invocation.InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  56. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  57. TenantId: endpoint.TenantID,
  58. UserId: "",
  59. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  60. },
  61. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  62. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  63. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  64. Identity: endpoint.ID,
  65. Data: endpoint.GetSettings(),
  66. Config: endpoint_declaration.Settings,
  67. },
  68. })
  69. if err != nil {
  70. ctx.JSON(500, gin.H{"error": "failed to decrypt data"})
  71. return
  72. }
  73. session := session_manager.NewSession(
  74. endpoint.TenantID,
  75. "",
  76. identifier,
  77. ctx.GetString("cluster_id"),
  78. access_types.PLUGIN_ACCESS_TYPE_ENDPOINT,
  79. access_types.PLUGIN_ACCESS_ACTION_INVOKE_ENDPOINT,
  80. runtime.Configuration(),
  81. )
  82. defer session.Close()
  83. session.BindRuntime(runtime)
  84. status_code, headers, response, err := plugin_daemon.InvokeEndpoint(
  85. session, &requests.RequestInvokeEndpoint{
  86. RawHttpRequest: hex.EncodeToString(buffer.Bytes()),
  87. Settings: settings,
  88. },
  89. )
  90. if err != nil {
  91. ctx.JSON(500, gin.H{"error": err.Error()})
  92. return
  93. }
  94. defer response.Close()
  95. done := make(chan bool)
  96. closed := new(int32)
  97. ctx.Status(status_code)
  98. for k, v := range *headers {
  99. if len(v) > 0 {
  100. ctx.Writer.Header().Set(k, v[0])
  101. }
  102. }
  103. close := func() {
  104. if atomic.CompareAndSwapInt32(closed, 0, 1) {
  105. close(done)
  106. }
  107. }
  108. defer close()
  109. routine.Submit(func() {
  110. defer close()
  111. for response.Next() {
  112. chunk, err := response.Read()
  113. if err != nil {
  114. ctx.JSON(500, gin.H{"error": err.Error()})
  115. return
  116. }
  117. ctx.Writer.Write(chunk)
  118. ctx.Writer.Flush()
  119. }
  120. })
  121. select {
  122. case <-ctx.Writer.CloseNotify():
  123. case <-done:
  124. case <-time.After(30 * time.Second):
  125. ctx.JSON(500, gin.H{"error": "killed by timeout"})
  126. }
  127. }
  128. func EnableEndpoint(endpoint_id string, tenant_id string) *entities.Response {
  129. endpoint, err := db.GetOne[models.Endpoint](
  130. db.Equal("id", endpoint_id),
  131. db.Equal("tenant_id", tenant_id),
  132. )
  133. if err != nil {
  134. return entities.NewErrorResponse(-404, "Endpoint not found")
  135. }
  136. endpoint.Enabled = true
  137. if err := install_service.EnabledEndpoint(&endpoint); err != nil {
  138. return entities.NewErrorResponse(-500, "Failed to enable endpoint")
  139. }
  140. return entities.NewSuccessResponse("success")
  141. }
  142. func DisableEndpoint(endpoint_id string, tenant_id string) *entities.Response {
  143. endpoint, err := db.GetOne[models.Endpoint](
  144. db.Equal("id", endpoint_id),
  145. db.Equal("tenant_id", tenant_id),
  146. )
  147. if err != nil {
  148. return entities.NewErrorResponse(-404, "Endpoint not found")
  149. }
  150. endpoint.Enabled = false
  151. if err := install_service.DisabledEndpoint(&endpoint); err != nil {
  152. return entities.NewErrorResponse(-500, "Failed to disable endpoint")
  153. }
  154. return entities.NewSuccessResponse("success")
  155. }
  156. func ListEndpoints(tenant_id string, page int, page_size int) *entities.Response {
  157. endpoints, err := db.GetAll[models.Endpoint](
  158. db.Equal("tenant_id", tenant_id),
  159. db.OrderBy("created_at", true),
  160. db.Page(page, page_size),
  161. )
  162. if err != nil {
  163. return entities.NewErrorResponse(-500, fmt.Sprintf("failed to list endpoints: %v", err))
  164. }
  165. // decrypt settings
  166. for i, endpoint := range endpoints {
  167. plugin_installation, err := db.GetOne[models.PluginInstallation](
  168. db.Equal("plugin_id", endpoint.PluginID),
  169. db.Equal("tenant_id", tenant_id),
  170. )
  171. if err != nil {
  172. return entities.NewErrorResponse(-404, fmt.Sprintf("failed to find plugin installation: %v", err))
  173. }
  174. plugin, err := db.GetOne[models.Plugin](
  175. db.Equal("plugin_unique_identifier", plugin_installation.PluginUniqueIdentifier),
  176. )
  177. if err != nil {
  178. return entities.NewErrorResponse(-404, fmt.Sprintf("failed to find plugin: %v", err))
  179. }
  180. plugin_declaration, err := plugin.GetDeclaration()
  181. if err != nil {
  182. return entities.NewErrorResponse(-404, fmt.Sprintf("failed to get plugin declaration: %v", err))
  183. }
  184. if plugin_declaration.Endpoint == nil {
  185. return entities.NewErrorResponse(-404, "plugin does not have an endpoint")
  186. }
  187. decrypted_settings, err := dify_invocation.InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  188. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  189. TenantId: tenant_id,
  190. UserId: "",
  191. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  192. },
  193. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  194. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  195. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  196. Identity: endpoint.ID,
  197. Data: endpoint.GetSettings(),
  198. Config: plugin_declaration.Endpoint.Settings,
  199. },
  200. })
  201. if err != nil {
  202. return entities.NewErrorResponse(-500, fmt.Sprintf("failed to decrypt settings: %v", err))
  203. }
  204. endpoint.SetSettings(decrypted_settings)
  205. endpoints[i] = endpoint
  206. }
  207. return entities.NewSuccessResponse(endpoints)
  208. }