8000 Drain shared Mac relay work during shutdown by hmmhmmhm · Pull Request #400 · hmmhmmhm/daiso-mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/dtryx-relay.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ node --max-old-space-size=128 --env-file=/absolute/path/dtryx.env \

현재 Mac 설치는 `~/Library/Application Support/DaisoRelay/dtryx-runtime`, `dtryx.env`, `dtryx-state`를 사용하고 `page.aka.daiso-dtryx` LaunchAgent로 관리한다. GUI 사용자 로그인 세션이 필요하다. Node 힙128MiB 제한은 전체 프로세스 RSS128MiB 보장이 아니다.

### LaunchAgent 종료 유예

`scripts/relay/install-macos.py`는 올리브영과 터널용입니다. 디트릭스 런타임을 설치하거나 갱신할 때는 `page.aka.daiso-dtryx`의 **스테이징 plist**에서 기존 `ExitTimeOut`을 정수 80초로 설정하고 검증합니다.

```sh
plutil -replace ExitTimeOut -integer 80 "$candidate_plist"
plutil -lint "$candidate_plist"
test "$(plutil -extract ExitTimeOut raw -expect integer "$candidate_plist")" = 80
```

검증한 런타임과 함께 이 plist를 등록합니다. 디스크의 plist만 고쳐도 현재 로드된 작업의 종료 유예가 바뀌지는 않습니다. 기존 런타임과 짧은 종료 유예가 적용된 첫 전환에서는 진행 중인 요청의 완료를 보장할 수 없습니다. 올리브영과 터널의 plist는 이 설정의 대상에서 제외합니다.

종료 신호를 받으면 새 요청을 막고 이미 받은 요청의 연결, 내부 처리, GS25 갱신과 세븐 Safari 정리를 최대 65초 기다립니다. 요청 처리 15초, Safari helper의 최대 45초, 종료 콜백 여유 5초를 반영한 값입니다. launchd의 80초는 미확인 상태를 기록하고 로그를 비울 여유를 줍니다. macOS에서 운영할 때는 이 LaunchAgent를 사용합니다.

대상 프로세스의 종료 이벤트가 `shutdown-drained`이면 추적한 로컬 작업이 모두 끝났습니다. 각 요청의 성공 여부는 해당 요청 결과에서 확인합니다. `shutdown-uncertain`이면 종료 코드는 1이며, 로그가 누락되거나 launchd가 프로세스를 강제 종료한 경우에도 정리가 확인되지 않은 상태로 처리합니다. 남아 있는 소유 창과 잠금은 해당 작업의 증거로 보존합니다. PID가 사라졌거나 포트가 닫혔다는 사실만으로 창 회수를 확인할 수 없습니다.

## Tunnel 경로
기존 `oy-relay.aka.page` Access 정책을 적용한 상태에서 기존 올리브영 규칙 앞에 다음 ingress를 배치한다.

