@cartanova/qgrid-cli 2.6.2 → 2.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +40 -6
  2. package/bundle/dist/application/qgrid/qgrid.frame.js +21 -6
  3. package/bundle/dist/application/qgrid/qgrid.types.js +13 -3
  4. package/bundle/dist/application/qgrid/token-death.js +28 -3
  5. package/bundle/dist/application/queries.generated.js +2 -1
  6. package/bundle/dist/application/request-log/request-log.model.js +37 -5
  7. package/bundle/dist/application/request-log-step/request-log-step.model.js +1 -1
  8. package/bundle/dist/application/sonamu.generated.js +41 -3
  9. package/bundle/dist/application/token/token.model.js +24 -14
  10. package/bundle/dist/i18n/en.js +3 -1
  11. package/bundle/dist/i18n/ko.js +3 -1
  12. package/bundle/dist/i18n/sd.generated.js +18 -1
  13. package/bundle/dist/migrations/20260807164057_alter_request_logs_alter1.js +13 -0
  14. package/bundle/dist/server-error-handler.js +5 -3
  15. package/bundle/dist/sonamu.config.js +5 -1
  16. package/bundle/src/application/qgrid/qgrid-oauth-redirect.test.ts +0 -3
  17. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +30 -2
  18. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +44 -6
  19. package/bundle/src/application/qgrid/qgrid.frame.ts +13 -4
  20. package/bundle/src/application/qgrid/qgrid.types.ts +10 -0
  21. package/bundle/src/application/qgrid/token-death.test.ts +33 -3
  22. package/bundle/src/application/qgrid/token-death.ts +32 -3
  23. package/bundle/src/application/queries.generated.ts +3 -0
  24. package/bundle/src/application/request-log/request-log.entity.json +26 -1
  25. package/bundle/src/application/request-log/request-log.model.ts +50 -10
  26. package/bundle/src/application/sonamu.generated.http +6 -0
  27. package/bundle/src/application/sonamu.generated.ts +42 -2
  28. package/bundle/src/application/token/token.model.test.ts +13 -3
  29. package/bundle/src/application/token/token.model.ts +15 -17
  30. package/bundle/src/i18n/en.ts +3 -0
  31. package/bundle/src/i18n/ko.ts +3 -0
  32. package/bundle/src/i18n/sd.generated.ts +17 -0
  33. package/bundle/src/migrations/20260807164057_alter_request_logs_alter1.ts +13 -0
  34. package/bundle/src/server-error-handler.test.ts +58 -0
  35. package/bundle/src/server-error-handler.ts +16 -5
  36. package/bundle/src/sonamu.config.ts +6 -0
  37. package/bundle/web-dist/client/assets/index-BGQSGMcK.css +1 -0
  38. package/bundle/web-dist/client/assets/index-CnNT0mdq.js +78 -0
  39. package/bundle/web-dist/client/assets/logs-DCY81UWb.js +1 -0
  40. package/bundle/web-dist/client/assets/{monit-BSa5lSZp.js → monit-D5OoAday.js} +1 -1
  41. package/bundle/web-dist/client/assets/routes-B4D9C86u.js +5 -0
  42. package/bundle/web-dist/client/assets/{sd.generated-CjW3rfJ8.js → sd.generated-DYdwSB2I.js} +1 -1
  43. package/bundle/web-dist/client/assets/{services.generated-B-dMUtEu.js → services.generated-BsAvotjG.js} +1 -1
  44. package/bundle/web-dist/client/assets/{show-C1jEPhuS.js → show-BSX8ii7Z.js} +3 -3
  45. package/bundle/web-dist/client/assets/{tokens-1e66MAC0.js → tokens-Gapk41cz.js} +1 -1
  46. package/bundle/web-dist/client/assets/{use-update-token-mutation-DueEppqt.js → use-update-token-mutation-DqEpK7It.js} +1 -1
  47. package/bundle/web-dist/client/index.html +3 -3
  48. package/bundle/web-dist/server/assets/{lazyRouteComponent-PRxXWW3t.js → lazyRouteComponent-BaZaveNc.js} +1 -1
  49. package/bundle/web-dist/server/assets/{logs-CwoOsveV.js → logs-DMOw3SjD.js} +82 -40
  50. package/bundle/web-dist/server/assets/{monit-DIsEsDJN.js → monit-UmcqHroX.js} +2 -2
  51. package/bundle/web-dist/server/assets/{routes-Bts-KJ9W.js → routes-Sv_4FjtH.js} +47 -45
  52. package/bundle/web-dist/server/assets/{sd.generated-ek-tz-7H.js → sd.generated-B0xqnHEo.js} +21 -0
  53. package/bundle/web-dist/server/assets/{services.generated-Bh7Vs8Ds.js → services.generated-DqAKskAS.js} +16 -1
  54. package/bundle/web-dist/server/assets/{show-DJfaCNUw.js → show-C-oSdzHX.js} +31 -25
  55. package/bundle/web-dist/server/assets/{tokens-BA4vwDat.js → tokens-h-2A3wfD.js} +112 -109
  56. package/bundle/web-dist/server/assets/{use-update-token-mutation-BQRzEPy2.js → use-update-token-mutation-DHCaa7Ku.js} +1 -1
  57. package/bundle/web-dist/server/entry-server.generated.js +70 -29
  58. package/package.json +1 -1
  59. package/skills/qgrid/references/cli-env-and-server-boot.md +8 -0
  60. package/skills/qgrid/references/token-auth-quota-lifecycle.md +2 -2
  61. package/bundle/web-dist/client/assets/index-2cAgaLOm.css +0 -1
  62. package/bundle/web-dist/client/assets/index-BgWzzjvj.js +0 -78
  63. package/bundle/web-dist/client/assets/logs-Lyv8OfHE.js +0 -1
  64. package/bundle/web-dist/client/assets/routes-Cp0re-Nn.js +0 -5
