app_notifications.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package porter_app
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/server/authz"
  6. "github.com/porter-dev/porter/api/server/shared/requestutils"
  7. "connectrpc.com/connect"
  8. porterv1 "github.com/porter-dev/api-contracts/generated/go/porter/v1"
  9. "github.com/google/uuid"
  10. "github.com/porter-dev/porter/internal/porter_app"
  11. "github.com/porter-dev/porter/internal/porter_app/notifications"
  12. "github.com/porter-dev/porter/internal/repository"
  13. "github.com/porter-dev/porter/internal/telemetry"
  14. "github.com/porter-dev/porter/api/server/handlers"
  15. "github.com/porter-dev/porter/api/server/shared"
  16. "github.com/porter-dev/porter/api/server/shared/apierrors"
  17. "github.com/porter-dev/porter/api/server/shared/config"
  18. "github.com/porter-dev/porter/api/types"
  19. "github.com/porter-dev/porter/internal/models"
  20. )
  21. // AppNotificationsHandler handles requests to the /apps/{porter_app_name}/notifications endpoint
  22. type AppNotificationsHandler struct {
  23. handlers.PorterHandlerReadWriter
  24. authz.KubernetesAgentGetter
  25. }
  26. // NewAppNotificationsHandler returns a new AppNotificationsHandler
  27. func NewAppNotificationsHandler(
  28. config *config.Config,
  29. decoderValidator shared.RequestDecoderValidator,
  30. writer shared.ResultWriter,
  31. ) *AppNotificationsHandler {
  32. return &AppNotificationsHandler{
  33. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  34. KubernetesAgentGetter: authz.NewOutOfClusterAgentGetter(config),
  35. }
  36. }
  37. // AppNotificationsRequest is the request object for the /apps/{porter_app_name}/notifications endpoint
  38. type AppNotificationsRequest struct {
  39. DeploymentTargetID string `schema:"deployment_target_id"`
  40. }
  41. // AppNotificationsResponse is the response object for the /apps/{porter_app_name}/notifications endpoint
  42. type AppNotificationsResponse struct {
  43. // Notifications are the notifications associated with the app revision
  44. Notifications []notifications.Notification `json:"notifications"`
  45. }
  46. func (c *AppNotificationsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  47. ctx, span := telemetry.NewSpan(r.Context(), "serve-app-notifications")
  48. defer span.End()
  49. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  50. appName, reqErr := requestutils.GetURLParamString(r, types.URLParamPorterAppName)
  51. if reqErr != nil {
  52. e := telemetry.Error(ctx, span, reqErr, "error parsing stack name from url")
  53. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(e, http.StatusBadRequest))
  54. return
  55. }
  56. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "app-name", Value: appName})
  57. request := &AppNotificationsRequest{}
  58. if ok := c.DecodeAndValidate(w, r, request); !ok {
  59. err := telemetry.Error(ctx, span, nil, "error decoding request")
  60. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  61. return
  62. }
  63. _, err := uuid.Parse(request.DeploymentTargetID)
  64. if err != nil {
  65. err := telemetry.Error(ctx, span, err, "error parsing deployment target id")
  66. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusBadRequest))
  67. return
  68. }
  69. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "deployment-target-id", Value: request.DeploymentTargetID})
  70. listAppRevisionsReq := connect.NewRequest(&porterv1.ListAppRevisionsRequest{
  71. ProjectId: int64(project.ID),
  72. DeploymentTargetIdentifier: &porterv1.DeploymentTargetIdentifier{Id: request.DeploymentTargetID},
  73. AppName: appName,
  74. })
  75. listAppRevisionsResp, err := c.Config().ClusterControlPlaneClient.ListAppRevisions(ctx, listAppRevisionsReq)
  76. if err != nil {
  77. err = telemetry.Error(ctx, span, err, "error listing app revisions")
  78. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  79. return
  80. }
  81. if listAppRevisionsResp == nil || listAppRevisionsResp.Msg == nil {
  82. err = telemetry.Error(ctx, span, nil, "list app revisions response is nil")
  83. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  84. return
  85. }
  86. appRevisionsList := listAppRevisionsResp.Msg.AppRevisions
  87. latestNotifications := make([]notifications.Notification, 0)
  88. encodedRevisions := make([]porter_app.Revision, 0)
  89. if len(appRevisionsList) > 0 {
  90. encodedRevision, err := porter_app.EncodedRevisionFromProto(ctx, appRevisionsList[0])
  91. if err != nil {
  92. err := telemetry.Error(ctx, span, err, "error getting encoded revision from proto")
  93. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  94. return
  95. }
  96. encodedRevisions = append(encodedRevisions, encodedRevision)
  97. // encode the penultimate revision as well in case it is a rollback
  98. if len(appRevisionsList) > 1 {
  99. penultimateRevision, err := porter_app.EncodedRevisionFromProto(ctx, appRevisionsList[1])
  100. if err != nil {
  101. err := telemetry.Error(ctx, span, err, "error getting encoded revision from proto")
  102. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  103. return
  104. }
  105. encodedRevisions = append(encodedRevisions, penultimateRevision)
  106. }
  107. }
  108. if len(encodedRevisions) > 0 {
  109. latestNotifications, err = notificationsForRevision(ctx, notificationsForRevisionInput{
  110. Revision: encodedRevisions[0],
  111. PorterAppEventRepository: c.Repo().PorterAppEvent(),
  112. })
  113. if err != nil {
  114. err := telemetry.Error(ctx, span, err, "error getting notifications for revision")
  115. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  116. return
  117. }
  118. // if the penultimate revision is a rollback, get the notifications for that revision as well so we can show the user why the rollback happened
  119. if len(encodedRevisions) > 1 && encodedRevisions[1].Status == models.AppRevisionStatus_RollbackSuccessful {
  120. rollbackNotifications, err := notificationsForRevision(ctx, notificationsForRevisionInput{
  121. Revision: encodedRevisions[1],
  122. PorterAppEventRepository: c.Repo().PorterAppEvent(),
  123. })
  124. if err != nil {
  125. err := telemetry.Error(ctx, span, err, "error getting notifications for rollback revision")
  126. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(err, http.StatusInternalServerError))
  127. return
  128. }
  129. latestNotifications = append(latestNotifications, rollbackNotifications...)
  130. }
  131. }
  132. response := AppNotificationsResponse{
  133. Notifications: latestNotifications,
  134. }
  135. c.WriteResult(w, r, response)
  136. }
  137. type notificationsForRevisionInput struct {
  138. Revision porter_app.Revision
  139. PorterAppEventRepository repository.PorterAppEventRepository
  140. }
  141. func notificationsForRevision(ctx context.Context, inp notificationsForRevisionInput) ([]notifications.Notification, error) {
  142. ctx, span := telemetry.NewSpan(ctx, "notifications-for-revision")
  143. defer span.End()
  144. telemetry.WithAttributes(span,
  145. telemetry.AttributeKV{Key: "app-revision-id", Value: inp.Revision.ID},
  146. telemetry.AttributeKV{Key: "app-instance-id", Value: inp.Revision.AppInstanceID},
  147. )
  148. notificationList := make([]notifications.Notification, 0)
  149. if inp.Revision.ID == "" {
  150. return notificationList, telemetry.Error(ctx, span, nil, "app revision id is missing")
  151. }
  152. if inp.Revision.AppInstanceID == uuid.Nil {
  153. return notificationList, telemetry.Error(ctx, span, nil, "app instance id is missing")
  154. }
  155. appRevisionId := inp.Revision.ID
  156. appInstanceId := inp.Revision.AppInstanceID
  157. notificationEvents, err := inp.PorterAppEventRepository.ReadNotificationsByAppRevisionID(ctx, appInstanceId, appRevisionId)
  158. if err != nil {
  159. return notificationList, telemetry.Error(ctx, span, err, "error getting notifications from repo")
  160. }
  161. for _, event := range notificationEvents {
  162. notification, err := notifications.NotificationFromPorterAppEvent(event)
  163. if err != nil {
  164. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: err.Error()})
  165. continue
  166. }
  167. if notification == nil {
  168. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: "notification is nil"})
  169. continue
  170. }
  171. // TODO: remove this check once this attribute is not found in the span for >30 days
  172. if notification.Scope == "" {
  173. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "notification-conversion-error", Value: "old-notification-format"})
  174. continue
  175. }
  176. notificationList = append(notificationList, *notification)
  177. }
  178. return notificationList, nil
  179. }