Expand Down
2 changes: 2 additions & 0 deletions docs/gs25-auth-recovery-runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ launchctl kill SIGTERM gui/$(id -u)/page.aka.daiso-dtryx
# 아래 설치·검증을 마칠 때까지 kickstart하지 않는다.
```

[디트릭스 LaunchAgent 종료 유예](dtryx-relay.md#launchagent-종료-유예)를 적용한 버전에서는 해당 프로세스의 `shutdown-drained`와 종료를 확인한다. `shutdown-uncertain`, 완료 기록 누락 또는 강제 종료가 있으면 GS25 갱신과 세븐 창 정리 상태를 확인할 때까지 정상 종료로 기록하지 않는다. 비정상 종료 뒤 KeepAlive가 후속 프로세스를 띄울 수 있으므로 기존 PID의 종료만으로 세션 파일을 교체하지 않는다. 새 중계도 없는 상태를 확인한 뒤에만 다음 단계로 간다.

3. 종료된 상태에서 비공개 백업 디렉터리(0700)에 변경할 runtime 파일·`dtryx.env`·기존 GS 세션을 백업한다. 환경/세션 백업도 0600으로 유지한다. `quota.json`과 상태 디렉터리를 삭제·교체하지 않는다.
4. 세션을 목적 디렉터리의 **새 0600 임시 파일**로 쓴 뒤 `os.replace`/rename으로 `gs25-auth.json`에 교체한다. 내용은 세 필드만 저장한다. 그룹/다른 사용자 권한이 열린 파일은 중계가 거절한다.
5. `dtryx.env`의 `GS25_AUTH_SESSION_FILE`을 절대 경로로 설정한다. 공백이 있는 값은 따옴표로 감싼다. 환경 파일도 0600·원자 교체하고 나머지 변수는 보존한다. 세션 재발급만 필요하면 runtime·Worker는 다시 배포할 필요가 없다.
Expand Down
26 changes: 26 additions & 0 deletions scripts/relay/dtryx-drain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { AsyncLocalStorage } from 'node:async_hooks';

// A cancelled HTTP request can leave transport or file work running.
const scope = new AsyncLocalStorage<Set<Promise<unknown>>>();

export function trackRelayWork<T>(task: Promise<T>): Promise<T> {
const pending = scope.getStore();
if (pending && !pending.has(task)) {
pending.add(task);
const settled = () => { pending.delete(task); };
void task.then(settled, settled);
}
return task;
}

export function createRelayDrain() {
const pending = new Set<Promise<unknown>>();
return {
run<T>(work: () => Promise<T>): Promise<T> {
return scope.run(pending, () => trackRelayWork(work()));
},
async wait(): Promise<void> {
while (pending.size) await Promise.allSettled(pending);
},
};
}
102 changes: 74 additions & 28 deletions scripts/relay/dtryx-start.ts
10000
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ import { createGs25SessionTransport } from './gs25-session.js';
import { createJapanProductRelay } from './daiso-jp.js';
import { createCgvRelay } from './cgv.js';
import { createDtryxRelay } from './dtryx.js';
import { createRelayDrain } from './dtryx-drain.js';

// Allow 15 sec 8000 onds for an admitted request and 45 for its Safari helper, with callback margin.
// The Dtryx LaunchAgent allows 80 seconds so unresolved work can be recorded before termination.
const shutdownDeadlineMs = 65000;

let logger: ReturnType<typeof createRelayLogger> | undefined;
async function main() {
Expand All @@ -35,10 +40,13 @@ async function main() {
log.append({ stage: 'process', outcome: 'starting' });
const takeQuota = await createFileQuota(join(stateDir, 'quota.json'));
log.append({ stage: 'quota', outcome: 'snapshot', ...takeQuota.status() });
const drain = createRelayDrain();
let stopping = false;
let sevenCleanupUncertain = false;
let maintainAuthentication = async () => {};
const heartbeat = setInterval(() => {
log.append({ stage: 'process', outcome: 'heartbeat', ...takeQuota.status() });
void maintainAuthentication();
void drain.run(maintainAuthentication);
}, 60000);
heartbeat.unref();
let convenience: ((request: Request) => Promise<Response>) | undefined;
Expand Down Expand Up @@ -73,7 +81,6 @@ async function main() {
});
}
};
void maintainAuthentication();
}
const sevenExecutable = process.env.SEVEN_BROWSER_EXECUTABLE?.trim();
const sevenSession =
Expand All @@ -82,6 +89,7 @@ async function main() {
takeQuota: quota,
onEvent: (outcome) =>
convenienceLog!.append({ stage: 'session', operation: 'seven', outcome }),
onCleanupUncertain: () => { sevenCleanupUncertain = true; },
})
: sevenExecutable
? createSevenSessionTransport({
Expand Down Expand Up @@ -155,30 +163,44 @@ async function main() {
? cgvHandler(request)
: dtryxHandler(request);
const server = createServer(async (req, res) => {
const controller = new AbortController();
res.once('close', () => controller.abort());
try {
const response = await handler(
new Request(`http://127.0.0.1:${port}${req.url}`, {
method: req.method,
headers: req.headers as Record<string, string>,
signal: controller.signal,
body: req.method === 'GET' || req.method === 'HEAD' ? undefined : Readable.toWeb(req),
duplex: 'half',
} as RequestInit & { duplex: 'half' }),
);
res.writeHead(response.status, {
...Object.fromEntries(response.headers),
if (stopping) {
res.writeHead(503, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
Connection: 'close',
});
res.end(await response.text());
} catch {
log.append({ stage: 'server', outcome: 'error', status: 500 });
res.writeHead(500, { Connection: 'close' });
res.end('{"error":"Relay failure"}');
res.end('{"error":"Relay unavailable"}');
return;
}
await drain.run(async () => {
const controller = new AbortController();
res.once('close', () => controller.abort());
try {
const response = await handler(
new Request(`http://127.0.0.1:${port}${req.url}`, {
method: req.method,
headers: req.headers as Record<string, string>,
signal: controller.signal,
body: req.method === 'GET' || req.method === 'HEAD' ? undefined : Readable.toWeb(req),
duplex: 'half',
} as RequestInit & { duplex: 'half' }),
);
const body = await response.text();
if (res.destroyed) return;
res.writeHead(response.status, {
...Object.fromEntries(response.headers),
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
Connection: 'close',
});
res.end(body);
} catch {
log.append({ stage: 'server', outcome: 'error', status: 500 });
if (res.destroyed) return;
res.writeHead(500, { Connection: 'close' });
res.end('{"error":"Relay failure"}');
}
});
});
server.requestTimeout = 15000;
server.headersTimeout = 10000;
Expand All @@ -188,16 +210,40 @@ async function main() {
server.listen(port, '127.0.0.1', resolve);
});
console.log(`Dtryx relay ready on 127.0.0.1:${port}`);
const close = () => {
const close = async () => {
if (stopping) return;
stopping = true;
clearInterval(heartbeat);
log.append({ stage: 'process', outcome: 'stopping' });
void log.flush();
void convenienceLog?.flush();
server.close();
server.closeAllConnections();
const closed = new Promise<void>((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
});
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const deadline = new Promise<false>((resolve) => {
timer = setTimeout(() => resolve(false), shutdownDeadlineMs);
});
const drained = await Promise.race([
Promise.all([closed, drain.wait()]).then(() => true),
deadline,
]);
if (!drained || sevenCleanupUncertain) {
log.append({ stage: 'process', outcome: 'shutdown-uncertain' });
process.exitCode = 1;
} else {
log.append({ stage: 'process', outcome: 'shutdown-drained' });
}
} catch {
log.append({ stage: 'process', outcome: 'shutdown-uncertain' });
process.exitCode = 1;
} finally {
clearTimeout(timer);
await Promise.allSettled([log.flush(), convenienceLog?.flush()]);
}
};
process.once('SIGTERM', close);
process.once('SIGINT', close);
process.on('SIGTERM', close);
process.on('SIGINT', close);
void drain.run(maintainAuthentication);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main().catch(async () => {
Expand Down
3 changes: 2 additions & 1 deletion scripts/relay/gs25-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
import { readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
import { GS25_API } from '../../src/services/gs25/api.js';
import { abortable, readJson, RelayError } from './http-relay.js';
import { trackRelayWork } from './dtryx-drain.js';

interface Session {
accessToken: string;
Expand Down Expand Up @@ -168,7 +169,7 @@ export function createGs25SessionTransport(
throw new RelayError(502);
} finally {
clearTimeout(timer);
void unlink(temporary).catch(() => undefined);
void trackRelayWork(unlink(temporary)).catch(() => undefined);
}
}

Expand Down
3 changes: 2 additions & 1 deletion scripts/relay/http-relay.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { trackRelayWork } from './dtryx-drain.js';
import type { RelayQuota } from '../../src/utils/relayQuota.js';
import type { QuotaStatus } from './quota.js';
import type { SevenStockFailure } from '../../src/utils/sevenStockFailure.js';
Expand Down Expand Up @@ -73,7 +74,7 @@ const reply = (status: number, body: unknown, headers: Record<string, string> =
export function abortable<T>(task: Promise<T>, signal: AbortSignal): Promise<T> {
return new Promise((resolve, reject) => {
const abort = () => reject(new RelayError(499));
task.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
trackRelayWork(task).then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
if (signal.aborted) {
reject(new RelayError(499));
return;
Expand Down
25 changes: 15 additions & 10 deletions scripts/relay/safari-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export function createSafariLifecycle(
let active = false;
let calls = 0;
let uncertain = false;
let unconfirmedCleanup = false;
let child: ChildProcess | undefined;
let pending: Promise<unknown> | undefined;
let starting: Promise<void> | undefined;
Expand Down Expand Up @@ -62,16 +63,19 @@ export function createSafariLifecycle(
clearTimeout(hardStop);
child = undefined;
if (error || closed()) {
if (error && typeof stderr === 'string' && stderr.length <= 128) {
const line = stderr.endsWith('\n') ? stderr.slice(0, -1) : stderr;
const match = safariDiagnostic.exec(line);
if (match && (!match[3] || match[2] === 'failed')) {
const stage = match[1] as SafariFailureStage;
const cleanup = match[2] as SafariCleanupResult;
report(`safari-stage-${stage}`);
report(`safari-cleanup-${cleanup}`);
if (match[3]) report(`safari-cleanup-detail-${match[3] as SafariCleanupDetail}`);
}
const diagnostic = error && typeof stderr === 'string' && stderr.length <= 128
? safariDiagnostic.exec(stderr.endsWith('\n') ? stderr.slice(0, -1) : stderr)
: null;
if (diagnostic && (!diagnostic[3] || diagnostic[2] === 'failed')) {
const stage = diagnostic[1] as SafariFailureStage;
const cleanup = diagnostic[2] as SafariCleanupResult;
report(`safari-stage-${stage}`);
report(`safari-cleanup-${cleanup}`);
if (diagnostic[3]) report(`safari-cleanup-detail-${diagnostic[3] as SafariCleanupDetail}`);
// A preflight error may leave a previously owned session in place.
unconfirmedCleanup ||= cleanup !== 'success';
} else if (error) {
unconfirmedCleanup = true;
}
return reject(new BrowserRequestError('safari-helper'));
}
Expand Down Expand Up @@ -171,6 +175,7 @@ export function createSafariLifecycle(
child?.kill('SIGTERM');
await pending?.catch(() => undefined);
},
cleanupUncertain: () => unconfirmedCleanup,
status: () => ({
state,
transport: 'safari',
Expand Down
2 changes: 2 additions & 0 deletions scripts/relay/seven-safari.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export function createSevenSafariTransport(
fetcher?: typeof fetch;
takeQuota: HttpRelayOptions['takeQuota'];
onEvent?: (outcome: SevenSafariOutcome) => void;
onCleanupUncertain?: () => void;
},
) {
const fetcher = options.fetcher ?? fetch;
Expand Down Expand Up @@ -174,6 +175,7 @@ export function createSevenSafariTransport(
init?.signal?.removeEventListener('abort', abort);
try {
await lifecycle.close();
if (lifecycle.cleanupUncertain()) options.onCleanupUncertain?.();
} finally {
if (state === 'preparing') state = previousState;
}
Expand Down
47 changes: 47 additions & 0 deletions tests/relay/dtryx-drain.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { EventEmitter } from 'node:events';
import { expect, it, vi } from 'vitest';
import { abortable } from '../../scripts/relay/http-relay.js';
import { createRelayDrain } from '../../scripts/relay/dtryx-drain.js';

it('waits for the admitted operation even after its HTTP response and abortable wrapper settle', async () => {
const drain = createRelayDrain();
const underlying = Promise.withResolvers<void>();
const response = new EventEmitter();
const controller = new AbortController();
const finished = new Promise<void>((resolve) => response.once('close', resolve));
const reply = drain.run(async () => {
await abortable(underlying.promise, controller.signal).catch(() => undefined);
await finished;
});
controller.abort();
await Promise.resolve();
response.emit('close');
await reply;
const done = vi.fn();
const stopping = drain.wait().then(done);
await Promise.resolve();
expect(done).not.toHaveBeenCalled();
underlying.resolve();
await stopping;
expect(done).toHaveBeenCalledOnce();
});

it('includes work started by an admitted operation while the server is draining', async () => {
const drain = createRelayDrain();
const admitted = Promise.withResolvers<void>();
const nested = Promise.withResolvers<void>();
await drain.run(async () => {
await abortable(admitted.promise.then(() => {
void abortable(nested.promise, AbortSignal.abort()).catch(() => undefined);
}), AbortSignal.abort()).catch(() => undefined);
});
let completed = false;
const stopping = drain.wait().then(() => { completed = true; });
admitted.resolve();
await admitted.promise;
await Promise.resolve();
expect(completed).toBe(false);
nested.resolve();
await stopping;
expect(completed).toBe(true);
});
Loading
Loading
0