@@ -38,7 +38,7 @@ describe("deactivateAuthDeadToken", () => {
38
38
 
39
39
  it("deactivates and notifies when the failed attempt used the current refresh token", async () => {
40
40
  findOneMock.mockResolvedValue(storedRefreshToken("rt-current"));
41
- deactivateMock.mockResolvedValue(true);
41
+ deactivateMock.mockResolvedValue({ deactivated: true, keptAsLastActive: false });
42
42
 
43
43
  await expect(
44
44
  deactivateAuthDeadToken(token, "rt-current", "anthropic:400"),
@@ -67,7 +67,7 @@ describe("deactivateAuthDeadToken", () => {
67
67
 
68
68
  it("does not notify when another process won the deactivation race", async () => {
69
69
  findOneMock.mockResolvedValue(storedRefreshToken("rt-current"));
70
- deactivateMock.mockResolvedValue(false);
70
+ deactivateMock.mockResolvedValue({ deactivated: false, keptAsLastActive: false });
71
71
 
72
72
  await expect(deactivateAuthDeadToken(token, "rt-current", "anthropic:400")).resolves.toBe(
73
73
  false,
@@ -76,6 +76,36 @@ describe("deactivateAuthDeadToken", () => {
76
76
  expect(notifySlackMock).not.toHaveBeenCalled();
77
77
  });
78
78
 
79
+ it("alerts instead of deactivating when the dying token is the last active one", async () => {
80
+ // 알림 쿨다운이 모듈 수준 상태라 다른 테스트의 발송 기록에 가려질 수 있다.
81
+ vi.resetModules();
82
+ const { deactivateAuthDeadToken: freshDeactivate } = await import("./token-death");
83
+ findOneMock.mockResolvedValue(storedRefreshToken("rt-current"));
84
+ deactivateMock.mockResolvedValue({ deactivated: false, keptAsLastActive: true });
85
+
86
+ await expect(freshDeactivate(token, "rt-current", "anthropic:400")).resolves.toBe(false);
87
+
88
+ expect(notifySlackMock).toHaveBeenCalledTimes(1);
89
+ const notification = notifySlackMock.mock.calls[0]![0] as { title: string; context: string };
90
+ expect(notification.title).toContain("마지막");
91
+ expect(notification.context).toContain("anthropic:400");
92
+ });
93
+
94
+ it("suppresses repeat last-active alerts for the same provider within the cooldown", async () => {
95
+ // 이 경로는 토큰을 비활성화하지 않아 상태 변화가 없다 — 억제가 없으면 요청마다 알림이 간다.
96
+ // 쿨다운은 모듈 수준 상태라 앞 테스트의 발송 기록이 남는다. 새로 불러 격리한다.
97
+ vi.resetModules();
98
+ const { deactivateAuthDeadToken: freshDeactivate } = await import("./token-death");
99
+ findOneMock.mockResolvedValue(storedRefreshToken("rt-current"));
100
+ deactivateMock.mockResolvedValue({ deactivated: false, keptAsLastActive: true });
101
+
102
+ await freshDeactivate(token, "rt-current", "anthropic:400");
103
+ await freshDeactivate(token, "rt-current", "anthropic:400");
104
+ await freshDeactivate(token, "rt-current", "anthropic:401");
105
+
106
+ expect(notifySlackMock).toHaveBeenCalledTimes(1);
107
+ });
108
+
79
109
  it("does nothing when the token no longer exists", async () => {
80
110
  findOneMock.mockResolvedValue(undefined);
81
111
 
@@ -88,7 +118,7 @@ describe("deactivateAuthDeadToken", () => {
88
118
 
89
119
  it("never puts the raw provider error body in the notification", async () => {
90
120
  findOneMock.mockResolvedValue(storedRefreshToken("rt-current"));
91
- deactivateMock.mockResolvedValue(true);
121
+ deactivateMock.mockResolvedValue({ deactivated: true, keptAsLastActive: false });
92
122
 
93
123
  await deactivateAuthDeadToken(token, "rt-current", "anthropic:400");
94
124
 
@@ -42,8 +42,11 @@ export async function deactivateAuthDeadToken(
42
42
  return false;
43
43
  }
44
44
 
45
- const deactivated = await TokenModel.deactivateIfActive(token.id);
46
- if (!deactivated) return false;
45
+ const { deactivated, keptAsLastActive } = await TokenModel.deactivateIfActive(token.id);
46
+ if (!deactivated) {
47
+ if (keptAsLastActive) notifyLastActiveTokenDying(token, reasonCode);
48
+ return false;
49
+ }
47
50
 
48
51
  logger.warn(`token deactivated (auth dead): ${token.name}(id=${token.id}) reason=${reasonCode}`);
49
52
  void notifySlack({
@@ -55,7 +58,33 @@ export async function deactivateAuthDeadToken(
55
58
  return true;
56
59
  }
57
60
 
58
- /** 처음 보는 계정이 등록됐을 때. 재로그인(기존 토큰 교체)은 알리지 않는다. */
61
+ /**
62
+ * 마지막 활성 토큰이 죽었을 때의 알림 쿨다운.
63
+ *
64
+ * 이 경우 토큰은 비활성화되지 않고 살아남으므로, 뒤따르는 요청마다 같은 실패를 반복해
65
+ * 알림이 폭주한다. 비활성화 성공 경로가 조건부 UPDATE 로 중복을 막는 것과 달리 여기엔
66
+ * 상태 변화가 없어 DB 로 억제할 수 없다 — provider 단위로 시간 창을 둔다.
67
+ */
68
+ const LAST_ACTIVE_ALERT_COOLDOWN_MS = 30 * 60 * 1000;
69
+ const lastActiveAlertAt = new Map<string, number>();
70
+
71
+ function notifyLastActiveTokenDying(token: DeadTokenRef, reasonCode: string): void {
72
+ const now = Date.now();
73
+ const previous = lastActiveAlertAt.get(token.provider);
74
+ if (previous !== undefined && now - previous < LAST_ACTIVE_ALERT_COOLDOWN_MS) return;
75
+ lastActiveAlertAt.set(token.provider, now);
76
+
77
+ void notifySlack({
78
+ title: "마지막 토큰 사망",
79
+ subject: token.name,
80
+ context:
81
+ `${token.provider} · ${reasonCode} · 풀이 비지 않도록 유지 중입니다. ` +
82
+ `전 토큰이 동시에 실패했다면 client_id 취소나 OAuth 계약 변경을 의심하세요`,
83
+ color: SLACK_COLOR.bad,
84
+ });
85
+ }
86
+
87
+ /** 로그인이 완료돼 토큰이 저장됐을 때. 신규·재로그인을 가리지 않는다. */
59
88
  export function notifyTokenAdded(name: string, provider: string): void {
60
89
  logger.info(`token added: ${name} (${provider})`);
61
90
  void notifySlack({
@@ -86,6 +86,9 @@ export namespace QgridService {
86
86
  export const projectNames = (): SSRQuery =>
87
87
  createSSRQuery("QgridFrame", "projectNames", [], ["Qgrid", "projectNames"]);
88
88
 
89
+ export const modelNames = (): SSRQuery =>
90
+ createSSRQuery("QgridFrame", "modelNames", [], ["Qgrid", "modelNames"]);
91
+
89
92
  export const usage = (tokenId?: number): SSRQuery =>
90
93
  createSSRQuery("QgridFrame", "usage", [tokenId], ["Qgrid", "usage"]);
91
94
 
@@ -133,6 +133,12 @@
133
133
  "name": "request_logs_project_name_cost_usd_index",
134
134
  "columns": [{ "name": "project_name" }, { "name": "cost_usd" }],
135
135
  "using": "btree"
136
+ },
137
+ {
138
+ "type": "index",
139
+ "name": "request_logs_model_name_index",
140
+ "columns": [{ "name": "model_name" }],
141
+ "using": "btree"
136
142
  }
137
143
  ],
138
144
  "subsets": {
@@ -207,7 +213,26 @@
207
213
  ]
208
214
  },
209
215
  "enums": {
210
- "RequestLogOrderBy": { "id-desc": "ID최신순" },
216
+ "RequestLogOrderBy": {
217
+ "id-desc": "ID최신순",
218
+ "id-asc": "ID오래된순",
219
+ "created_at-desc": "등록일시최신순",
220
+ "created_at-asc": "등록일시오래된순",
221
+ "ttft_ms-desc": "TTFT긴순",
222
+ "ttft_ms-asc": "TTFT짧은순",
223
+ "duration_ms-desc": "소요시간긴순",
224
+ "duration_ms-asc": "소요시간짧은순",
225
+ "input_tokens-desc": "입력토큰많은순",
226
+ "input_tokens-asc": "입력토큰적은순",
227
+ "output_tokens-desc": "출력토큰많은순",
228
+ "output_tokens-asc": "출력토큰적은순",
229
+ "cache_read_tokens-desc": "캐시읽기많은순",
230
+ "cache_read_tokens-asc": "캐시읽기적은순",
231
+ "cache_creation_tokens-desc": "캐시생성많은순",
232
+ "cache_creation_tokens-asc": "캐시생성적은순",
233
+ "cost_usd-desc": "비용높은순",
234
+ "cost_usd-asc": "비용낮은순"
235
+ },
211
236
  "RequestLogSearchField": {
212
237
  "id": "ID",
213
238
  "token_name": "토큰이름",
@@ -3,7 +3,6 @@ import {
3
3
  asArray,
4
4
  BadRequestException,
5
5
  BaseModelClass,
6
- exhaustive,
7
6
  type ListResult,
8
7
  NotFoundException,
9
8
  Puri,
@@ -152,6 +151,43 @@ function normalizeLegacyAnthropicRow<T extends RequestLogUsageRow>(row: T): T {
152
151
  return normalized;
153
152
  }
154
153
 
154
+ /**
155
+ * `orderBy` enum 값(`컬럼-방향`)을 정렬 절로 옮긴다.
156
+ *
157
+ * enum 이 18 종이라 케이스를 일일이 적는 대신 파싱하되, 컬럼은 아래 목록으로 한정한다 —
158
+ * 문자열을 그대로 컬럼명에 넘기면 enum 이 바뀔 때 검증 없는 식별자가 SQL 로 흘러든다.
159
+ * 목록에 없는 값은 기본 정렬(id desc)로 떨어진다.
160
+ */
161
+ const ORDERABLE_COLUMNS = {
162
+ id: "request_logs.id",
163
+ created_at: "request_logs.created_at",
164
+ ttft_ms: "request_logs.ttft_ms",
165
+ duration_ms: "request_logs.duration_ms",
166
+ input_tokens: "request_logs.input_tokens",
167
+ output_tokens: "request_logs.output_tokens",
168
+ cache_read_tokens: "request_logs.cache_read_tokens",
169
+ cache_creation_tokens: "request_logs.cache_creation_tokens",
170
+ cost_usd: "request_logs.cost_usd",
171
+ } as const;
172
+
173
+ function applyOrderBy(
174
+ qb: ReturnType<RequestLogModelClass["getSubsetQueries"]>["qb"],
175
+ orderBy: string,
176
+ ): void {
177
+ const separator = orderBy.lastIndexOf("-");
178
+ const key = orderBy.slice(0, separator) as keyof typeof ORDERABLE_COLUMNS;
179
+ const direction = orderBy.slice(separator + 1) === "asc" ? "asc" : "desc";
180
+ const column = ORDERABLE_COLUMNS[key];
181
+
182
+ if (!column) {
183
+ qb.orderBy("request_logs.id", "desc");
184
+ return;
185
+ }
186
+ qb.orderBy(column, direction);
187
+ // 동점 행의 순서가 페이지마다 흔들리지 않게 고유 컬럼으로 tie-break 한다.
188
+ if (key !== "id") qb.orderBy("request_logs.id", "desc");
189
+ }
190
+
155
191
  /*
156
192
  RequestLog Model
157
193
  */
@@ -254,15 +290,7 @@ class RequestLogModelClass extends BaseModelClass<
254
290
 
255
291
  this.applyListFilters(qb, params);
256
292
 
257
- // orderBy
258
- if (params.orderBy) {
259
- // default orderBy
260
- if (params.orderBy === "id-desc") {
261
- qb.orderBy("request_logs.id", "desc");
262
- } else {
263
- exhaustive(params.orderBy);
264
- }
265
- }
293
+ if (params.orderBy) applyOrderBy(qb, params.orderBy);
266
294
 
267
295
  const enhancers = this.createEnhancers({
268
296
  A: (row) => normalizeLegacyAnthropicRow(row),
@@ -705,6 +733,18 @@ class RequestLogModelClass extends BaseModelClass<
705
733
  return rows.map((r) => r.project_name!);
706
734
  }
707
735
 
736
+ async distinctModelNames(): Promise<string[]> {
737
+ const rows = await this.getPuri("r")
738
+ .from("request_logs")
739
+ .distinct("model_name")
740
+ .where("model_name", "!=", null)
741
+ .orderBy("model_name", "asc")
742
+ .select({
743
+ model_name: "model_name",
744
+ });
745
+ return rows.map((r) => r.model_name!);
746
+ }
747
+
708
748
  @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
709
749
  async del(ids: number[]): Promise<number> {
710
750
  const wdb = this.getPuri("w");
@@ -457,6 +457,12 @@ Content-Type: application/json
457
457
 
458
458
  ###
459
459
 
460
+ GET {{baseUrl}}/api/qgrid/modelNames
461
+ ?
462
+ Content-Type: application/json
463
+
464
+ ###
465
+
460
466
  POST {{baseUrl}}/api/qgrid/addToken
461
467
  Content-Type: application/json
462
468
 
@@ -53,9 +53,49 @@ const ToolDefinitions = z.array(
53
53
  type ToolDefinitions = z.infer<typeof ToolDefinitions>;
54
54
 
55
55
  // Enums: RequestLog
56
- export const RequestLogOrderBy = z.enum(["id-desc"]).describe("RequestLogOrderBy");
56
+ export const RequestLogOrderBy = z
57
+ .enum([
58
+ "id-desc",
59
+ "id-asc",
60
+ "created_at-desc",
61
+ "created_at-asc",
62
+ "ttft_ms-desc",
63
+ "ttft_ms-asc",
64
+ "duration_ms-desc",
65
+ "duration_ms-asc",
66
+ "input_tokens-desc",
67
+ "input_tokens-asc",
68
+ "output_tokens-desc",
69
+ "output_tokens-asc",
70
+ "cache_read_tokens-desc",
71
+ "cache_read_tokens-asc",
72
+ "cache_creation_tokens-desc",
73
+ "cache_creation_tokens-asc",
74
+ "cost_usd-desc",
75
+ "cost_usd-asc",
76
+ ])
77
+ .describe("RequestLogOrderBy");
57
78
  export type RequestLogOrderBy = z.infer<typeof RequestLogOrderBy>;
58
- export const RequestLogOrderByLabel = { "id-desc": "ID최신순" };
79
+ export const RequestLogOrderByLabel = {
80
+ "id-desc": "ID최신순",
81
+ "id-asc": "ID오래된순",
82
+ "created_at-desc": "등록일시최신순",
83
+ "created_at-asc": "등록일시오래된순",
84
+ "ttft_ms-desc": "TTFT긴순",
85
+ "ttft_ms-asc": "TTFT짧은순",
86
+ "duration_ms-desc": "소요시간긴순",
87
+ "duration_ms-asc": "소요시간짧은순",
88
+ "input_tokens-desc": "입력토큰많은순",
89
+ "input_tokens-asc": "입력토큰적은순",
90
+ "output_tokens-desc": "출력토큰많은순",
91
+ "output_tokens-asc": "출력토큰적은순",
92
+ "cache_read_tokens-desc": "캐시읽기많은순",
93
+ "cache_read_tokens-asc": "캐시읽기적은순",
94
+ "cache_creation_tokens-desc": "캐시생성많은순",
95
+ "cache_creation_tokens-asc": "캐시생성적은순",
96
+ "cost_usd-desc": "비용높은순",
97
+ "cost_usd-asc": "비용낮은순",
98
+ };
59
99
  export const RequestLogSearchField = z
60
100
  .enum(["id", "token_name", "user_prompt"])
61
101
  .describe("RequestLogSearchField");
@@ -128,7 +128,10 @@ describe("TokenModel.deactivateIfActive", () => {
128
128
  it("deactivates in one statement that carries the last-token guard", async () => {
129
129
  const raw = mockKnex([{ rowCount: 1 }]);
130
130
 
131
- await expect(TokenModel.deactivateIfActive(7)).resolves.toBe(true);
131
+ await expect(TokenModel.deactivateIfActive(7)).resolves.toEqual({
132
+ deactivated: true,
133
+ keptAsLastActive: false,
134
+ });
132
135
  expect(raw).toHaveBeenCalledTimes(1);
133
136
  const sql = raw.mock.calls[0]![0] as string;
134
137
  expect(sql).toContain("UPDATE tokens SET active = false");
@@ -138,14 +141,21 @@ describe("TokenModel.deactivateIfActive", () => {
138
141
  it("returns false without a diagnostic read when the token is already inactive", async () => {
139
142
  const raw = mockKnex([{ rowCount: 0 }, { rows: [] }]);
140
143
 
141
- await expect(TokenModel.deactivateIfActive(7)).resolves.toBe(false);
144
+ await expect(TokenModel.deactivateIfActive(7)).resolves.toEqual({
145
+ deactivated: false,
146
+ keptAsLastActive: false,
147
+ });
142
148
  expect(raw).toHaveBeenCalledTimes(2);
143
149
  });
144
150
 
145
151
  it("refuses to deactivate the provider's last active token", async () => {
146
152
  const raw = mockKnex([{ rowCount: 0 }, { rows: [{ provider: "anthropic" }] }]);
147
153
 
148
- await expect(TokenModel.deactivateIfActive(7)).resolves.toBe(false);
154
+ // 마지막 활성 토큰은 살려두되, 호출부가 systemic 실패로 알릴 수 있게 구분해 알린다.
155
+ await expect(TokenModel.deactivateIfActive(7)).resolves.toEqual({
156
+ deactivated: false,
157
+ keptAsLastActive: true,
158
+ });
149
159
  expect(raw).toHaveBeenCalledTimes(2);
150
160
  });
151
161
  });
@@ -188,26 +188,17 @@ class TokenModelClass extends BaseModelClass<
188
188
  /**
189
189
  * 같은 계정의 기존 토큰을 지우고 새로 저장한다(로그인·재로그인 공통 경로).
190
190
  *
191
- * @returns 처음 들어온 계정인지 — 호출부의 신규 등록 알림 게이트. 재로그인은
192
- * 기존 토큰을 대체하는 것이라 알릴 사건이 아니다.
193
- *
194
- * provider 응답에 계정 식별자가 없으면 dedup 자체가 불가능하므로 경고만 남기고
195
- * 중복 제거 없이 저장한다(죽은 row 가 남는다). 이때는 기존 토큰 유무를 알 수 없어
196
- * 신규로 보지 않는다 — 재로그인을 신규로 잘못 알리는 편보다 조용한 편이 낫다.
191
+ * provider 응답에 계정 식별자가 없으면 dedup 자체가 불가능하므로 경고만 남기고
192
+ * 중복 제거 없이 저장한다(죽은 row 가 남는다).
197
193
  */
198
194
  async replaceByAccount(
199
195
  provider: string,
200
196
  accountId: string | undefined,
201
197
  saveParams: TokenSaveParams,
202
- ): Promise<{ isNew: boolean }> {
203
- let isNew = false;
198
+ ): Promise<void> {
204
199
  if (accountId) {
205
200
  const oldEntries = await this.findByAccountIdentifier("A", provider, accountId);
206
- if (oldEntries.length > 0) {
207
- await this.del(oldEntries.map((o) => o.id));
208
- } else {
209
- isNew = true;
210
- }
201
+ if (oldEntries.length > 0) await this.del(oldEntries.map((o) => o.id));
211
202
  } else {
212
203
  logger.warn(
213
204
  `${provider} login without account identifier: dedup skipped for ${saveParams.name ?? "unnamed"}`,
@@ -215,10 +206,16 @@ class TokenModelClass extends BaseModelClass<
215
206
  }
216
207
 
217
208
  await this.save([saveParams]);
218
- return { isNew };
219
209
  }
220
210
 
221
- async deactivateIfActive(id: number): Promise<boolean> {
211
+ /**
212
+ * @returns `deactivated` 는 이 호출이 실제로 비활성화를 수행했는지 — 호출부의 알림
213
+ * 게이트다. `keptAsLastActive` 는 마지막 활성 토큰이라 거부한 경우로, 사망 자체는
214
+ * 사실이지만 풀을 비우지 않으려고 살려둔 상태다(systemic 실패 신호).
215
+ */
216
+ async deactivateIfActive(
217
+ id: number,
218
+ ): Promise<{ deactivated: boolean; keptAsLastActive: boolean }> {
222
219
  const wdb = this.getPuri("w");
223
220
 
224
221
  // 활성 여부와 "마지막 남은 토큰인가"를 한 statement 안에서 판정한다. 두 조건을
@@ -231,7 +228,7 @@ class TokenModelClass extends BaseModelClass<
231
228
  WHERE peer.provider = tokens.provider AND peer.active) > 1`,
232
229
  [id],
233
230
  );
234
- if ((updated.rowCount ?? 0) > 0) return true;
231
+ if ((updated.rowCount ?? 0) > 0) return { deactivated: true, keptAsLastActive: false };
235
232
 
236
233
  // 갱신되지 않은 이유는 둘 중 하나다: 이미 비활성이거나(정상 경쟁 결과), 마지막
237
234
  // 활성 토큰이거나. 후자는 systemic 실패 신호라 남겨야 하므로 이때만 한 번 더 읽는다.
@@ -246,8 +243,9 @@ class TokenModelClass extends BaseModelClass<
246
243
  `refusing to auto-deactivate token ${id}: last active ${survivor.provider} token — ` +
247
244
  `systemic refresh failure suspected, keeping the pool non-empty`,
248
245
  );
246
+ return { deactivated: false, keptAsLastActive: true };
249
247
  }
250
- return false;
248
+ return { deactivated: false, keptAsLastActive: false };
251
249
  }
252
250
 
253
251
  @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
@@ -47,6 +47,9 @@ export default {
47
47
  "error.internalServerError": "Internal server error",
48
48
  "error.notFound": "Not found",
49
49
  "error.serviceUnavailable": "Service unavailable",
50
+ "qgrid.dispatcherFailed": (provider: string) => `${provider} dispatcher failed to initialize`,
51
+ "qgrid.dispatcherStarting": (provider: string) =>
52
+ `${provider} dispatcher is starting up. Please retry shortly`,
50
53
  "error.unauthorized": "Unauthorized",
51
54
  notFound: (name: string, id: number) => `${name} ID ${id} not found`,
52
55
  "validation.email": "Invalid email format",
@@ -46,6 +46,9 @@ export default {
46
46
  "error.internalServerError": "서버 오류가 발생했습니다",
47
47
  "error.notFound": "찾을 수 없습니다",
48
48
  "error.serviceUnavailable": "서비스를 사용할 수 없습니다",
49
+ "qgrid.dispatcherFailed": (provider: string) => `${provider} dispatcher 초기화에 실패했습니다`,
50
+ "qgrid.dispatcherStarting": (provider: string) =>
51
+ `${provider} dispatcher 기동 중입니다. 잠시 후 다시 시도해주세요`,
49
52
  "error.unauthorized": "인증이 필요합니다",
50
53
  "error.unknownSearchField": (field: string) => `구현되지 않은 검색 필드 ${field}`,
51
54
  notFound: (name: string, id: number) => `존재하지 않는 ${name} ID ${id}`,
@@ -240,6 +240,23 @@ const entityLabels = {
240
240
  "entity.RequestLog.tool_call_count": "tool call 횟수",
241
241
  "entity.RequestLog.is_image_generation": "이미지 생성 turn 여부 (quota 귀속용)",
242
242
  "enum.RequestLogOrderBy.id-desc": "ID최신순",
243
+ "enum.RequestLogOrderBy.id-asc": "ID오래된순",
244
+ "enum.RequestLogOrderBy.created_at-desc": "등록일시최신순",
245
+ "enum.RequestLogOrderBy.created_at-asc": "등록일시오래된순",
246
+ "enum.RequestLogOrderBy.ttft_ms-desc": "TTFT긴순",
247
+ "enum.RequestLogOrderBy.ttft_ms-asc": "TTFT짧은순",
248
+ "enum.RequestLogOrderBy.duration_ms-desc": "소요시간긴순",
249
+ "enum.RequestLogOrderBy.duration_ms-asc": "소요시간짧은순",
250
+ "enum.RequestLogOrderBy.input_tokens-desc": "입력토큰많은순",
251
+ "enum.RequestLogOrderBy.input_tokens-asc": "입력토큰적은순",
252
+ "enum.RequestLogOrderBy.output_tokens-desc": "출력토큰많은순",
253
+ "enum.RequestLogOrderBy.output_tokens-asc": "출력토큰적은순",
254
+ "enum.RequestLogOrderBy.cache_read_tokens-desc": "캐시읽기많은순",
255
+ "enum.RequestLogOrderBy.cache_read_tokens-asc": "캐시읽기적은순",
256
+ "enum.RequestLogOrderBy.cache_creation_tokens-desc": "캐시생성많은순",
257
+ "enum.RequestLogOrderBy.cache_creation_tokens-asc": "캐시생성적은순",
258
+ "enum.RequestLogOrderBy.cost_usd-desc": "비용높은순",
259
+ "enum.RequestLogOrderBy.cost_usd-asc": "비용낮은순",
243
260
  "enum.RequestLogSearchField.id": "ID",
244
261
  "enum.RequestLogSearchField.token_name": "토큰이름",
245
262
  "enum.RequestLogSearchField.user_prompt": "사용자 프롬프트",
@@ -0,0 +1,13 @@
1
+ import { type Knex } from "knex";
2
+
3
+ export async function up(knex: Knex): Promise<void> {
4
+ await knex.raw(
5
+ `CREATE INDEX request_logs_model_name_index ON request_logs USING btree(model_name ASC NULLS LAST);`,
6
+ );
7
+ }
8
+
9
+ export async function down(knex: Knex): Promise<void> {
10
+ await knex.schema.alterTable("request_logs", (table) => {
11
+ table.dropIndex(["model_name"], "request_logs_model_name_index");
12
+ });
13
+ }
@@ -0,0 +1,58 @@
1
+ import { type FastifyReply } from "fastify";
2
+ import {
3
+ BadRequestException,
4
+ InternalServerErrorException,
5
+ ServiceUnavailableException,
6
+ } from "sonamu";
7
+ import { describe, expect, it, vi } from "vitest";
8
+
9
+ import { handleServerError } from "./server-error-handler";
10
+
11
+ function fakeReply() {
12
+ const reply = {
13
+ header: vi.fn(),
14
+ status: vi.fn(),
15
+ send: vi.fn(),
16
+ };
17
+ reply.status.mockReturnValue(reply);
18
+ return reply as unknown as FastifyReply & typeof reply;
19
+ }
20
+
21
+ describe("handleServerError", () => {
22
+ it("Sonamu 예외의 statusCode 를 그대로 쓴다", () => {
23
+ const reply = fakeReply();
24
+
25
+ handleServerError(new BadRequestException("bad" as never), reply);
26
+
27
+ expect(reply.status).toHaveBeenCalledWith(400);
28
+ });
29
+
30
+ it("Sonamu 예외가 아니면 statusCode 를 신뢰하지 않고 500 으로 내린다", () => {
31
+ const reply = fakeReply();
32
+ // upstream fetch 오류처럼 statusCode 를 달고 오는 예외 — 그대로 에코하면 upstream 의
33
+ // 401 이 호출자 자신의 오류로 둔갑한다.
34
+ const upstream = Object.assign(new Error("upstream said 401"), { statusCode: 401 });
35
+
36
+ handleServerError(upstream, reply);
37
+
38
+ expect(reply.status).toHaveBeenCalledWith(500);
39
+ });
40
+
41
+ it("503 에는 Retry-After 를 붙여 재시도 시점을 알린다", () => {
42
+ const reply = fakeReply();
43
+
44
+ handleServerError(new ServiceUnavailableException("starting up" as never), reply);
45
+
46
+ expect(reply.status).toHaveBeenCalledWith(503);
47
+ expect(reply.header).toHaveBeenCalledWith("Retry-After", expect.any(String));
48
+ });
49
+
50
+ it("503 이 아닌 응답에는 Retry-After 를 붙이지 않는다", () => {
51
+ const reply = fakeReply();
52
+
53
+ handleServerError(new InternalServerErrorException("dead" as never), reply);
54
+
55
+ expect(reply.status).toHaveBeenCalledWith(500);
56
+ expect(reply.header).not.toHaveBeenCalled();
57
+ });
58
+ });
@@ -1,20 +1,31 @@
1
1
  import { getLogger } from "@logtape/logtape";
2
2
  import { type FastifyReply } from "fastify";
3
- import { isSoException } from "sonamu";
3
+ import { SoException } from "sonamu";
4
4
 
5
- // statusCode 를 신뢰하는 범위를 Sonamu 예외 계약(isSoException)으로 한정한다. qgrid 는 프록시라
6
- // upstream HTTP 오류(fetch/undici 류)도 statusCode 를 달고 나오는데, 그걸 duck-typing 으로
7
- // 그대로 에코하면 upstream 의 401/429 가 호출자 자신의 오류로 둔갑한다. Sonamu 예외가 아니면 500.
5
+ // dispatcher 기동은 dev0 기준 1~2분 걸린다(워커 25개 × spawn 간격). 그보다 짧게 잡으면
6
+ // 재시도가 같은 503 을 다시 받는다.
7
+ const RETRY_AFTER_SECONDS = "30";
8
+
9
+ // statusCode 를 신뢰하는 범위를 Sonamu 예외로 한정한다. qgrid 는 프록시라 upstream HTTP
10
+ // 오류(fetch/undici 류)도 statusCode 를 달고 나오는데, 그걸 그대로 에코하면 upstream 의
11
+ // 401/429 가 호출자 자신의 오류로 둔갑한다. Sonamu 예외가 아니면 500.
12
+ //
13
+ // sonamu 의 isSoException 은 `statusCode !== undefined` 만 보는 duck-typing 이라 바로 그
14
+ // upstream 예외를 통과시킨다. 여기서는 instanceof 로 실제 계약을 확인한다.
8
15
  export function handleServerError(error: Error, reply: FastifyReply): void {
9
16
  getLogger(["qgrid"]).error(`${error}`);
10
17
  const statusCode =
11
- isSoException(error) &&
18
+ error instanceof SoException &&
12
19
  Number.isInteger(error.statusCode) &&
13
20
  error.statusCode >= 400 &&
14
21
  error.statusCode <= 599
15
22
  ? error.statusCode
16
23
  : 500;
17
24
 
25
+ // 503 은 "지금은 아니지만 곧 된다"는 뜻이라 재시도 시점을 함께 준다. 값이 없으면
26
+ // 클라이언트는 재시도 간격을 스스로 정해야 하고, 대개 즉시 재시도해 부하만 키운다.
27
+ if (statusCode === 503) reply.header("Retry-After", RETRY_AFTER_SECONDS);
28
+
18
29
  reply.status(statusCode).send({
19
30
  name: error.name,
20
31
  message: error.message,
@@ -179,11 +179,15 @@ export default defineConfig({
179
179
 
180
180
  const started = await subscriber.start();
181
181
 
182
+ // 기동 상태를 남긴다 — HTTP 는 이미 열려 있어서, 준비 전 요청이 "잠시 후 되는지"
183
+ // "재시도해도 안 되는지"를 구분해 응답해야 한다(503 vs 500).
182
184
  try {
183
185
  const openaiDispatcher = new OpenAIDispatcher();
184
186
  await openaiDispatcher.start();
185
187
  QgridDispatcher.openaiDispatcher = openaiDispatcher;
188
+ QgridDispatcher.startupState.openai = "ready";
186
189
  } catch (e) {
190
+ QgridDispatcher.startupState.openai = "failed";
187
191
  log.warn(`openai dispatcher failed: ${(e as Error).message}`);
188
192
  }
189
193
 
@@ -191,7 +195,9 @@ export default defineConfig({
191
195
  const anthropicDispatcher = new AnthropicDispatcher();
192
196
  await anthropicDispatcher.start();
193
197
  QgridDispatcher.anthropicDispatcher = anthropicDispatcher;
198
+ QgridDispatcher.startupState.anthropic = "ready";
194
199
  } catch (e) {
200
+ QgridDispatcher.startupState.anthropic = "failed";
195
201
  log.warn(`anthropic dispatcher failed: ${(e as Error).message}`);
196
202
  }
197
203