endpoint.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "sync/atomic"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/langgenius/dify-plugin-daemon/internal/core/dify_invocation"
  12. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon"
  13. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_daemon/access_types"
  14. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager"
  15. "github.com/langgenius/dify-plugin-daemon/internal/core/session_manager"
  16. "github.com/langgenius/dify-plugin-daemon/internal/db"
  17. "github.com/langgenius/dify-plugin-daemon/internal/service/install_service"
  18. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  19. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  20. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/requests"
  21. "github.com/langgenius/dify-plugin-daemon/internal/types/exception"
  22. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  23. "github.com/langgenius/dify-plugin-daemon/internal/utils/encryption"
  24. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  25. )
  26. func Endpoint(
  27. ctx *gin.Context,
  28. endpoint *models.Endpoint,
  29. pluginInstallation *models.PluginInstallation,
  30. path string,
  31. ) {
  32. if !endpoint.Enabled {
  33. ctx.JSON(404, exception.NotFoundError(errors.New("endpoint not found")).ToResponse())
  34. return
  35. }
  36. req := ctx.Request.Clone(context.Background())
  37. req.URL.Path = path
  38. var buffer bytes.Buffer
  39. err := req.Write(&buffer)
  40. if err != nil {
  41. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  42. }
  43. identifier, err := plugin_entities.NewPluginUniqueIdentifier(pluginInstallation.PluginUniqueIdentifier)
  44. if err != nil {
  45. ctx.JSON(400, exception.PluginUniqueIdentifierError(err).ToResponse())
  46. return
  47. }
  48. // fetch plugin
  49. manager := plugin_manager.Manager()
  50. runtime, err := manager.Get(identifier)
  51. if err != nil {
  52. ctx.JSON(404, exception.ErrPluginNotFound().ToResponse())
  53. return
  54. }
  55. // fetch endpoint declaration
  56. endpointDeclaration := runtime.Configuration().Endpoint
  57. if endpointDeclaration == nil {
  58. ctx.JSON(404, exception.ErrPluginNotFound().ToResponse())
  59. return
  60. }
  61. // decrypt settings
  62. settings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  63. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  64. TenantId: endpoint.TenantID,
  65. UserId: "",
  66. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  67. },
  68. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  69. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  70. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  71. Identity: endpoint.ID,
  72. Data: endpoint.Settings,
  73. Config: endpointDeclaration.Settings,
  74. },
  75. })
  76. if err != nil {
  77. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  78. return
  79. }
  80. session := session_manager.NewSession(
  81. session_manager.NewSessionPayload{
  82. TenantID: endpoint.TenantID,
  83. UserID: "",
  84. PluginUniqueIdentifier: identifier,
  85. ClusterID: ctx.GetString("cluster_id"),
  86. InvokeFrom: access_types.PLUGIN_ACCESS_TYPE_ENDPOINT,
  87. Action: access_types.PLUGIN_ACCESS_ACTION_INVOKE_ENDPOINT,
  88. Declaration: runtime.Configuration(),
  89. BackwardsInvocation: manager.BackwardsInvocation(),
  90. IgnoreCache: false,
  91. EndpointID: &endpoint.ID,
  92. },
  93. )
  94. defer session.Close(session_manager.CloseSessionPayload{
  95. IgnoreCache: false,
  96. })
  97. session.BindRuntime(runtime)
  98. statusCode, headers, response, err := plugin_daemon.InvokeEndpoint(
  99. session, &requests.RequestInvokeEndpoint{
  100. RawHttpRequest: hex.EncodeToString(buffer.Bytes()),
  101. Settings: settings,
  102. },
  103. )
  104. if err != nil {
  105. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  106. return
  107. }
  108. defer response.Close()
  109. done := make(chan bool)
  110. closed := new(int32)
  111. ctx.Status(statusCode)
  112. for k, v := range *headers {
  113. if len(v) > 0 {
  114. ctx.Writer.Header().Set(k, v[0])
  115. }
  116. }
  117. close := func() {
  118. if atomic.CompareAndSwapInt32(closed, 0, 1) {
  119. close(done)
  120. }
  121. }
  122. defer close()
  123. routine.Submit(func() {
  124. defer close()
  125. for response.Next() {
  126. chunk, err := response.Read()
  127. if err != nil {
  128. ctx.JSON(500, exception.InternalServerError(err).ToResponse())
  129. return
  130. }
  131. ctx.Writer.Write(chunk)
  132. ctx.Writer.Flush()
  133. }
  134. })
  135. select {
  136. case <-ctx.Writer.CloseNotify():
  137. case <-done:
  138. case <-time.After(240 * time.Second):
  139. ctx.JSON(500, exception.InternalServerError(errors.New("killed by timeout")).ToResponse())
  140. }
  141. }
  142. func EnableEndpoint(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 exception.NotFoundError(errors.New("endpoint not found")).ToResponse()
  149. }
  150. endpoint.Enabled = true
  151. if err := install_service.EnabledEndpoint(&endpoint); err != nil {
  152. return exception.InternalServerError(errors.New("failed to enable endpoint")).ToResponse()
  153. }
  154. return entities.NewSuccessResponse(true)
  155. }
  156. func DisableEndpoint(endpoint_id string, tenant_id string) *entities.Response {
  157. endpoint, err := db.GetOne[models.Endpoint](
  158. db.Equal("id", endpoint_id),
  159. db.Equal("tenant_id", tenant_id),
  160. )
  161. if err != nil {
  162. return exception.NotFoundError(errors.New("Endpoint not found")).ToResponse()
  163. }
  164. endpoint.Enabled = false
  165. if err := install_service.DisabledEndpoint(&endpoint); err != nil {
  166. return exception.InternalServerError(errors.New("failed to disable endpoint")).ToResponse()
  167. }
  168. return entities.NewSuccessResponse(true)
  169. }
  170. func ListEndpoints(tenant_id string, page int, page_size int) *entities.Response {
  171. endpoints, err := db.GetAll[models.Endpoint](
  172. db.Equal("tenant_id", tenant_id),
  173. db.OrderBy("created_at", true),
  174. db.Page(page, page_size),
  175. )
  176. if err != nil {
  177. return exception.InternalServerError(fmt.Errorf("failed to list endpoints: %v", err)).ToResponse()
  178. }
  179. manager := plugin_manager.Manager()
  180. if manager == nil {
  181. return exception.InternalServerError(errors.New("failed to get plugin manager")).ToResponse()
  182. }
  183. // decrypt settings
  184. for i, endpoint := range endpoints {
  185. pluginInstallation, err := db.GetOne[models.PluginInstallation](
  186. db.Equal("plugin_id", endpoint.PluginID),
  187. db.Equal("tenant_id", tenant_id),
  188. )
  189. if err != nil {
  190. // use empty settings and declaration for uninstalled plugins
  191. endpoint.Settings = map[string]any{}
  192. endpoint.Declaration = &plugin_entities.EndpointProviderDeclaration{
  193. Settings: []plugin_entities.ProviderConfig{},
  194. Endpoints: []plugin_entities.EndpointDeclaration{},
  195. EndpointFiles: []string{},
  196. }
  197. endpoints[i] = endpoint
  198. continue
  199. }
  200. pluginUniqueIdentifier, err := plugin_entities.NewPluginUniqueIdentifier(
  201. pluginInstallation.PluginUniqueIdentifier,
  202. )
  203. if err != nil {
  204. return exception.PluginUniqueIdentifierError(
  205. fmt.Errorf("failed to parse plugin unique identifier: %v", err),
  206. ).ToResponse()
  207. }
  208. pluginDeclaration, err := manager.GetDeclaration(
  209. pluginUniqueIdentifier,
  210. tenant_id,
  211. plugin_entities.PluginRuntimeType(pluginInstallation.RuntimeType),
  212. )
  213. if err != nil {
  214. return exception.InternalServerError(
  215. fmt.Errorf("failed to get plugin declaration: %v", err),
  216. ).ToResponse()
  217. }
  218. if pluginDeclaration.Endpoint == nil {
  219. return exception.NotFoundError(errors.New("plugin does not have an endpoint")).ToResponse()
  220. }
  221. decryptedSettings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  222. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  223. TenantId: tenant_id,
  224. UserId: "",
  225. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  226. },
  227. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  228. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  229. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  230. Identity: endpoint.ID,
  231. Data: endpoint.Settings,
  232. Config: pluginDeclaration.Endpoint.Settings,
  233. },
  234. })
  235. if err != nil {
  236. return exception.InternalServerError(
  237. fmt.Errorf("failed to decrypt settings: %v", err),
  238. ).ToResponse()
  239. }
  240. // mask settings
  241. decryptedSettings = encryption.MaskConfigCredentials(decryptedSettings, pluginDeclaration.Endpoint.Settings)
  242. endpoint.Settings = decryptedSettings
  243. endpoint.Declaration = pluginDeclaration.Endpoint
  244. endpoints[i] = endpoint
  245. }
  246. return entities.NewSuccessResponse(endpoints)
  247. }
  248. func ListPluginEndpoints(tenant_id string, plugin_id string, page int, page_size int) *entities.Response {
  249. endpoints, err := db.GetAll[models.Endpoint](
  250. db.Equal("plugin_id", plugin_id),
  251. db.Equal("tenant_id", tenant_id),
  252. db.OrderBy("created_at", true),
  253. db.Page(page, page_size),
  254. )
  255. if err != nil {
  256. return exception.InternalServerError(
  257. fmt.Errorf("failed to list endpoints: %v", err),
  258. ).ToResponse()
  259. }
  260. manager := plugin_manager.Manager()
  261. if manager == nil {
  262. return exception.InternalServerError(
  263. errors.New("failed to get plugin manager"),
  264. ).ToResponse()
  265. }
  266. // decrypt settings
  267. for i, endpoint := range endpoints {
  268. // get installation
  269. pluginInstallation, err := db.GetOne[models.PluginInstallation](
  270. db.Equal("plugin_id", plugin_id),
  271. db.Equal("tenant_id", tenant_id),
  272. )
  273. if err != nil {
  274. return exception.NotFoundError(
  275. fmt.Errorf("failed to find plugin installation: %v", err),
  276. ).ToResponse()
  277. }
  278. pluginUniqueIdentifier, err := plugin_entities.NewPluginUniqueIdentifier(
  279. pluginInstallation.PluginUniqueIdentifier,
  280. )
  281. if err != nil {
  282. return exception.PluginUniqueIdentifierError(
  283. fmt.Errorf("failed to parse plugin unique identifier: %v", err),
  284. ).ToResponse()
  285. }
  286. pluginDeclaration, err := manager.GetDeclaration(
  287. pluginUniqueIdentifier,
  288. tenant_id,
  289. plugin_entities.PluginRuntimeType(pluginInstallation.RuntimeType),
  290. )
  291. if err != nil {
  292. return exception.InternalServerError(
  293. fmt.Errorf("failed to get plugin declaration: %v", err),
  294. ).ToResponse()
  295. }
  296. decryptedSettings, err := manager.BackwardsInvocation().InvokeEncrypt(&dify_invocation.InvokeEncryptRequest{
  297. BaseInvokeDifyRequest: dify_invocation.BaseInvokeDifyRequest{
  298. TenantId: tenant_id,
  299. UserId: "",
  300. Type: dify_invocation.INVOKE_TYPE_ENCRYPT,
  301. },
  302. InvokeEncryptSchema: dify_invocation.InvokeEncryptSchema{
  303. Opt: dify_invocation.ENCRYPT_OPT_DECRYPT,
  304. Namespace: dify_invocation.ENCRYPT_NAMESPACE_ENDPOINT,
  305. Identity: endpoint.ID,
  306. Data: endpoint.Settings,
  307. Config: pluginDeclaration.Endpoint.Settings,
  308. },
  309. })
  310. if err != nil {
  311. return exception.InternalServerError(
  312. fmt.Errorf("failed to decrypt settings: %v", err),
  313. ).ToResponse()
  314. }
  315. // mask settings
  316. decryptedSettings = encryption.MaskConfigCredentials(decryptedSettings, pluginDeclaration.Endpoint.Settings)
  317. endpoint.Settings = decryptedSettings
  318. endpoint.Declaration = pluginDeclaration.Endpoint
  319. endpoints[i] = endpoint
  320. }
  321. return entities.NewSuccessResponse(endpoints)
  322. }