record.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package handler
  2. import (
  3. "context"
  4. "database/sql"
  5. "errors"
  6. "log/slog"
  7. "net/http"
  8. "strconv"
  9. cf "goflare/internal/cloudflare"
  10. "goflare/internal/database/queries"
  11. "github.com/labstack/echo/v4"
  12. )
  13. type RecordHandler struct {
  14. q *queries.Queries
  15. }
  16. func NewRecordHandler(q *queries.Queries) *RecordHandler {
  17. return &RecordHandler{q: q}
  18. }
  19. type recordRequest struct {
  20. ZoneID int64 `json:"zone_id"`
  21. CfRecordID string `json:"cf_record_id"`
  22. Name string `json:"name"`
  23. Type string `json:"type"`
  24. Content string `json:"content"`
  25. Proxied bool `json:"proxied"`
  26. IsStatic bool `json:"is_static"`
  27. }
  28. func boolToInt64(b bool) int64 {
  29. if b {
  30. return 1
  31. }
  32. return 0
  33. }
  34. // pushRecordToCloudflare updates the DNS record on Cloudflare to match the local record.
  35. func (h *RecordHandler) pushRecordToCloudflare(ctx context.Context, record queries.Record) error {
  36. zone, err := h.q.GetZone(ctx, record.ZoneID)
  37. if err != nil {
  38. return err
  39. }
  40. return cf.UpdateDNSRecord(ctx, zone.ApiKey, zone.ZoneID, record.CfRecordID, cf.DNSRecord{
  41. Type: record.Type,
  42. Name: record.Name,
  43. Content: record.Content,
  44. Proxied: record.Proxied == 1,
  45. TTL: 1, // auto
  46. })
  47. }
  48. func (h *RecordHandler) List(c echo.Context) error {
  49. zoneIDStr := c.QueryParam("zone_id")
  50. if zoneIDStr != "" {
  51. zoneID, err := strconv.ParseInt(zoneIDStr, 10, 64)
  52. if err != nil {
  53. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid zone_id"})
  54. }
  55. records, err := h.q.ListRecordsByZone(c.Request().Context(), zoneID)
  56. if err != nil {
  57. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list records"})
  58. }
  59. if records == nil {
  60. records = []queries.ListRecordsByZoneRow{}
  61. }
  62. return c.JSON(http.StatusOK, records)
  63. }
  64. records, err := h.q.ListRecords(c.Request().Context())
  65. if err != nil {
  66. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list records"})
  67. }
  68. if records == nil {
  69. records = []queries.ListRecordsRow{}
  70. }
  71. return c.JSON(http.StatusOK, records)
  72. }
  73. func (h *RecordHandler) Get(c echo.Context) error {
  74. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  75. if err != nil {
  76. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  77. }
  78. record, err := h.q.GetRecord(c.Request().Context(), id)
  79. if errors.Is(err, sql.ErrNoRows) {
  80. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  81. }
  82. if err != nil {
  83. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to get record"})
  84. }
  85. return c.JSON(http.StatusOK, record)
  86. }
  87. func (h *RecordHandler) Create(c echo.Context) error {
  88. var req recordRequest
  89. if err := c.Bind(&req); err != nil {
  90. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  91. }
  92. if req.ZoneID == 0 || req.CfRecordID == "" || req.Name == "" || req.Content == "" {
  93. return c.JSON(http.StatusBadRequest, map[string]string{"error": "zone_id, cf_record_id, name, and content required"})
  94. }
  95. if req.Type == "" {
  96. req.Type = "A"
  97. }
  98. record, err := h.q.CreateRecord(c.Request().Context(), queries.CreateRecordParams{
  99. ZoneID: req.ZoneID,
  100. CfRecordID: req.CfRecordID,
  101. Name: req.Name,
  102. Type: req.Type,
  103. Content: req.Content,
  104. Proxied: boolToInt64(req.Proxied),
  105. IsStatic: boolToInt64(req.IsStatic),
  106. })
  107. if err != nil {
  108. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create record"})
  109. }
  110. return c.JSON(http.StatusCreated, record)
  111. }
  112. func (h *RecordHandler) Update(c echo.Context) error {
  113. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  114. if err != nil {
  115. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  116. }
  117. var req recordRequest
  118. if err := c.Bind(&req); err != nil {
  119. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  120. }
  121. if req.Name == "" || req.Content == "" {
  122. return c.JSON(http.StatusBadRequest, map[string]string{"error": "name and content required"})
  123. }
  124. if req.Type == "" {
  125. req.Type = "A"
  126. }
  127. ctx := c.Request().Context()
  128. record, err := h.q.UpdateRecord(ctx, queries.UpdateRecordParams{
  129. ID: id,
  130. Name: req.Name,
  131. Type: req.Type,
  132. Content: req.Content,
  133. Proxied: boolToInt64(req.Proxied),
  134. IsStatic: boolToInt64(req.IsStatic),
  135. })
  136. if errors.Is(err, sql.ErrNoRows) {
  137. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  138. }
  139. if err != nil {
  140. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  141. }
  142. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  143. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  144. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  145. }
  146. return c.JSON(http.StatusOK, record)
  147. }
  148. func (h *RecordHandler) Delete(c echo.Context) error {
  149. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  150. if err != nil {
  151. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  152. }
  153. if err := h.q.DeleteRecord(c.Request().Context(), id); err != nil {
  154. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to delete record"})
  155. }
  156. return c.JSON(http.StatusOK, map[string]string{"message": "record deleted"})
  157. }
  158. type partialRecordRequest struct {
  159. Name *string `json:"name"`
  160. Type *string `json:"type"`
  161. Content *string `json:"content"`
  162. Proxied *bool `json:"proxied"`
  163. IsStatic *bool `json:"is_static"`
  164. }
  165. func (h *RecordHandler) PartialUpdate(c echo.Context) error {
  166. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  167. if err != nil {
  168. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  169. }
  170. var req partialRecordRequest
  171. if err := c.Bind(&req); err != nil {
  172. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  173. }
  174. ctx := c.Request().Context()
  175. existing, err := h.q.GetRecord(ctx, id)
  176. if errors.Is(err, sql.ErrNoRows) {
  177. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  178. }
  179. if err != nil {
  180. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to get record"})
  181. }
  182. params := queries.UpdateRecordParams{
  183. ID: id,
  184. Name: existing.Name,
  185. Type: existing.Type,
  186. Content: existing.Content,
  187. Proxied: existing.Proxied,
  188. IsStatic: existing.IsStatic,
  189. }
  190. if req.Name != nil {
  191. params.Name = *req.Name
  192. }
  193. if req.Type != nil {
  194. params.Type = *req.Type
  195. }
  196. if req.Content != nil {
  197. params.Content = *req.Content
  198. }
  199. if req.Proxied != nil {
  200. params.Proxied = boolToInt64(*req.Proxied)
  201. }
  202. if req.IsStatic != nil {
  203. params.IsStatic = boolToInt64(*req.IsStatic)
  204. }
  205. record, err := h.q.UpdateRecord(ctx, params)
  206. if err != nil {
  207. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  208. }
  209. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  210. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  211. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  212. }
  213. return c.JSON(http.StatusOK, record)
  214. }
  215. func (h *RecordHandler) Sync(c echo.Context) error {
  216. ctx := c.Request().Context()
  217. zones, err := h.q.ListZones(ctx)
  218. if err != nil {
  219. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list zones"})
  220. }
  221. var synced int
  222. for _, zone := range zones {
  223. cfRecords, err := cf.ListDNSRecords(ctx, zone.ApiKey, zone.ZoneID)
  224. if err != nil {
  225. slog.Error("failed to fetch CF records", "zone", zone.Name, "error", err)
  226. continue
  227. }
  228. cfIDs := make(map[string]struct{}, len(cfRecords))
  229. for _, rec := range cfRecords {
  230. cfIDs[rec.ID] = struct{}{}
  231. var proxied int64
  232. if rec.Proxied {
  233. proxied = 1
  234. }
  235. _, err := h.q.UpsertRecord(ctx, queries.UpsertRecordParams{
  236. ZoneID: zone.ID,
  237. CfRecordID: rec.ID,
  238. Name: rec.Name,
  239. Type: rec.Type,
  240. Content: rec.Content,
  241. Proxied: proxied,
  242. IsStatic: 1,
  243. })
  244. if err != nil {
  245. slog.Error("failed to upsert record", "name", rec.Name, "error", err)
  246. continue
  247. }
  248. synced++
  249. }
  250. localIDs, err := h.q.ListRecordCfIDsByZone(ctx, zone.ID)
  251. if err != nil {
  252. slog.Error("failed to list local record IDs", "zone", zone.Name, "error", err)
  253. continue
  254. }
  255. for _, localID := range localIDs {
  256. if _, exists := cfIDs[localID]; !exists {
  257. _ = h.q.DeleteRecordByCfID(ctx, queries.DeleteRecordByCfIDParams{
  258. ZoneID: zone.ID,
  259. CfRecordID: localID,
  260. })
  261. }
  262. }
  263. }
  264. return c.JSON(http.StatusOK, map[string]int{"synced": synced})
  265. }