File size: 10,796 Bytes
d5de68a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import csv
import re
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, List
# 确保从任何位置执行都能 import app.*
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from dotenv import load_dotenv
from app.config.settings import Settings
from app.core.context import RunContext
from app.core.logger import JsonlLogger
from app.core.http_client import HttpClient
from app.clients.airops_web_client import AirOpsWebClient
from app.clients.airops_api_client import AirOpsApiClient
from app.clients.mailhub_client import build_mailhub_client
from app.services.registration_service import RegistrationService
from app.services.verification_service import VerificationService
from app.services.workspace_service import WorkspaceService
from app.services.oauth_service import OAuthService
from app.services.app_execution_service import AppExecutionService
from app.flows.register_bootstrap_flow import RegisterBootstrapFlow
from app.flows.full_flow import FullFlow
from app.integrations.account_store import AccountStore
from app.integrations.registration_email_verification_flow import RegistrationEmailVerificationFlow
from app.integrations.registration_failure_classifier import classify_registration_error
from app.integrations.registration_retry_policy import RegistrationRetryPolicy
def parse_args():
parser = argparse.ArgumentParser(description="Batch register accounts from email list.")
parser.add_argument("--input", required=True, help="Email list file path. Supports: one email per line, or email,password.")
parser.add_argument("--output", default="", help="CSV output path. Default: data/batch_register_result_<ts>.csv")
parser.add_argument("--with-chat-test", action="store_true", help="After bootstrap, run one chat test and require success.")
parser.add_argument("--sleep-sec", type=float, default=0.0, help="Sleep between accounts.")
parser.add_argument("--limit", type=int, default=0, help="Max rows to process. 0 means all.")
parser.add_argument("--skip-ready", action="store_true", help="Skip emails already in ready/oauth_ok/verified.")
return parser.parse_args()
def is_valid_email(email: str) -> bool:
return bool(re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", email or ""))
def read_accounts(path: Path) -> List[Dict[str, str]]:
rows: List[Dict[str, str]] = []
for i, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
line = raw.strip().lstrip("\ufeff")
if not line or line.startswith("#"):
continue
if i == 1 and line.lower().startswith("email"):
continue
if "," in line:
email, password = line.split(",", 1)
elif "\t" in line:
email, password = line.split("\t", 1)
else:
email, password = line, ""
rows.append({"line": str(i), "email": email.strip(), "password": password.strip()})
return rows
def build_flow_components(settings: Settings, email: str, password: str, account_store: AccountStore, log: JsonlLogger):
http = HttpClient(settings.base_url, timeout=settings.request_timeout)
web = AirOpsWebClient(http)
api = AirOpsApiClient(http)
reg = RegistrationService(web)
if not password:
password = reg.gen_password(email)
ctx = RunContext(email=email, password=password)
account_store.upsert(email=ctx.email, password=ctx.password, status="registering")
mail_client = build_mailhub_client(
settings.mailhub_base_url,
settings.mailhub_api_key,
settings.mailhub_password,
timeout=settings.mailhub_timeout_sec,
)
mail_flow = RegistrationEmailVerificationFlow(mail_client)
retry = RegistrationRetryPolicy(
flow=mail_flow,
max_wait_sec=settings.mail_verify_max_wait_sec,
initial_interval_sec=settings.mail_verify_initial_interval_sec,
backoff_step_sec=settings.mail_verify_backoff_step_sec,
max_interval_sec=settings.mail_verify_max_interval_sec,
)
verify = VerificationService(web, retry)
ws = WorkspaceService(api, ctx)
oauth = OAuthService(api, ctx, settings)
app_exec = AppExecutionService(api, ctx, settings)
bootstrap = RegisterBootstrapFlow(log, ctx, reg, verify, web, api, ws, oauth, account_store=account_store)
full = FullFlow(log, bootstrap, app_exec, ctx=ctx, account_store=account_store)
return ctx, bootstrap, full
def run_one(settings: Settings, email: str, password: str, account_store: AccountStore, log: JsonlLogger, with_chat_test: bool):
ctx, bootstrap, full = build_flow_components(settings, email, password, account_store, log)
if with_chat_test:
messages = [
{"role": "system", "content": "", "id": "system"},
{"role": "user", "content": "你好,做个自我介绍", "id": "u1"},
]
final = full.run(messages)
status = (final or {}).get("status")
if status != "success":
raise RuntimeError(f"execution_status={status}")
return ctx, "ready", ""
bootstrap.run()
row = account_store.get_by_email(ctx.email) or {}
status = str(row.get("status") or "verified")
return ctx, status, ""
def write_results_csv(path: Path, rows: List[Dict[str, str]]):
path.parent.mkdir(parents=True, exist_ok=True)
fields = [
"line",
"email",
"status",
"retryable",
"failure_code",
"reason",
"workspace_id",
"duration_sec",
"at",
]
with path.open("w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
for row in rows:
writer.writerow(row)
def main():
args = parse_args()
load_dotenv(dotenv_path=PROJECT_ROOT / ".env")
settings = Settings()
account_store = AccountStore(settings.account_store_path)
input_path = Path(args.input)
if not input_path.exists():
raise FileNotFoundError(f"input not found: {input_path}")
if args.output:
output_path = Path(args.output)
else:
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
output_path = PROJECT_ROOT / "data" / f"batch_register_result_{ts}.csv"
log = JsonlLogger(f"run_batch_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.jsonl")
rows = read_accounts(input_path)
if args.limit and args.limit > 0:
rows = rows[: args.limit]
if not rows:
print("[INFO] no rows to process.")
return
result_rows: List[Dict[str, str]] = []
ok = 0
failed = 0
skipped = 0
for idx, row in enumerate(rows, start=1):
email = row["email"]
password = row["password"]
line_no = row["line"]
print(f"\n[{idx}/{len(rows)}] email={email}")
if not is_valid_email(email):
failed += 1
result_rows.append(
{
"line": line_no,
"email": email,
"status": "failed_permanent",
"retryable": "False",
"failure_code": "invalid_email_format",
"reason": "invalid email format",
"workspace_id": "",
"duration_sec": "0.00",
"at": datetime.utcnow().isoformat(),
}
)
continue
if args.skip_ready:
old = account_store.get_by_email(email) or {}
if old.get("status") in ("ready", "oauth_ok", "verified"):
skipped += 1
result_rows.append(
{
"line": line_no,
"email": email,
"status": "skipped_ready",
"retryable": "",
"failure_code": "",
"reason": "",
"workspace_id": str(old.get("workspace_id") or ""),
"duration_sec": "0.00",
"at": datetime.utcnow().isoformat(),
}
)
print("[skip] already ready-like status")
continue
start = time.time()
try:
ctx, status, _ = run_one(settings, email, password, account_store, log, with_chat_test=bool(args.with_chat_test))
ok += 1
result_rows.append(
{
"line": line_no,
"email": email,
"status": status,
"retryable": "",
"failure_code": "",
"reason": "",
"workspace_id": str(ctx.workspace_id or ""),
"duration_sec": f"{time.time() - start:.2f}",
"at": datetime.utcnow().isoformat(),
}
)
print(f"[ok] status={status} workspace_id={ctx.workspace_id}")
except Exception as e:
failed += 1
cls = classify_registration_error(e)
ws_id = ""
prev = account_store.get_by_email(email) or {}
if prev.get("workspace_id"):
ws_id = str(prev.get("workspace_id"))
account_store.upsert(
email=email,
password=password or str(prev.get("password") or ""),
status=cls["status"],
workspace_id=ws_id or None,
last_error=cls["reason"],
failure_code=cls["failure_code"],
retryable=cls["retryable"],
)
result_rows.append(
{
"line": line_no,
"email": email,
"status": cls["status"],
"retryable": str(cls["retryable"]),
"failure_code": cls["failure_code"],
"reason": cls["reason"],
"workspace_id": ws_id,
"duration_sec": f"{time.time() - start:.2f}",
"at": datetime.utcnow().isoformat(),
}
)
print(
f"[failed] status={cls['status']} retryable={cls['retryable']} "
f"code={cls['failure_code']} reason={cls['reason']}"
)
if args.sleep_sec > 0:
time.sleep(args.sleep_sec)
write_results_csv(output_path, result_rows)
print("\n=== BATCH DONE ===")
print(f"total={len(rows)} ok={ok} failed={failed} skipped={skipped}")
print(f"result_csv={output_path}")
if __name__ == "__main__":
main()
|