endpoint.go 11 KB

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