diff --git a/bun.lock b/bun.lock index ae1cabe..ac63678 100644 --- a/bun.lock +++ b/bun.lock @@ -9,6 +9,7 @@ "@fastify/jwt": "^10.0.0", "@fastify/static": "^9.0.0", "fastify": "^5.8.4", + "ioredis": "^5.10.1", "postgres": "^3.4.8", "zod": "^4.3.6", }, @@ -44,6 +45,8 @@ "@fastify/static": ["@fastify/static@9.0.0", "", { "dependencies": { "@fastify/accept-negotiator": "^2.0.0", "@fastify/send": "^4.0.0", "content-disposition": "^1.0.1", "fastify-plugin": "^5.0.0", "fastq": "^1.17.1", "glob": "^13.0.0" } }, "sha512-r64H8Woe/vfilg5RTy7lwWlE8ZZcTrc3kebYFMEUBrMqlydhQyoiExQXdYAy2REVpST/G35+stAM8WYp1WGmMA=="], + "@ioredis/commands": ["@ioredis/commands@1.5.1", "", {}, "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw=="], + "@lukeed/ms": ["@lukeed/ms@2.0.2", "", {}, "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA=="], "@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="], @@ -72,10 +75,16 @@ "bun-types": ["bun-types@1.3.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="], + "cluster-key-slot": ["cluster-key-slot@1.1.2", "", {}, "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA=="], + "content-disposition": ["content-disposition@1.0.1", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="], "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="], + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], @@ -116,6 +125,8 @@ "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + "ioredis": ["ioredis@5.10.1", "", { "dependencies": { "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", "lodash.defaults": "^4.2.0", "lodash.isarguments": "^3.1.0", "redis-errors": "^1.2.0", "redis-parser": "^3.0.0", "standard-as-callback": "^2.1.0" } }, "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA=="], + "ipaddr.js": ["ipaddr.js@2.3.0", "", {}, "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg=="], "json-schema-ref-resolver": ["json-schema-ref-resolver@3.0.0", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A=="], @@ -124,6 +135,10 @@ "light-my-request": ["light-my-request@6.6.0", "", { "dependencies": { "cookie": "^1.0.1", "process-warning": "^4.0.0", "set-cookie-parser": "^2.6.0" } }, "sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A=="], + "lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="], + + "lodash.isarguments": ["lodash.isarguments@3.1.0", "", {}, "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg=="], + "lru-cache": ["lru-cache@11.2.7", "", {}, "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA=="], "mime": ["mime@3.0.0", "", { "bin": { "mime": "cli.js" } }, "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A=="], @@ -136,6 +151,8 @@ "mnemonist": ["mnemonist@0.40.3", "", { "dependencies": { "obliterator": "^2.0.4" } }, "sha512-Vjyr90sJ23CKKH/qPAgUKicw/v6pRoamxIEDFOF8uSgFME7DqPRpHgRTejWVjkdGg5dXj0/NyxZHZ9bcjH+2uQ=="], + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "obliterator": ["obliterator@2.0.5", "", {}, "sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw=="], "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], @@ -156,6 +173,10 @@ "real-require": ["real-require@0.2.0", "", {}, "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg=="], + "redis-errors": ["redis-errors@1.2.0", "", {}, "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w=="], + + "redis-parser": ["redis-parser@3.0.0", "", { "dependencies": { "redis-errors": "^1.0.0" } }, "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], "ret": ["ret@0.5.0", "", {}, "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw=="], @@ -184,6 +205,8 @@ "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], + "standard-as-callback": ["standard-as-callback@2.1.0", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="], + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], "steed": ["steed@1.1.3", "", { "dependencies": { "fastfall": "^1.5.0", "fastparallel": "^2.2.0", "fastq": "^1.3.0", "fastseries": "^1.7.0", "reusify": "^1.0.0" } }, "sha512-EUkci0FAUiE4IvGTSKcDJIQ/eRUP2JJb56+fvZ4sdnguLTqIdKjSxUe138poW8mkvKWXW2sFPrgTsxqoISnmoA=="], diff --git a/frontend/index.html b/frontend/index.html index b1114b8..b40ec5a 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -9,20 +9,8 @@ body { font-family: "Inter", system-ui, sans-serif; background: #0d1117; color: #c9d1d9; min-height: 100vh; } /* ── Login ── */ - #login-view { - display: none; - min-height: 100vh; - align-items: center; - justify-content: center; - } - .login-box { - background: #161b22; - border: 1px solid #30363d; - border-radius: 10px; - padding: 2.5rem; - width: 100%; - max-width: 360px; - } + #login-view { display: none; min-height: 100vh; align-items: center; justify-content: center; } + .login-box { background: #161b22; border: 1px solid #30363d; border-radius: 10px; padding: 2.5rem; width: 100%; max-width: 360px; } .login-box h1 { font-size: 1.1rem; color: #e6edf3; margin-bottom: 0.3rem; font-weight: 600; } .login-box p { font-size: 0.82rem; color: #8b949e; margin-bottom: 1.8rem; } @@ -31,77 +19,22 @@ .shell { display: flex; height: 100%; } /* ── Sidebar ── */ - .sidebar { - width: 220px; - background: #13161f; - border-right: 1px solid #21262d; - display: flex; - flex-direction: column; - flex-shrink: 0; - } - .sidebar-brand { - padding: 1.2rem 1.2rem 1rem; - font-size: 0.88rem; - font-weight: 700; - color: #e6edf3; - letter-spacing: 0.06em; - text-transform: uppercase; - border-bottom: 1px solid #21262d; - } + .sidebar { width: 220px; background: #13161f; border-right: 1px solid #21262d; display: flex; flex-direction: column; flex-shrink: 0; } + .sidebar-brand { padding: 1.2rem 1.2rem 1rem; font-size: 0.88rem; font-weight: 700; color: #e6edf3; letter-spacing: 0.06em; text-transform: uppercase; border-bottom: 1px solid #21262d; } .sidebar-nav { flex: 1; padding: 0.6rem 0.5rem; } - .nav-item { - display: flex; - align-items: center; - gap: 0.65rem; - padding: 0.55rem 0.8rem; - border-radius: 6px; - font-size: 0.845rem; - color: #8b949e; - cursor: pointer; - transition: background 0.12s, color 0.12s; - user-select: none; - } + .nav-item { display: flex; align-items: center; gap: 0.65rem; padding: 0.55rem 0.8rem; border-radius: 6px; font-size: 0.845rem; color: #8b949e; cursor: pointer; transition: background 0.12s, color 0.12s; user-select: none; } .nav-item:hover { background: #1c2128; color: #c9d1d9; } .nav-item.active { background: #1c2128; color: #e6edf3; } .nav-icon { font-size: 0.9rem; width: 1.1rem; text-align: center; opacity: 0.7; } - .sidebar-user { padding: 0.7rem; border-top: 1px solid #21262d; } - .user-btn { - display: flex; - align-items: center; - gap: 0.65rem; - padding: 0.55rem 0.8rem; - border-radius: 6px; - cursor: pointer; - transition: background 0.12s; - width: 100%; - background: none; - border: none; - color: #8b949e; - text-align: left; - } + .user-btn { display: flex; align-items: center; gap: 0.65rem; padding: 0.55rem 0.8rem; border-radius: 6px; cursor: pointer; transition: background 0.12s; width: 100%; background: none; border: none; color: #8b949e; text-align: left; } .user-btn:hover { background: #1c2128; color: #c9d1d9; } .user-menu { display: none; flex-direction: column; gap: 1px; padding: 0 0.5rem 0.3rem; } .user-menu.open { display: flex; } - .user-menu-item { - font-size: 0.8rem; - padding: 0.42rem 0.8rem; - border-radius: 6px; - cursor: pointer; - color: #8b949e; - transition: background 0.12s, color 0.12s; - } + .user-menu-item { font-size: 0.8rem; padding: 0.42rem 0.8rem; border-radius: 6px; cursor: pointer; color: #8b949e; transition: background 0.12s, color 0.12s; } .user-menu-item:hover { background: #1c2128; color: #e6edf3; } .user-menu-item.danger:hover { background: #3d1a1a; color: #f85149; } - .user-avatar { - width: 26px; height: 26px; - border-radius: 50%; - background: #1d3a6e; - border: 1px solid #30363d; - display: flex; align-items: center; justify-content: center; - font-size: 0.72rem; font-weight: 700; color: #79c0ff; - flex-shrink: 0; - } + .user-avatar { width: 26px; height: 26px; border-radius: 50%; background: #1d3a6e; border: 1px solid #30363d; display: flex; align-items: center; justify-content: center; font-size: 0.72rem; font-weight: 700; color: #79c0ff; flex-shrink: 0; } .user-name { font-size: 0.83rem; } /* ── Main content ── */ @@ -111,58 +44,25 @@ .page-title { font-size: 1rem; font-weight: 600; color: #e6edf3; margin-bottom: 1.5rem; letter-spacing: 0.01em; } /* ── Cards ── */ - .card { - background: #161b22; - border: 1px solid #30363d; - border-radius: 8px; - padding: 1.5rem; - max-width: 520px; - } + .card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 1.5rem; max-width: 520px; } + .card-title { font-size: 0.78rem; font-weight: 600; color: #8b949e; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 1rem; } /* ── Form elements ── */ .form-group { margin-bottom: 1.1rem; } label { display: block; font-size: 0.76rem; color: #8b949e; margin-bottom: 0.35rem; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 500; } - input[type=text], input[type=password], input[type=date] { - width: 100%; padding: 0.55rem 0.75rem; - background: #0d1117; border: 1px solid #30363d; border-radius: 6px; - color: #c9d1d9; font-size: 0.875rem; - } + input[type=text], input[type=password], input[type=date] { width: 100%; padding: 0.55rem 0.75rem; background: #0d1117; border: 1px solid #30363d; border-radius: 6px; color: #c9d1d9; font-size: 0.875rem; } input:focus { outline: none; border-color: #58a6ff; box-shadow: 0 0 0 3px rgba(88,166,255,0.1); } input[type=date]::-webkit-calendar-picker-indicator { filter: invert(0.5); } - /* ── Modules checkboxes ── */ - .modules-grid { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 0.4rem; - } - .module-check { - display: flex; - align-items: center; - gap: 0.5rem; - padding: 0.4rem 0.6rem; - border: 1px solid #30363d; - border-radius: 6px; - cursor: pointer; - font-size: 0.82rem; - color: #8b949e; - transition: border-color 0.12s, color 0.12s, background 0.12s; - user-select: none; - } + /* ── Modules ── */ + .modules-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.4rem; } + .module-check { display: flex; align-items: center; gap: 0.5rem; padding: 0.4rem 0.6rem; border: 1px solid #30363d; border-radius: 6px; cursor: pointer; font-size: 0.82rem; color: #8b949e; transition: border-color 0.12s, color 0.12s, background 0.12s; user-select: none; } .module-check:hover { border-color: #58a6ff; color: #c9d1d9; } .module-check input { display: none; } .module-check.checked { border-color: #1d3a6e; background: #0d1f3a; color: #79c0ff; } /* ── Buttons ── */ - .btn { - padding: 0.55rem 1.1rem; - border-radius: 6px; - font-size: 0.875rem; - cursor: pointer; - border: none; - font-weight: 500; - transition: background 0.12s, opacity 0.12s; - } + .btn { padding: 0.55rem 1.1rem; border-radius: 6px; font-size: 0.875rem; cursor: pointer; border: none; font-weight: 500; transition: background 0.12s, opacity 0.12s; } .btn-primary { background: #1d3a6e; color: #79c0ff; border: 1px solid #1d4ed8; } .btn-primary:hover { background: #1e4080; } .btn-primary:disabled { opacity: 0.45; cursor: not-allowed; } @@ -172,106 +72,101 @@ .btn-danger:hover { background: #3d1a1a; border-color: #f85149; } .btn-sm { padding: 0.3rem 0.7rem; font-size: 0.78rem; } - /* ── Status ── */ + /* ── Status messages ── */ .status { margin-top: 1rem; font-size: 0.83rem; padding: 0.55rem 0.8rem; border-radius: 6px; display: none; } .status.success { background: #0d2818; color: #3fb950; border: 1px solid #1a4731; display: block; } .status.error { background: #2d0f0f; color: #f85149; border: 1px solid #4a1a1a; display: block; } + /* ── Badges ── */ + .badge { display: inline-flex; align-items: center; padding: 0.15rem 0.5rem; border-radius: 4px; font-size: 0.72rem; font-weight: 500; } + .badge-blue { background: #1d3a6e; color: #79c0ff; border: 1px solid #1d4ed8; } + .badge-green { background: #0d2818; color: #3fb950; border: 1px solid #1a4731; } + .badge-red { background: #2d0f0f; color: #f85149; border: 1px solid #4a1a1a; } + .badge-yellow { background: #2d1f0a; color: #e3a04a; border: 1px solid #5a3a10; } + .badge-gray { background: #1c2128; color: #8b949e; border: 1px solid #30363d; } + /* ── Table ── */ - .table-toolbar { - display: flex; - align-items: center; - gap: 0.75rem; - margin-bottom: 1rem; - } - .search-input { - background: #0d1117; - border: 1px solid #30363d; - border-radius: 6px; - padding: 0.5rem 0.75rem; - color: #c9d1d9; - font-size: 0.875rem; - width: 260px; - } + .table-toolbar { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 1rem; } + .search-input { background: #0d1117; border: 1px solid #30363d; border-radius: 6px; padding: 0.5rem 0.75rem; color: #c9d1d9; font-size: 0.875rem; width: 260px; } .search-input:focus { outline: none; border-color: #58a6ff; } - .table-wrap { - background: #161b22; - border: 1px solid #30363d; - border-radius: 8px; - overflow: hidden; - } + .table-wrap { background: #161b22; border: 1px solid #30363d; border-radius: 8px; overflow: hidden; } table { width: 100%; border-collapse: collapse; font-size: 0.845rem; } thead { background: #1c2128; } - th { - padding: 0.65rem 1rem; - text-align: left; - font-size: 0.76rem; - font-weight: 600; - color: #8b949e; - text-transform: uppercase; - letter-spacing: 0.05em; - border-bottom: 1px solid #30363d; - white-space: nowrap; - user-select: none; - } + th { padding: 0.65rem 1rem; text-align: left; font-size: 0.76rem; font-weight: 600; color: #8b949e; text-transform: uppercase; letter-spacing: 0.05em; border-bottom: 1px solid #30363d; white-space: nowrap; user-select: none; } th.sortable { cursor: pointer; } th.sortable:hover { color: #c9d1d9; } th .sort-icon { margin-left: 4px; opacity: 0.4; font-size: 0.7rem; } th.sort-active { color: #58a6ff; } th.sort-active .sort-icon { opacity: 1; } - td { - padding: 0.7rem 1rem; - border-bottom: 1px solid #21262d; - color: #c9d1d9; - vertical-align: middle; - } + td { padding: 0.7rem 1rem; border-bottom: 1px solid #21262d; color: #c9d1d9; vertical-align: middle; } tr:last-child td { border-bottom: none; } tr:hover td { background: #1c2128; } - .tag { - display: inline-block; - padding: 0.15rem 0.45rem; - border-radius: 4px; - font-size: 0.72rem; - font-weight: 500; - background: #1d3a6e; - color: #79c0ff; - border: 1px solid #1d4ed8; - margin: 1px 2px 1px 0; - } + .tag { display: inline-block; padding: 0.15rem 0.45rem; border-radius: 4px; font-size: 0.72rem; font-weight: 500; background: #1d3a6e; color: #79c0ff; border: 1px solid #1d4ed8; margin: 1px 2px 1px 0; } .tag-expired { background: #2d1a0a; color: #e3956a; border-color: #5a3010; } .empty-row td { text-align: center; color: #484f58; padding: 2.5rem; } /* ── Pagination ── */ - .pagination { - display: flex; - align-items: center; - justify-content: space-between; - padding: 0.75rem 1rem; - border-top: 1px solid #21262d; - font-size: 0.8rem; - color: #8b949e; - } + .pagination { display: flex; align-items: center; justify-content: space-between; padding: 0.75rem 1rem; border-top: 1px solid #21262d; font-size: 0.8rem; color: #8b949e; } .pagination-btns { display: flex; gap: 0.4rem; align-items: center; } - .pagination-info { font-size: 0.78rem; } + + /* ── Kebab menu ── */ + .kebab-btn { background: none; border: none; color: #8b949e; cursor: pointer; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 1.1rem; line-height: 1; transition: background 0.1s, color 0.1s; } + .kebab-btn:hover { background: #21262d; color: #c9d1d9; } + #kebab-menu { display: none; position: fixed; background: #161b22; border: 1px solid #30363d; border-radius: 6px; min-width: 160px; z-index: 200; box-shadow: 0 8px 24px rgba(0,0,0,0.4); overflow: hidden; } + #kebab-menu.open { display: block; } + .kebab-item { padding: 0.55rem 1rem; font-size: 0.845rem; color: #c9d1d9; cursor: pointer; transition: background 0.1s; } + .kebab-item:hover { background: #1c2128; } + .kebab-item.danger { color: #f85149; } + .kebab-item.danger:hover { background: #3d1a1a; } + + /* ── Customer detail page ── */ + .detail-header { display: flex; align-items: flex-start; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; } + .detail-title { font-size: 1.1rem; font-weight: 700; color: #e6edf3; } + .detail-slug { font-size: 0.82rem; color: #8b949e; margin-top: 0.2rem; font-family: monospace; } + .detail-meta { display: flex; gap: 0.4rem; align-items: center; flex-wrap: wrap; margin-top: 0.5rem; } + .detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } + @media (max-width: 900px) { .detail-grid { grid-template-columns: 1fr; } } + .stat-card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 1.2rem 1.5rem; } + .stat-card-full { grid-column: 1 / -1; } + .stat-card .card-title { margin-bottom: 0.8rem; } + .stat-row { display: flex; justify-content: space-between; align-items: center; padding: 0.35rem 0; border-bottom: 1px solid #21262d; font-size: 0.845rem; } + .stat-row:last-child { border-bottom: none; } + .stat-label { color: #8b949e; } + .stat-value { color: #e6edf3; font-weight: 500; text-align: right; } + + /* ── Pods table in detail ── */ + .pods-table { width: 100%; border-collapse: collapse; font-size: 0.82rem; margin-top: 0.5rem; } + .pods-table th { text-align: left; color: #8b949e; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em; padding: 0 0 0.5rem 0; border-bottom: 1px solid #21262d; } + .pods-table td { padding: 0.5rem 0; border-bottom: 1px solid #21262d; vertical-align: middle; } + .pods-table tr:last-child td { border-bottom: none; } + .pod-name { font-family: monospace; font-size: 0.8rem; color: #c9d1d9; } + .pod-status-running { color: #3fb950; } + .pod-status-pending { color: #e3a04a; } + .pod-status-failed { color: #f85149; } + .pod-status-unknown { color: #8b949e; } + + /* ── Size history table ── */ + .history-table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } + .history-table th { text-align: left; color: #8b949e; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em; padding: 0 0 0.5rem 0; border-bottom: 1px solid #21262d; } + .history-table td { padding: 0.45rem 0; border-bottom: 1px solid #21262d; color: #c9d1d9; } + .history-table tr:last-child td { border-bottom: none; } + + /* ── Skeleton ── */ + @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.4} } + .skeleton { background: #21262d; border-radius: 4px; animation: pulse 1.5s infinite; display: inline-block; } + + /* ── Step list ── */ + .step-list { display: flex; flex-direction: column; gap: 0.4rem; } + .step-item { display: flex; align-items: center; gap: 0.6rem; font-size: 0.845rem; } + .step-icon { width: 16px; height: 16px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.65rem; flex-shrink: 0; } + .step-done { background: #0d2818; color: #3fb950; border: 1px solid #1a4731; } + .step-failed { background: #2d0f0f; color: #f85149; border: 1px solid #4a1a1a; } + .step-pending { background: #1c2128; color: #8b949e; border: 1px solid #30363d; } /* ── Confirm overlay ── */ - .overlay { - display: none; - position: fixed; inset: 0; - background: rgba(0,0,0,0.6); - align-items: center; - justify-content: center; - z-index: 100; - } + .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; z-index: 100; } .overlay.open { display: flex; } - .dialog { - background: #161b22; - border: 1px solid #30363d; - border-radius: 10px; - padding: 1.8rem; - max-width: 380px; - width: 100%; - } + .dialog { background: #161b22; border: 1px solid #30363d; border-radius: 10px; padding: 1.8rem; max-width: 380px; width: 100%; } .dialog h3 { font-size: 0.95rem; color: #e6edf3; margin-bottom: 0.5rem; } .dialog p { font-size: 0.845rem; color: #8b949e; margin-bottom: 1.4rem; line-height: 1.5; } .dialog-actions { display: flex; gap: 0.6rem; justify-content: flex-end; } @@ -327,11 +222,11 @@
- +
Customers
- +
@@ -346,7 +241,7 @@ Expires Created Updated - + @@ -354,7 +249,7 @@ + +
+
+ +
+
+
+
+
+
+
+
+ + +
+
+
+
+
Loading…
+
Fetching status…
+
+
+
+
Create Environment
@@ -389,24 +308,12 @@
- - - - - - + + + + + +
@@ -435,11 +342,18 @@
+ +
+
View Details
+
Delete
+
Remove Record Only
+
+

Delete Customer

-

This will remove the ArgoCD app, database, and all associated resources for . This cannot be undone.

+

This will remove the ArgoCD app, database, storage, and all associated resources for . This cannot be undone.

@@ -452,26 +366,21 @@ let tableState = { page: 1, limit: 25, q: '', sort: 'created_at', order: 'desc', total: 0, totalPages: 1 }; let searchTimer = null; let pendingDeleteSlug = null; + let kebabSlug = null; + let currentDetailSlug = null; function authHeaders() { - const token = localStorage.getItem('token'); - return token ? { 'Authorization': 'Bearer ' + token } : {}; + const t = localStorage.getItem('token'); + return t ? { Authorization: 'Bearer ' + t } : {}; } - - function apiFetch(url, options = {}) { - return fetch(url, { - ...options, - headers: { ...authHeaders(), ...(options.headers || {}) }, - }); + function apiFetch(url, opts = {}) { + return fetch(url, { ...opts, headers: { ...authHeaders(), ...(opts.headers || {}) } }); } // ── Auth ────────────────────────────────────────────────────────────────── async function checkAuth() { - if (!localStorage.getItem('token')) { - document.getElementById('login-view').style.display = 'flex'; - return; - } + if (!localStorage.getItem('token')) { showLogin(); return; } const res = await apiFetch('/api/auth/me'); if (res.ok) { const data = await res.json(); @@ -480,10 +389,15 @@ loadCustomers(); } else { localStorage.removeItem('token'); - document.getElementById('login-view').style.display = 'flex'; + showLogin(); } } + function showLogin() { + document.getElementById('login-view').style.display = 'flex'; + document.getElementById('app-view').style.display = 'none'; + } + function setUser(username) { currentUser = username; document.getElementById('user-name-label').textContent = username; @@ -498,8 +412,7 @@ status.className = 'status'; try { const res = await fetch('/api/auth/login', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }); const data = await res.json(); @@ -515,10 +428,10 @@ } } - async function logout() { + function logout() { localStorage.removeItem('token'); document.getElementById('app-view').style.display = 'none'; - document.getElementById('login-view').style.display = 'flex'; + showLogin(); document.getElementById('login-password').value = ''; } @@ -531,10 +444,11 @@ function showPage(name) { document.querySelectorAll('.page').forEach(p => p.classList.remove('active')); document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active')); - document.getElementById('page-' + name).classList.add('active'); + document.getElementById('page-' + name)?.classList.add('active'); const navEl = document.getElementById('nav-' + name); if (navEl) navEl.classList.add('active'); document.getElementById('user-menu').classList.remove('open'); + closeKebab(); } // ── Customers table ─────────────────────────────────────────────────────── @@ -551,6 +465,21 @@ renderTable(data, pagination); } + function customerStatusBadge(r) { + if (r.status === 'provisioning') return 'Provisioning'; + if (r.status === 'failed') { + const failedStep = Object.entries(r.steps || {}).find(([,v]) => v === 'failed'); + const label = failedStep ? failedStep[0].replace('_', ' ') : 'unknown'; + return `Failed`; + } + if (r.status === 'provisioned') { + const allDone = Object.values(r.steps || {}).every(v => v === 'done'); + if (allDone) return 'Provisioned'; + return 'Partial'; + } + return `${r.status}`; + } + function renderTable(rows, pagination) { const tbody = document.getElementById('customers-tbody'); if (rows.length === 0) { @@ -562,30 +491,16 @@ const expiry = r.expiration_date ? `${fmtDate(r.expiration_date)}` : ''; - const statusColor = r.status === 'provisioned' ? '#3fb950' : r.status === 'failed' ? '#f85149' : '#e3a04a'; - const STEP_LABELS = { database: 'DB', database_user: 'User', database_setup: 'Schema', pool: 'Pool', chart: 'Chart' }; - const stepsHtml = Object.entries(STEP_LABELS).map(([key, label]) => { - const s = (r.steps || {})[key]; - const icon = s === 'done' ? '✓' : s === 'failed' ? '✗' : '·'; - const color = s === 'done' ? '#3fb950' : s === 'failed' ? '#f85149' : '#484f58'; - return `${icon} ${label}`; - }).join(''); - return ` + return ` ${r.slug} ${r.name || ''} - -
${r.status}
-
${stepsHtml}
- + ${customerStatusBadge(r)} ${modules} ${fmtDate(r.start_date)} ${expiry} ${fmtDateTime(r.created_at)} ${fmtDateTime(r.updated_at)} - - - - + `; }).join(''); } @@ -600,7 +515,6 @@ document.getElementById('btn-prev').disabled = pagination.page <= 1; document.getElementById('btn-next').disabled = pagination.page >= pagination.totalPages; - // Update sort headers document.querySelectorAll('th[data-col]').forEach(th => { const col = th.dataset.col; const icon = document.getElementById('sort-icon-' + col); @@ -614,12 +528,8 @@ } function setSort(col) { - if (tableState.sort === col) { - tableState.order = tableState.order === 'asc' ? 'desc' : 'asc'; - } else { - tableState.sort = col; - tableState.order = 'asc'; - } + if (tableState.sort === col) tableState.order = tableState.order === 'asc' ? 'desc' : 'asc'; + else { tableState.sort = col; tableState.order = 'asc'; } tableState.page = 1; loadCustomers(); } @@ -640,6 +550,178 @@ }, 300); } + // ── Kebab menu ──────────────────────────────────────────────────────────── + + function openKebab(event, slug) { + event.stopPropagation(); + kebabSlug = slug; + const menu = document.getElementById('kebab-menu'); + const rect = event.currentTarget.getBoundingClientRect(); + menu.style.top = (rect.bottom + 4) + 'px'; + menu.style.left = Math.min(rect.left, window.innerWidth - 170) + 'px'; + menu.classList.add('open'); + } + + function closeKebab() { + document.getElementById('kebab-menu').classList.remove('open'); + kebabSlug = null; + } + + function kebabAction(action) { + const slug = kebabSlug; + closeKebab(); + if (!slug) return; + if (action === 'view') openDetail(slug); + else if (action === 'delete') openDeleteDialog(slug); + else if (action === 'record') removeRecord(slug); + } + + document.addEventListener('click', e => { + if (!document.getElementById('kebab-menu').contains(e.target)) closeKebab(); + }); + + // ── Customer detail page ────────────────────────────────────────────────── + + function openDetail(slug) { + currentDetailSlug = slug; + document.getElementById('detail-name').textContent = '…'; + document.getElementById('detail-slug').textContent = slug; + document.getElementById('detail-meta').innerHTML = ''; + document.getElementById('detail-delete-btn').onclick = () => openDeleteDialog(slug); + document.getElementById('detail-grid').innerHTML = ` +
+
Loading
+
+ ${[120,90,140,80].map(w => ``).join('')} +
+
`; + showPage('customer-detail'); + loadDetail(slug, false); + } + + function refreshDetail() { + if (currentDetailSlug) loadDetail(currentDetailSlug, true); + } + + async function loadDetail(slug, forceRefresh) { + const url = `/api/customers/${slug}/overview${forceRefresh ? '?refresh=1' : ''}`; + try { + const res = await apiFetch(url); + if (!res.ok) throw new Error('Failed to load'); + const data = await res.json(); + renderDetail(data); + } catch (err) { + document.getElementById('detail-grid').innerHTML = + `
Failed to load: ${err.message}
`; + } + } + + function renderDetail({ customer, status, sizeHistory }) { + // Header + document.getElementById('detail-name').textContent = customer.name || customer.slug; + document.getElementById('detail-slug').textContent = customer.slug; + const expired = customer.expiration_date && new Date(customer.expiration_date) < new Date(); + const meta = [ + customerStatusBadge(customer), + ...(customer.modules || []).map(m => `${m}`), + expired ? `Expired ${fmtDate(customer.expiration_date)}` : '', + ].filter(Boolean).join(''); + document.getElementById('detail-meta').innerHTML = meta; + + // Compute overall health badge + const pods = status.pods || []; + const argocd = status.argocd; + const allReady = pods.length > 0 && pods.every(p => p.ready); + const hasRestarts = pods.some(p => p.restarts > 5); + const argoHealthy = argocd?.healthStatus === 'Healthy'; + const argoSynced = argocd?.syncStatus === 'Synced'; + + // ── Live status card ────────────────────────────────────────────────── + const argoSyncBadge = !argocd ? 'Unknown' + : argocd.syncStatus === 'Synced' ? 'Synced' + : argocd.syncStatus === 'OutOfSync' ? 'OutOfSync' + : `${argocd.syncStatus}`; + + const argoHealthBadge = !argocd ? 'Unknown' + : argocd.healthStatus === 'Healthy' ? 'Healthy' + : argocd.healthStatus === 'Degraded' ? 'Degraded' + : argocd.healthStatus === 'Progressing' ? 'Progressing' + : `${argocd.healthStatus}`; + + const conditionsHtml = (argocd?.conditions ?? []).filter(c => c.message) + .map(c => `
⚠ ${c.message}
`).join(''); + + const podsHtml = pods.length === 0 + ? '
No pods found
' + : ` + + ${pods.map(p => { + const cls = p.status === 'Running' ? 'pod-status-running' + : p.status === 'Pending' ? 'pod-status-pending' + : p.status === 'Failed' ? 'pod-status-failed' : 'pod-status-unknown'; + const shortName = p.name.replace(new RegExp(`^customer-${customer.slug}-`), ''); + return ` + + + + + + `; + }).join('')} +
PodReadyStatusRestartsAge
${shortName}${p.readyCount}/${p.totalCount}${p.status}${p.restarts}${p.startedAt ? fmtAge(p.startedAt) : '—'}
`; + + const cachedAt = status.cachedAt ? `cached ${fmtDateTime(status.cachedAt)}` : ''; + + // ── Provisioning steps card ─────────────────────────────────────────── + const STEP_LABELS = { database: 'Database', database_user: 'DB User', database_setup: 'Schema', pool: 'Connection Pool', namespace: 'K8s Namespace', secrets: 'Secrets', storage: 'Object Storage', chart: 'ArgoCD Chart' }; + const stepsHtml = Object.entries(STEP_LABELS).map(([key, label]) => { + const s = (customer.steps || {})[key]; + const cls = s === 'done' ? 'step-done' : s === 'failed' ? 'step-failed' : 'step-pending'; + const icon = s === 'done' ? '✓' : s === 'failed' ? '✗' : '·'; + return `
+
${icon}
+ ${label} +
`; + }).join(''); + + // ── Size history card ───────────────────────────────────────────────── + const latestSize = sizeHistory[0] || null; + const sizeRowsHtml = sizeHistory.length === 0 + ? '
No size data yet — collected every 12 hours
' + : ` + + ${sizeHistory.slice(0, 7).map(s => ` + + + + + `).join('')} +
DateDatabaseStorageObjects
${fmtDate(s.recorded_at)}${s.db_size_bytes != null ? fmtBytes(s.db_size_bytes) : '—'}${s.spaces_size_bytes != null ? fmtBytes(s.spaces_size_bytes) : '—'}${s.spaces_object_count ?? '—'}
`; + + document.getElementById('detail-grid').innerHTML = ` +
+
+ Live Status ${cachedAt} +
+
+
Sync ${argoSyncBadge}
+
Health ${argoHealthBadge}
+
+ ${conditionsHtml} + ${podsHtml} +
+
+
Provisioning Steps
+
${stepsHtml}
+
Provisioned ${fmtDateTime(customer.created_at)}
+
+
+
Size History
+ ${sizeRowsHtml} +
+ `; + } + // ── Delete ──────────────────────────────────────────────────────────────── function openDeleteDialog(slug) { @@ -666,6 +748,7 @@ throw new Error(d.message ?? 'Delete failed'); } closeDeleteDialog(); + if (currentDetailSlug === slug) showPage('customers'); loadCustomers(); } catch (err) { alert(err.message); @@ -676,9 +759,10 @@ } async function removeRecord(slug) { - if (!confirm(`Remove "${slug}" from the manager database only?\n\nThis will NOT delete the ArgoCD app or DO database — use this only for failed partial deployments.`)) return; + if (!confirm(`Remove "${slug}" from the manager database only?\n\nThis will NOT delete the ArgoCD app or DO database.`)) return; const res = await apiFetch(`/api/customers/${slug}/record`, { method: 'DELETE' }); if (res.ok) { + if (currentDetailSlug === slug) showPage('customers'); loadCustomers(); } else { const d = await res.json().catch(() => ({})); @@ -689,8 +773,7 @@ // ── Provision ───────────────────────────────────────────────────────────── function toggleModule(checkbox) { - const label = checkbox.closest('.module-check'); - label.classList.toggle('checked', checkbox.checked); + checkbox.closest('.module-check').classList.toggle('checked', checkbox.checked); } async function provision() { @@ -699,10 +782,9 @@ const startDate = document.getElementById('start-date').value; const expirationDate = document.getElementById('expiration-date').value || null; const modules = [...document.querySelectorAll('.module-check input:checked')].map(el => el.value); - if (!name) return; + if (!name || !slug) return; const btn = document.getElementById('provision-btn'); const status = document.getElementById('provision-status'); - if (!slug) return; btn.disabled = true; btn.textContent = 'Provisioning…'; status.className = 'status'; @@ -736,11 +818,7 @@ const confirm = document.getElementById('confirm-password').value; const status = document.getElementById('account-status'); status.className = 'status'; - if (pw !== confirm) { - status.textContent = 'Passwords do not match'; - status.className = 'status error'; - return; - } + if (pw !== confirm) { status.textContent = 'Passwords do not match'; status.className = 'status error'; return; } try { const res = await apiFetch('/api/auth/password', { method: 'POST', @@ -748,7 +826,7 @@ body: JSON.stringify({ password: pw }), }); const data = await res.json(); - if (!res.ok) throw new Error(data.message ?? 'Failed to update password'); + if (!res.ok) throw new Error(data.message ?? 'Failed'); status.textContent = 'Password updated'; status.className = 'status success'; document.getElementById('new-password').value = ''; @@ -765,14 +843,29 @@ if (!val) return '—'; return new Date(val).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); } - function fmtDateTime(val) { if (!val) return '—'; return new Date(val).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }); } + function fmtAge(startedAt) { + const secs = Math.floor((Date.now() - new Date(startedAt)) / 1000); + if (secs < 60) return `${secs}s`; + const mins = Math.floor(secs / 60); + if (mins < 60) return `${mins}m`; + const hrs = Math.floor(mins / 60); + if (hrs < 24) return `${hrs}h ${mins % 60}m`; + return `${Math.floor(hrs / 24)}d`; + } + function fmtBytes(bytes) { + if (bytes == null) return '—'; + bytes = Number(bytes); + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MB`; + return `${(bytes / 1024 ** 3).toFixed(2)} GB`; + } // ── Init ────────────────────────────────────────────────────────────────── - document.getElementById('start-date').value = new Date().toISOString().slice(0, 10); checkAuth(); diff --git a/package.json b/package.json index 3e85024..26f0b76 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "@fastify/jwt": "^10.0.0", "@fastify/static": "^9.0.0", "fastify": "^5.8.4", + "ioredis": "^5.10.1", "postgres": "^3.4.8", "zod": "^4.3.6" }, diff --git a/src/db/manager.ts b/src/db/manager.ts index 919247c..1f6fa7d 100644 --- a/src/db/manager.ts +++ b/src/db/manager.ts @@ -27,6 +27,18 @@ export async function migrate() { ) `; // idempotent column additions for existing deployments + await db` + CREATE TABLE IF NOT EXISTS customer_size_snapshots ( + id SERIAL PRIMARY KEY, + slug TEXT NOT NULL REFERENCES customers(slug) ON DELETE CASCADE, + recorded_at DATE NOT NULL DEFAULT CURRENT_DATE, + db_size_bytes BIGINT, + spaces_size_bytes BIGINT, + spaces_object_count INT, + UNIQUE (slug, recorded_at) + ) + `; + await db`CREATE INDEX IF NOT EXISTS customer_size_snapshots_slug_date ON customer_size_snapshots (slug, recorded_at DESC)`; await db`ALTER TABLE users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`; await db` ALTER TABLE customers @@ -35,6 +47,7 @@ export async function migrate() { ADD COLUMN IF NOT EXISTS modules TEXT[] NOT NULL DEFAULT '{}', ADD COLUMN IF NOT EXISTS start_date DATE NOT NULL DEFAULT CURRENT_DATE, ADD COLUMN IF NOT EXISTS expiration_date DATE, - ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + ADD COLUMN IF NOT EXISTS spaces_key TEXT NOT NULL DEFAULT '' `; } diff --git a/src/index.ts b/src/index.ts index b604985..3daea86 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ import { config } from "./lib/config"; import { migrate } from "./db/manager"; import { authRoutes } from "./routes/auth"; import { customerRoutes } from "./routes/customers"; +import { startSizeCollector } from "./services/sizeCollector"; const app = Fastify({ logger: true }); @@ -42,6 +43,7 @@ app.register(customerRoutes, { } as any); await migrate(); +startSizeCollector(app.log); app.listen({ port: config.port, host: "0.0.0.0" }, (err) => { if (err) { diff --git a/src/lib/cache.ts b/src/lib/cache.ts new file mode 100644 index 0000000..56d64da --- /dev/null +++ b/src/lib/cache.ts @@ -0,0 +1,33 @@ +import Redis from "ioredis"; +import { config } from "./config"; + +// Manager uses the managed Valkey with "mgr:" prefix so it doesn't collide with customer keys +export const cache = new Redis(config.managedValkeyUrl, { + keyPrefix: "mgr:", + lazyConnect: true, + enableReadyCheck: false, +}); + +const STATUS_TTL = 120; // seconds + +export async function getCachedStatus(slug: string): Promise<{ data: any; cachedAt: string } | null> { + try { + const raw = await cache.get(`status:${slug}`); + if (!raw) return null; + return JSON.parse(raw); + } catch { + return null; + } +} + +export async function setCachedStatus(slug: string, data: any): Promise { + try { + await cache.set(`status:${slug}`, JSON.stringify({ data, cachedAt: new Date().toISOString() }), "EX", STATUS_TTL); + } catch {} +} + +export async function invalidateCachedStatus(slug: string): Promise { + try { + await cache.del(`status:${slug}`); + } catch {} +} diff --git a/src/lib/config.ts b/src/lib/config.ts index 5559068..cdc3ead 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -8,6 +8,8 @@ export const config = { doadminDbUrl: process.env.DOADMIN_DATABASE_URL!, jwtSecret: process.env.JWT_SECRET!, managedValkeyUrl: process.env.MANAGED_VALKEY_URL!, + spacesBucket: process.env.SPACES_BUCKET ?? "lunarfront-data", + spacesRegion: process.env.SPACES_REGION ?? "nyc3", }; for (const [key, val] of Object.entries(config)) { diff --git a/src/lib/k8s.ts b/src/lib/k8s.ts index 37c4ee7..3cc9cd1 100644 --- a/src/lib/k8s.ts +++ b/src/lib/k8s.ts @@ -10,7 +10,7 @@ function token() { return readFileSync(SA_TOKEN_PATH, "utf-8").trim(); } -async function k8sFetch(path: string, options: RequestInit = {}, allowStatuses: number[] = []) { +export async function k8sFetch(path: string, options: RequestInit = {}, allowStatuses: number[] = []) { const res = await fetch(`${K8S_API}${path}`, { ...options, headers: { diff --git a/src/routes/customers.ts b/src/routes/customers.ts index a0d55a7..59d79bc 100644 --- a/src/routes/customers.ts +++ b/src/routes/customers.ts @@ -1,13 +1,16 @@ import type { FastifyInstance } from "fastify"; import { z } from "zod"; import crypto from "crypto"; +import postgres from "postgres"; import { createDatabase, createDatabaseUser, deleteDatabase, deleteDatabaseUser } from "../services/do"; import { addCustomerToPool, removeCustomerFromPool } from "../services/pgbouncer"; import { addCustomerChart, removeCustomerChart } from "../services/git"; import { setupCustomerDatabase, teardownCustomerDatabase } from "../services/db"; -import { createNamespace, deleteNamespace, createSecret, createDockerRegistrySecret } from "../lib/k8s"; +import { createNamespace, deleteNamespace, createSecret, createDockerRegistrySecret, patchSecret, getSecret, k8sFetch } from "../lib/k8s"; +import { createSpacesKey, deleteSpacesKey, deleteSpacesObjects, getSpacesUsage } from "../services/spaces"; import { db } from "../db/manager"; import { config } from "../lib/config"; +import { getCachedStatus, setCachedStatus } from "../lib/cache"; const MODULES = ["pos", "inventory", "rentals", "scheduling", "repairs", "accounting"] as const; const PGBOUNCER_HOST = "pgbouncer.pgbouncer.svc"; @@ -71,6 +74,7 @@ export async function customerRoutes(app: FastifyInstance) { pool: "pending", namespace: "pending", secrets: "pending", + storage: "pending", chart: "pending", }; @@ -122,6 +126,20 @@ export async function customerRoutes(app: FastifyInstance) { await setStep("namespace", "done"); await setStep("secrets", "done"); + const { accessKey: spacesKey, secretKey: spacesSecret } = await createSpacesKey( + `customer-${slug}`, + config.spacesBucket, + ); + await patchSecret(namespace, "lunarfront-secrets", { + "spaces-key": spacesKey, + "spaces-secret": spacesSecret, + "spaces-bucket": config.spacesBucket, + "spaces-endpoint": `https://${config.spacesRegion}.digitaloceanspaces.com`, + "spaces-prefix": `${slug}/`, + }); + await db`UPDATE customers SET spaces_key = ${spacesKey}, updated_at = NOW() WHERE slug = ${slug}`; + await setStep("storage", "done"); + addCustomerChart(slug, body.appVersion); await setStep("chart", "done"); @@ -144,9 +162,20 @@ export async function customerRoutes(app: FastifyInstance) { app.log.info({ slug }, "deprovisioning customer"); + const [customer] = await db`SELECT spaces_key FROM customers WHERE slug = ${slug}`; + removeCustomerChart(slug); await removeCustomerFromPool(slug); await teardownCustomerDatabase(slug, slug); + + if (customer?.spaces_key) { + try { + const secrets = await getSecret(namespace, "lunarfront-secrets"); + await deleteSpacesObjects(customer.spaces_key, secrets["spaces-secret"], config.spacesBucket, config.spacesRegion, `${slug}/`); + } catch {} + try { await deleteSpacesKey(customer.spaces_key); } catch {} + } + await Promise.all([ deleteDatabase(slug), deleteDatabaseUser(slug), @@ -159,6 +188,63 @@ export async function customerRoutes(app: FastifyInstance) { return reply.code(204).send(); }); + // Live overview: cached status (pods + ArgoCD) + latest size snapshot + 30d history + app.get("/customers/:slug/overview", async (req, reply) => { + const { slug } = req.params as { slug: string }; + const namespace = `customer-${slug}`; + const { refresh } = req.query as { refresh?: string }; + + const [customer] = await db`SELECT * FROM customers WHERE slug = ${slug}`; + if (!customer) return reply.code(404).send({ message: "Not found" }); + + // ── Status (Redis cache, 2min TTL) ──────────────────────────────────────── + let statusEntry = refresh ? null : await getCachedStatus(slug); + if (!statusEntry) { + const [podsResult, argoResult] = await Promise.allSettled([ + k8sFetch(`/api/v1/namespaces/${namespace}/pods`).then(r => r.json()), + k8sFetch(`/apis/argoproj.io/v1alpha1/namespaces/argocd/applications/customer-${slug}`).then(r => r.json()), + ]); + + const podsRaw = podsResult.status === "fulfilled" ? podsResult.value : null; + const argoRaw = argoResult.status === "fulfilled" ? argoResult.value : null; + + const pods = (podsRaw?.items ?? []).map((pod: any) => ({ + name: pod.metadata.name, + ready: (pod.status.containerStatuses ?? []).every((c: any) => c.ready), + readyCount: (pod.status.containerStatuses ?? []).filter((c: any) => c.ready).length, + totalCount: (pod.status.containerStatuses ?? []).length, + status: pod.status.phase ?? "Unknown", + restarts: (pod.status.containerStatuses ?? []).reduce((s: number, c: any) => s + (c.restartCount ?? 0), 0), + startedAt: pod.status.startTime ?? null, + })); + + const argocd = argoRaw?.status ? { + syncStatus: argoRaw.status.sync?.status ?? "Unknown", + healthStatus: argoRaw.status.health?.status ?? "Unknown", + conditions: (argoRaw.status.conditions ?? []).map((c: any) => ({ type: c.type, message: c.message })), + } : null; + + const liveStatus = { pods, argocd }; + await setCachedStatus(slug, liveStatus); + statusEntry = { data: liveStatus, cachedAt: new Date().toISOString() }; + } + + // ── Size history (last 30 days) ─────────────────────────────────────────── + const sizeHistory = await db` + SELECT recorded_at, db_size_bytes, spaces_size_bytes, spaces_object_count + FROM customer_size_snapshots + WHERE slug = ${slug} + ORDER BY recorded_at DESC + LIMIT 30 + `; + + return reply.send({ + customer, + status: { ...statusEntry.data, cachedAt: statusEntry.cachedAt }, + sizeHistory, + }); + }); + // Remove only the manager DB record without touching infrastructure — // useful for cleaning up failed partial deployments app.delete("/customers/:slug/record", async (req, reply) => { diff --git a/src/services/sizeCollector.ts b/src/services/sizeCollector.ts new file mode 100644 index 0000000..bce3de1 --- /dev/null +++ b/src/services/sizeCollector.ts @@ -0,0 +1,87 @@ +import postgres from "postgres"; +import { db } from "../db/manager"; +import { config } from "../lib/config"; +import { getSecret } from "../lib/k8s"; +import { getSpacesUsage } from "./spaces"; + +async function collectSizes() { + const customers = await db`SELECT slug, spaces_key FROM customers WHERE status = 'provisioned'`; + if (customers.length === 0) return; + + for (const customer of customers) { + const { slug } = customer; + try { + // DB size + let dbSizeBytes: number | null = null; + try { + const sql = postgres(config.doadminDbUrl.replace(/\/([^/?]+)(\?|$)/, `/${slug}$2`), { max: 1 }); + try { + const [row] = await sql<[{ bytes: string }]>`SELECT pg_database_size(${slug}::text)::text AS bytes`; + dbSizeBytes = Number(row.bytes); + } finally { + await sql.end(); + } + } catch {} + + // Spaces size + let spacesSizeBytes: number | null = null; + let spacesObjectCount: number | null = null; + if (customer.spaces_key) { + try { + const namespace = `customer-${slug}`; + const secrets = await getSecret(namespace, "lunarfront-secrets"); + const result = await getSpacesUsage( + customer.spaces_key, + secrets["spaces-secret"], + config.spacesBucket, + config.spacesRegion, + `${slug}/`, + ); + spacesSizeBytes = result.sizeBytes; + spacesObjectCount = result.objectCount; + } catch {} + } + + // Upsert today's snapshot (one row per day per customer) + await db` + INSERT INTO customer_size_snapshots (slug, recorded_at, db_size_bytes, spaces_size_bytes, spaces_object_count) + VALUES (${slug}, CURRENT_DATE, ${dbSizeBytes}, ${spacesSizeBytes}, ${spacesObjectCount}) + ON CONFLICT (slug, recorded_at) DO UPDATE SET + db_size_bytes = EXCLUDED.db_size_bytes, + spaces_size_bytes = EXCLUDED.spaces_size_bytes, + spaces_object_count = EXCLUDED.spaces_object_count + `; + } catch (err) { + console.error(`[sizeCollector] failed for ${slug}:`, err); + } + } +} + +function msUntilNext12h(): number { + const now = new Date(); + const next = new Date(now); + const h = now.getUTCHours(); + // next run at 00:00 or 12:00 UTC, whichever is sooner + if (h < 12) { + next.setUTCHours(12, 0, 0, 0); + } else { + next.setUTCDate(next.getUTCDate() + 1); + next.setUTCHours(0, 0, 0, 0); + } + return next.getTime() - now.getTime(); +} + +export function startSizeCollector(log: { info: (msg: string) => void }) { + // Run immediately on startup + collectSizes().then(() => log.info("Initial size snapshot collected")).catch(() => {}); + + // Then schedule for 00:00 and 12:00 UTC + function scheduleNext() { + const delay = msUntilNext12h(); + setTimeout(() => { + collectSizes().then(() => log.info("Size snapshot collected")).catch(() => {}); + scheduleNext(); + }, delay); + } + scheduleNext(); +} diff --git a/src/services/spaces.ts b/src/services/spaces.ts new file mode 100644 index 0000000..322d209 --- /dev/null +++ b/src/services/spaces.ts @@ -0,0 +1,219 @@ +import crypto from "crypto"; +import { config } from "../lib/config"; + +const DO_API = "https://api.digitalocean.com/v2"; + +// ── DO Spaces key management ───────────────────────────────────────────────── + +export async function createSpacesKey( + name: string, + bucket: string, +): Promise<{ accessKey: string; secretKey: string }> { + const res = await fetch(`${DO_API}/spaces/keys`, { + method: "POST", + headers: { + Authorization: `Bearer ${config.doToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + name, + grants: [{ bucket, permission: "readwrite" }], + }), + }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`DO API POST /v2/spaces/keys → ${res.status}: ${body}`); + } + const data = (await res.json()) as { key: { access_key: string; secret_key: string } }; + return { accessKey: data.key.access_key, secretKey: data.key.secret_key }; +} + +export async function deleteSpacesKey(accessKey: string): Promise { + const res = await fetch(`${DO_API}/spaces/keys/${accessKey}`, { + method: "DELETE", + headers: { + Authorization: `Bearer ${config.doToken}`, + "Content-Type": "application/json", + }, + }); + if (!res.ok && res.status !== 404) { + const body = await res.text(); + throw new Error(`DO API DELETE /v2/spaces/keys/${accessKey} → ${res.status}: ${body}`); + } +} + +// ── AWS4 signing helpers ────────────────────────────────────────────────────── + +function sha256hex(data: string | Buffer): string { + return crypto.createHash("sha256").update(data).digest("hex"); +} + +function hmac(key: string | Buffer, data: string): Buffer { + return crypto.createHmac("sha256", key).update(data).digest(); +} + +function awsSign( + method: string, + url: URL, + headers: Record, + body: string, + accessKey: string, + secretKey: string, + region: string, +): Record { + const service = "s3"; + const now = new Date(); + const dateStamp = now.toISOString().slice(0, 10).replace(/-/g, ""); + const amzDate = now.toISOString().replace(/[:-]/g, "").replace(/\.\d{3}/, ""); + + const payloadHash = sha256hex(body); + const allHeaders: Record = { + ...headers, + host: url.host, + "x-amz-date": amzDate, + "x-amz-content-sha256": payloadHash, + }; + + // Canonical headers (sorted lowercase) + const sortedKeys = Object.keys(allHeaders).sort(); + const canonicalHeaders = sortedKeys.map(k => `${k.toLowerCase()}:${allHeaders[k].trim()}`).join("\n") + "\n"; + const signedHeaders = sortedKeys.map(k => k.toLowerCase()).join(";"); + + const canonicalUri = url.pathname || "/"; + const canonicalQueryString = [...url.searchParams.entries()] + .sort(([a], [b]) => a.localeCompare(b)) + .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) + .join("&"); + + const canonicalRequest = [method, canonicalUri, canonicalQueryString, canonicalHeaders, signedHeaders, payloadHash].join("\n"); + + const credentialScope = `${dateStamp}/${region}/${service}/aws4_request`; + const stringToSign = ["AWS4-HMAC-SHA256", amzDate, credentialScope, sha256hex(canonicalRequest)].join("\n"); + + const signingKey = hmac( + hmac(hmac(hmac(`AWS4${secretKey}`, dateStamp), region), service), + "aws4_request", + ); + const signature = crypto.createHmac("sha256", signingKey).update(stringToSign).digest("hex"); + + const authHeader = `AWS4-HMAC-SHA256 Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; + + return { + ...allHeaders, + Authorization: authHeader, + }; +} + +// ── Spaces usage ────────────────────────────────────────────────────────────── + +export async function getSpacesUsage( + accessKey: string, + secretKey: string, + bucket: string, + region: string, + prefix: string, +): Promise<{ objectCount: number; sizeBytes: number; sizePretty: string }> { + const endpoint = `https://${bucket}.${region}.digitaloceanspaces.com/`; + const url = new URL(endpoint); + url.searchParams.set("list-type", "2"); + url.searchParams.set("prefix", prefix); + url.searchParams.set("max-keys", "1000"); + + const signedHeaders = awsSign("GET", url, {}, "", accessKey, secretKey, region); + + const res = await fetch(url.toString(), { headers: signedHeaders }); + if (!res.ok) { + const body = await res.text(); + throw new Error(`Spaces ListObjectsV2 → ${res.status}: ${body}`); + } + + const xml = await res.text(); + + const sizeMatches = xml.match(/(\d+)<\/Size>/g) ?? []; + const sizeBytes = sizeMatches.reduce((sum, m) => { + const n = m.match(/(\d+)<\/Size>/); + return sum + (n ? Number(n[1]) : 0); + }, 0); + + const keyMatches = xml.match(//g) ?? []; + const objectCount = keyMatches.length; + + return { objectCount, sizeBytes, sizePretty: formatBytes(sizeBytes) }; +} + +// ── Spaces object deletion ──────────────────────────────────────────────────── + +export async function deleteSpacesObjects( + accessKey: string, + secretKey: string, + bucket: string, + region: string, + prefix: string, +): Promise { + // List all objects under prefix + const endpoint = `https://${bucket}.${region}.digitaloceanspaces.com/`; + const listUrl = new URL(endpoint); + listUrl.searchParams.set("list-type", "2"); + listUrl.searchParams.set("prefix", prefix); + listUrl.searchParams.set("max-keys", "1000"); + + const listHeaders = awsSign("GET", listUrl, {}, "", accessKey, secretKey, region); + const listRes = await fetch(listUrl.toString(), { headers: listHeaders }); + if (!listRes.ok) { + const body = await listRes.text(); + throw new Error(`Spaces ListObjectsV2 → ${listRes.status}: ${body}`); + } + + const xml = await listRes.text(); + const keyMatches = [...xml.matchAll(/([^<]+)<\/Key>/g)]; + if (keyMatches.length === 0) return; + + const keys = keyMatches.map(m => m[1]); + + // Delete in batches of 1000 + const batchSize = 1000; + for (let i = 0; i < keys.length; i += batchSize) { + const batch = keys.slice(i, i + batchSize); + const deleteXml = + `` + + batch.map(k => `${escapeXml(k)}`).join("") + + ``; + + const deleteUrl = new URL(endpoint); + deleteUrl.searchParams.set("delete", ""); + + const contentMd5 = crypto.createHash("md5").update(deleteXml).digest("base64"); + const deleteHeaders = awsSign( + "POST", + deleteUrl, + { "content-md5": contentMd5, "content-type": "application/xml" }, + deleteXml, + accessKey, + secretKey, + region, + ); + + const deleteRes = await fetch(deleteUrl.toString(), { + method: "POST", + headers: deleteHeaders, + body: deleteXml, + }); + if (!deleteRes.ok) { + const body = await deleteRes.text(); + throw new Error(`Spaces DeleteObjects → ${deleteRes.status}: ${body}`); + } + } +} + +// ── Helpers ─────────────────────────────────────────────────────────────────── + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +function escapeXml(str: string): string { + return str.replace(/&/g, "&").replace(//g, ">"); +}