record.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. isStatic := boolToInt64(req.IsStatic)
  146. record, err := h.q.UpdateRecord(ctx, queries.UpdateRecordParams{
  147. ID: id,
  148. Name: req.Name,
  149. Type: req.Type,
  150. Content: req.Content,
  151. Proxied: boolToInt64(req.Proxied),
  152. IsStatic: isStatic,
  153. Column6: isStatic,
  154. })
  155. if errors.Is(err, sql.ErrNoRows) {
  156. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  157. }
  158. if err != nil {
  159. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  160. }
  161. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  162. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  163. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  164. }
  165. return c.JSON(http.StatusOK, record)
  166. }
  167. func (h *RecordHandler) Delete(c echo.Context) error {
  168. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  169. if err != nil {
  170. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  171. }
  172. if err := h.q.DeleteRecord(c.Request().Context(), id); err != nil {
  173. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to delete record"})
  174. }
  175. return c.JSON(http.StatusOK, map[string]string{"message": "record deleted"})
  176. }
  177. type partialRecordRequest struct {
  178. Name *string `json:"name"`
  179. Type *string `json:"type"`
  180. Content *string `json:"content"`
  181. Proxied *bool `json:"proxied"`
  182. IsStatic *bool `json:"is_static"`
  183. }
  184. func (h *RecordHandler) PartialUpdate(c echo.Context) error {
  185. id, err := strconv.ParseInt(c.Param("id"), 10, 64)
  186. if err != nil {
  187. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid id"})
  188. }
  189. var req partialRecordRequest
  190. if err := c.Bind(&req); err != nil {
  191. return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})
  192. }
  193. ctx := c.Request().Context()
  194. existing, err := h.q.GetRecord(ctx, id)
  195. if errors.Is(err, sql.ErrNoRows) {
  196. return c.JSON(http.StatusNotFound, map[string]string{"error": "record not found"})
  197. }
  198. if err != nil {
  199. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to get record"})
  200. }
  201. params := queries.UpdateRecordParams{
  202. ID: id,
  203. Name: existing.Name,
  204. Type: existing.Type,
  205. Content: existing.Content,
  206. Proxied: existing.Proxied,
  207. IsStatic: existing.IsStatic,
  208. }
  209. if req.Name != nil {
  210. params.Name = *req.Name
  211. }
  212. if req.Type != nil {
  213. params.Type = *req.Type
  214. }
  215. if req.Content != nil {
  216. params.Content = *req.Content
  217. }
  218. if req.Proxied != nil {
  219. params.Proxied = boolToInt64(*req.Proxied)
  220. }
  221. if req.IsStatic != nil {
  222. params.IsStatic = boolToInt64(*req.IsStatic)
  223. }
  224. params.Column6 = params.IsStatic
  225. record, err := h.q.UpdateRecord(ctx, params)
  226. if err != nil {
  227. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update record"})
  228. }
  229. if err := h.pushRecordToCloudflare(ctx, record); err != nil {
  230. slog.Error("failed to update record on Cloudflare", "record_id", record.ID, "error", err)
  231. return c.JSON(http.StatusBadGateway, map[string]string{"error": "record updated locally but failed to update on Cloudflare: " + err.Error()})
  232. }
  233. return c.JSON(http.StatusOK, record)
  234. }
  235. func (h *RecordHandler) Sync(c echo.Context) error {
  236. ctx := c.Request().Context()
  237. zones, err := h.q.ListZones(ctx)
  238. if err != nil {
  239. return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list zones"})
  240. }
  241. var synced int
  242. for _, zone := range zones {
  243. cfRecords, err := cf.ListDNSRecords(ctx, zone.ApiKey, zone.ZoneID)
  244. if err != nil {
  245. slog.Error("failed to fetch CF records", "zone", zone.Name, "error", err)
  246. continue
  247. }
  248. cfIDs := make(map[string]struct{}, len(cfRecords))
  249. for _, rec := range cfRecords {
  250. cfIDs[rec.ID] = struct{}{}
  251. var proxied int64
  252. if rec.Proxied {
  253. proxied = 1
  254. }
  255. _, err := h.q.UpsertRecord(ctx, queries.UpsertRecordParams{
  256. ZoneID: zone.ID,
  257. CfRecordID: rec.ID,
  258. Name: rec.Name,
  259. Type: rec.Type,
  260. Content: rec.Content,
  261. Proxied: proxied,
  262. IsStatic: 1,
  263. })
  264. if err != nil {
  265. slog.Error("failed to upsert record", "name", rec.Name, "error", err)
  266. continue
  267. }
  268. synced++
  269. }
  270. localIDs, err := h.q.ListRecordCfIDsByZone(ctx, zone.ID)
  271. if err != nil {
  272. slog.Error("failed to list local record IDs", "zone", zone.Name, "error", err)
  273. continue
  274. }
  275. for _, localID := range localIDs {
  276. if _, exists := cfIDs[localID]; !exists {
  277. _ = h.q.DeleteRecordByCfID(ctx, queries.DeleteRecordByCfIDParams{
  278. ZoneID: zone.ID,
  279. CfRecordID: localID,
  280. })
  281. }
  282. }
  283. }
  284. return c.JSON(http.StatusOK, map[string]int{"synced": synced})
  285. }