record.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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.Name == "" || req.Content == "" {
  93. return c.JSON(http.StatusBadRequest, map[string]string{"error": "zone_id, name, and content required"})
  94. }
  95. if req.Type == "" {
  96. req.Type = "A"
  97. }
  98. ctx := c.Request().Context()
  99. zone, err := h.q.GetZone(ctx, req.ZoneID)
  100. if errors.Is(err, sql.ErrNoRows) {
  101. return c.JSON(http.StatusBadRequest, map[string]string{"error": "zone not found"})
  102. }
  103. if err != nil {
  104. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to get zone"})
  105. }
  106. cfRecord, err := cf.CreateDNSRecord(ctx, zone.ApiKey, zone.ZoneID, cf.DNSRecord{
  107. Type: req.Type,
  108. Name: req.Name,
  109. Content: req.Content,
  110. Proxied: req.Proxied,
  111. })
  112. if err != nil {
  113. return c.JSON(http.StatusBadGateway, map[string]string{"error": "failed to create record on Cloudflare: " + err.Error()})
  114. }
  115. record, err := h.q.CreateRecord(ctx, queries.CreateRecordParams{
  116. ZoneID: req.ZoneID,
  117. CfRecordID: cfRecord.ID,
  118. Name: req.Name,
  119. Type: req.Type,
  120. Content: req.Content,
  121. Proxied: boolToInt64(req.Proxied),
  122. IsStatic: boolToInt64(req.IsStatic),
  123. })
  124. if err != nil {
  125. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create record"})
  126. }
  127. return c.JSON(http.StatusCreated, record)
  128. }
  129. func (h *RecordHandler) Update(c echo.Context) error {
  130. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  131. if err != nil {
  132. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  133. }
  134. var req recordRequest
  135. if err := c.Bind(&req); err != nil {
  136. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  137. }
  138. if req.Name == "" || req.Content == "" {
  139. return c.JSON(http.StatusBadRequest, map[string]string{"error": "name and content required"})
  140. }
  141. if req.Type == "" {
  142. req.Type = "A"
  143. }
  144. ctx := c.Request().Context()
  145. record, err := h.q.UpdateRecord(ctx, queries.UpdateRecordParams{
  146. ID: id,
  147. Name: req.Name,
  148. Type: req.Type,
  149. Content: req.Content,
  150. Proxied: boolToInt64(req.Proxied),
  151. IsStatic: boolToInt64(req.IsStatic),
  152. })
  153. if errors.Is(err, sql.ErrNoRows) {
  154. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  155. }
  156. if err != nil {
  157. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  158. }
  159. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  160. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  161. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  162. }
  163. return c.JSON(http.StatusOK, record)
  164. }
  165. func (h *RecordHandler) Delete(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. if err := h.q.DeleteRecord(c.Request().Context(), id); err != nil {
  171. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to delete record"})
  172. }
  173. return c.JSON(http.StatusOK, map[string]string{"message": "record deleted"})
  174. }
  175. type partialRecordRequest struct {
  176. Name *string `json:"name"`
  177. Type *string `json:"type"`
  178. Content *string `json:"content"`
  179. Proxied *bool `json:"proxied"`
  180. IsStatic *bool `json:"is_static"`
  181. }
  182. func (h *RecordHandler) PartialUpdate(c echo.Context) error {
  183. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  184. if err != nil {
  185. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  186. }
  187. var req partialRecordRequest
  188. if err := c.Bind(&req); err != nil {
  189. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  190. }
  191. ctx := c.Request().Context()
  192. existing, err := h.q.GetRecord(ctx, id)
  193. if errors.Is(err, sql.ErrNoRows) {
  194. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  195. }
  196. if err != nil {
  197. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to get record"})
  198. }
  199. params := queries.UpdateRecordParams{
  200. ID: id,
  201. Name: existing.Name,
  202. Type: existing.Type,
  203. Content: existing.Content,
  204. Proxied: existing.Proxied,
  205. IsStatic: existing.IsStatic,
  206. }
  207. if req.Name != nil {
  208. params.Name = *req.Name
  209. }
  210. if req.Type != nil {
  211. params.Type = *req.Type
  212. }
  213. if req.Content != nil {
  214. params.Content = *req.Content
  215. }
  216. if req.Proxied != nil {
  217. params.Proxied = boolToInt64(*req.Proxied)
  218. }
  219. if req.IsStatic != nil {
  220. params.IsStatic = boolToInt64(*req.IsStatic)
  221. }
  222. record, err := h.q.UpdateRecord(ctx, params)
  223. if err != nil {
  224. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  225. }
  226. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  227. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  228. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  229. }
  230. return c.JSON(http.StatusOK, record)
  231. }
  232. func (h *RecordHandler) Sync(c echo.Context) error {
  233. ctx := c.Request().Context()
  234. zones, err := h.q.ListZones(ctx)
  235. if err != nil {
  236. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list zones"})
  237. }
  238. var synced int
  239. for _, zone := range zones {
  240. cfRecords, err := cf.ListDNSRecords(ctx, zone.ApiKey, zone.ZoneID)
  241. if err != nil {
  242. slog.Error("failed to fetch CF records", "zone", zone.Name, "error", err)
  243. continue
  244. }
  245. cfIDs := make(map[string]struct{}, len(cfRecords))
  246. for _, rec := range cfRecords {
  247. cfIDs[rec.ID] = struct{}{}
  248. var proxied int64
  249. if rec.Proxied {
  250. proxied = 1
  251. }
  252. _, err := h.q.UpsertRecord(ctx, queries.UpsertRecordParams{
  253. ZoneID: zone.ID,
  254. CfRecordID: rec.ID,
  255. Name: rec.Name,
  256. Type: rec.Type,
  257. Content: rec.Content,
  258. Proxied: proxied,
  259. IsStatic: 1,
  260. })
  261. if err != nil {
  262. slog.Error("failed to upsert record", "name", rec.Name, "error", err)
  263. continue
  264. }
  265. synced++
  266. }
  267. localIDs, err := h.q.ListRecordCfIDsByZone(ctx, zone.ID)
  268. if err != nil {
  269. slog.Error("failed to list local record IDs", "zone", zone.Name, "error", err)
  270. continue
  271. }
  272. for _, localID := range localIDs {
  273. if _, exists := cfIDs[localID]; !exists {
  274. _ = h.q.DeleteRecordByCfID(ctx, queries.DeleteRecordByCfIDParams{
  275. ZoneID: zone.ID,
  276. CfRecordID: localID,
  277. })
  278. }
  279. }
  280. }
  281. return c.JSON(http.StatusOK, map[string]int{"synced": synced})
  282. }