### Start Mock Server Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md Navigate to the test directory and run the mock server script. It uses non-privileged ports and automatically generates a self-signed certificate on first run. Press Ctrl+C to stop. ```bash cd AlicloudHttpDNSTests/Network python3 mock_server.py ``` -------------------------------- ### Example: Combined Global and Service-Level Logging with Custom Handler Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md This comprehensive example demonstrates enabling global logging with HttpdnsLog and setting a custom logger for a specific HttpDnsService instance, all within the DEBUG build configuration. It initializes the service and configures logging for both levels. ```objc @interface AppDelegate () @property (nonatomic, strong) HttpDnsService *httpdnsService; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 初始化HTTPDNS self.httpdnsService = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; // 只在DEBUG模式启用日志 #ifdef DEBUG [HttpdnsLog enableLog]; // 启用全局日志 // 同时设置自定义logger用于服务实例 [self.httpdnsService setLogHandler:[[CustomLogger alloc] init]]; [self.httpdnsService setLogEnabled:YES]; #endif return YES; } @end ``` -------------------------------- ### Example: Runtime Log Toggle with UI Switch Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md This example shows how to implement a UI switch in a view controller to dynamically enable or disable both global HTTPDNS logging and service-level logging at runtime. It updates the switch's state based on the current logging status. ```objc @interface DebugViewController : UITableViewController @property (nonatomic, strong) HttpDnsService *service; @end @implementation DebugViewController - (void)viewDidLoad { [super viewDidLoad]; // 添加日志开关控制 UISwitch *logSwitch = [[UISwitch alloc] init]; [logSwitch addTarget:self action:@selector(toggleLog:) forControlEvents:UIControlEventValueChanged]; logSwitch.on = [HttpdnsLog isEnabled]; UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:logSwitch]; self.navigationItem.rightBarButtonItem = item; } - (void)toggleLog:(UISwitch *)sender { if (sender.on) { [HttpdnsLog enableLog]; [self.service setLogEnabled:YES]; } else { [HttpdnsLog disableLog]; [self.service setLogEnabled:NO]; } } @end ``` -------------------------------- ### Example: Enable and Use SDK Logging Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Demonstrates enabling global SDK logging using HttpdnsLog, then initializing HttpDnsService and performing a resolution. Logs will be output during the resolution process. Finally, it shows how to disable logging. ```objc // 启用SDK日志 [HttpdnsLog enableLog]; // SDK此后输出日志到默认位置(Xcode控制台或系统日志) HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; HttpdnsResult *result = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; // 此时SDK会输出解析过程中的日志 // 禁用日志 [HttpdnsLog disableLog]; ``` -------------------------------- ### Install OpenSSL Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md If the 'openssl' command is not found, install it using your system's package manager. ```bash # macOS (通常已预装) brew install openssl # Ubuntu/Debian sudo apt-get install openssl # CentOS/RHEL sudo yum install openssl ``` -------------------------------- ### Example: Enable Service-Level Logging with Custom Handler Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Shows how to enable logging for a specific HttpDnsService instance and set a custom log handler for its output. Logs will be directed through the custom handler during resolution. ```objc HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; // 启用此实例的日志 [service setLogEnabled:YES]; // 使用自定义日志处理器 [service setLogHandler:[[MyLogger alloc] init]]; // 进行解析操作,日志将通过自定义handler输出 HttpdnsResult *result = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; // 禁用此实例的日志 [service setLogEnabled:NO]; ``` -------------------------------- ### Example: Conditional Logging in Application Launch Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md This snippet demonstrates how to conditionally enable or disable SDK logging based on the build environment (DEBUG vs. Release) during application launch. It also shows the initialization of the HttpDnsService. ```objc - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { #ifdef DEBUG // 开发调试时启用日志 [HttpdnsLog enableLog]; #else // 生产环境禁用日志 [HttpdnsLog disableLog]; #endif // 初始化HTTPDNS服务 HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; return YES; } ``` -------------------------------- ### Example: Conditionally Enable Logging Based on User Defaults Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md This example shows how to enable or disable HTTPDNS logging dynamically based on a boolean value stored in NSUserDefaults, allowing for runtime configuration of logging behavior. ```objc - (void)setupHttpDnsLogging { // 根据配置条件启用日志 BOOL shouldLogHttpdns = [[NSUserDefaults standardUserDefaults] boolForKey:@"httpdns_debug_log"]; if (shouldLogHttpdns) { [HttpdnsLog enableLog]; } else { [HttpdnsLog disableLog]; } } ``` -------------------------------- ### Enable Logging and Get Session ID Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Enable global logging and retrieve a session ID for a specific HTTPDNS service instance. This session ID is useful for correlating logs with support requests. ```Objective-C [HttpdnsLog enableLog]; HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; NSString *sessionId = [service getSessionId]; NSLog(@"HTTPDNS SessionId: %@", sessionId); HttpdnsResult *result = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; // 使用sessionId和结果联系技术支持 ``` -------------------------------- ### CREATING to IN_USE Transition Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Handles the transition of a new connection from the CREATING state to the IN_USE state. This occurs when a new connection is created, successfully opened, and added to the pool. ```objc newConnection.inUse = YES; newConnection.lastUsedDate = now; [pool addObject:newConnection]; // 加入池 ``` -------------------------------- ### 构建脚本基本用法 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/ios-xcframework-build-script/README.md 展示了 Workspace 和 Project 模式下构建脚本的基本调用格式。 ```bash # Workspace 模式 ./build.sh framework_id framework_name build_config build_dir [workspace_name] # Project 模式 ./build_proj.sh framework_id framework_name build_config build_dir [project_name] ``` -------------------------------- ### 构建脚本使用示例 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/ios-xcframework-build-script/README.md 针对不同场景(如名称相同、名称不同、多 SDK 构建、Project 模式)的脚本调用示例。 ```bash ./build.sh MySDK_1.0.0 MySDK Release /Users/developer/output ``` ```bash ./build.sh MySDK_1.0.0 MySDK Release /Users/developer/output MyProject ``` ```bash # 构建第一个 SDK ./build.sh SDK1_1.0.0 SDK1 Release /Users/developer/output SharedWorkspace # 构建第二个 SDK ./build.sh SDK2_1.0.0 SDK2 Release /Users/developer/output SharedWorkspace ``` ```bash ./build_proj.sh MySDK_1.0.0 MySDK Release /Users/developer/output MyProject ``` -------------------------------- ### 运行 Xcode 测试命令 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/README.md 使用 xcodebuild 命令行工具执行单元测试、集成测试或单个测试用例。 ```bash xcodebuild test \ -workspace AlicloudHttpDNS.xcworkspace \ -scheme AlicloudHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientTests ``` ```bash xcodebuild test \ -workspace AlicloudHttpDNS.xcworkspace \ -scheme AlicloudHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests ``` ```bash xcodebuild test \ -workspace AlicloudHttpDNS.xcworkspace \ -scheme AlicloudHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientTests/testParseHTTPHeaders_ValidResponse_Success ``` -------------------------------- ### IN_USE to IDLE Transition (Normal Return) Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Handles the normal return of a connection from the IN_USE state to the IDLE state. It ensures the connection is not invalidated and is added back to the pool if not already present, followed by pruning the pool. ```objc if (shouldClose || connection.isInvalidated) { // → INVALIDATED (见#4) } else { connection.inUse = NO; connection.lastUsedDate = now; if (![pool containsObject:connection]) { [pool addObject:connection]; // 防止双重添加 } [self pruneConnectionPool:pool referenceDate:now]; } ``` -------------------------------- ### 脚本权限设置 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/ios-xcframework-build-script/README.md 解决执行权限问题的命令。 ```bash chmod +x build.sh ``` -------------------------------- ### IDLE to IN_USE Transition (Connection Reuse) Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Manages the reuse of an idle connection. It iterates through the pool to find an available and viable connection, marking it as in use and updating its last used date. ```objc for (HttpdnsNWReusableConnection *candidate in pool) { if (!candidate.inUse && [candidate isViable]) { candidate.inUse = YES; candidate.lastUsedDate = now; connection = candidate; break; } } ``` -------------------------------- ### Trace Network Issues with Logs Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Enable logging and perform a host resolution to observe network-related logs. If resolution fails, check the SDK logs for detailed error messages such as timeouts or DNS failures. ```Objective-C [HttpdnsLog enableLog]; // 执行解析,观察日志输出 HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; HttpdnsResult *result = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; if (!result) { // 查看日志中的错误信息,如超时、DNS failure等 NSLog(@"Resolution failed, check logs above for details"); } ``` -------------------------------- ### CI/CD 集成示例 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/ios-xcframework-build-script/README.md 将构建脚本集成到 CI/CD 流程中的完整 Bash 脚本示例。 ```bash #!/bin/bash print_info() { echo -e "\033[32m[INFO]\033[0m $1" } print_error() { echo -e "\033[31m[ERROR]\033[0m $1" } # 设置构建参数 FRAMEWORK_ID="MySDK_$(date +%Y%m%d_%H%M%S)" FRAMEWORK_NAME="MySDK" BUILD_CONFIG="Release" BUILD_DIR="/tmp/build" WORKSPACE_NAME="MyProject" print_info "开始构建 XCFramework..." # 清理并创建构建目录 rm -rf Build && mkdir Build # 执行构建(从项目根目录执行) sh ios-xcframework-build-script/build.sh $FRAMEWORK_ID $FRAMEWORK_NAME $BUILD_CONFIG $BUILD_DIR $WORKSPACE_NAME if [[ $? -eq 0 ]]; then print_info "$FRAMEWORK_NAME XCFramework 构建完成!" print_info "Framework ID: $FRAMEWORK_ID" print_info "构建目录: $BUILD_DIR" else print_error "$FRAMEWORK_NAME XCFramework 构建失败!" exit 1 fi ``` -------------------------------- ### Verify Cache Behavior with Logs Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Enable logging and persistent cache. Observe logs for network requests on the first resolution and cache hits on subsequent resolutions for the same host. ```Objective-C [HttpdnsLog enableLog]; HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; [service setPersistentCacheIPEnabled:YES]; // 第一次调用,应该会看到网络请求日志 HttpdnsResult *result1 = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; // 第二次调用,应该看到缓存命中日志 HttpdnsResult *result2 = [service resolveHostSync:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto]; ``` -------------------------------- ### Run Integration Tests Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md Execute integration tests using xcodebuild. You can run all tests or specify a single test case. Ensure you are in the project's root directory. ```bash cd ~/Project/iOS/alicloud-ios-sdk-httpdns xcodebuild test \ -workspace AlicloudHttpDNS.xcworkspace \ -scheme AlicloudHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests ``` ```bash xcodebuild test \ -workspace AlicloudHttpDNS.xcworkspace \ -scheme AlicloudHttpDNSTests \ -destination 'platform=iOS Simulator,name=iPhone 15' \ -only-testing:AlicloudHttpDNSTests/HttpdnsNWHTTPClientIntegrationTests/testConcurrency_ParallelRequestsSameHost_AllSucceed ``` -------------------------------- ### Enable SDK Logging Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Call this method to enable the SDK's internal log output. Logs will be directed to the Xcode console or system log. ```objc + (void)enableLog; ``` -------------------------------- ### HttpdnsNWHTTPClientTestHelper 辅助工具 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/README.md 提供用于构造 HTTP 响应、处理 Chunked 编码及生成测试数据的工具方法。 ```objc // 构造标准 HTTP 响应 + (NSData *)createHTTPResponseWithStatus:(NSInteger)statusCode statusText:(NSString *)statusText headers:(NSDictionary *)headers body:(NSData *)body; // 构造 chunked 响应 + (NSData *)createChunkedHTTPResponseWithStatus:(NSInteger)statusCode headers:(NSDictionary *)headers chunks:(NSArray *)chunks; ``` ```objc + (NSData *)encodeChunk:(NSData *)data; + (NSData *)encodeLastChunk; ``` ```objc + (NSData *)randomDataWithSize:(NSUInteger)size; + (NSData *)jsonBodyWithDictionary:(NSDictionary *)dictionary; ``` -------------------------------- ### State Transition Sequence Verification Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Verifies the sequence of state changes from creation to reuse. ```objc // 验证转换序列 [client resetPoolStatistics]; // CREATING → IN_USE response1 = [client performRequest...]; XCTAssertEqual(creationCount, 1); // IN_USE → IDLE [NSThread sleepForTimeInterval:0.5]; XCTAssertEqual(poolCount, 1); // IDLE → IN_USE (reuse) response2 = [client performRequest...]; XCTAssertEqual(reuseCount, 1); ``` -------------------------------- ### Enable Debug Logging in Mock Server Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md Uncomment the `log_message` method in `mock_server.py` to enable detailed logging for debugging purposes. ```python def log_message(self, format, *args): print(f"[{self.address_string()}] {format % args}") ``` -------------------------------- ### 构建输出目录结构 Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/ios-xcframework-build-script/README.md 构建成功后生成的目录结构示意。 ```text build_dir/ ├── framework_id.zip # 打包的 ZIP 文件 └── framework_id/ # Framework 目录 └── framework_name.xcframework/ # XCFramework 文件 ├── ios-arm64/ # iOS 设备端 └── ios-arm64_x86_64-simulator/ # iOS 模拟器端 ``` -------------------------------- ### enableLog Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Enables the SDK's internal log output. Once enabled, the SDK will output internal log information to the default location (Xcode console or system log). ```APIDOC ## enableLog ### Description Enables the SDK's internal log output. Once enabled, the SDK will output internal log information. ### Method `+ (void)enableLog;` ### Parameters This method takes no parameters. ### Response This method returns void. ### Example ```objc [HttpdnsLog enableLog]; ``` ``` -------------------------------- ### Find Process Using Port Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md If a port is already in use, use these commands to find the process ID (PID) and then terminate it using 'sudo kill -9 '. ```bash sudo lsof -i :80 sudo lsof -i :443 ``` -------------------------------- ### Global and Service-Specific Logging Configuration Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Configure logging infrastructure globally using `[HttpdnsLog enableLog]` and then enable/disable logging for a specific `HttpDnsService` instance using `setLogEnabled:`. A custom logger can also be assigned to a service instance. ```Objective-C // 全局启用日志基础设施 [HttpdnsLog enableLog]; // 为特定service实例配置日志处理 HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; [service setLogHandler:[[CustomLogger alloc] init]]; // 自定义处理 [service setLogEnabled:YES]; // 启用此实例的日志 // 结果:此service的日志将通过CustomLogger处理 ``` -------------------------------- ### Return Connection to Pool Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Logic for returning a connection to a specific pool key, noting potential for pool contamination if the key is incorrect. ```objc - (void)returnConnection:(HttpdnsNWReusableConnection *)connection forKey:(NSString *)key shouldClose:(BOOL)shouldClose { // ... NSMutableArray *pool = self.connectionPool[key]; // 会添加到错误的池! } ``` -------------------------------- ### Direct State Check Verification Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Basic assertions to verify connection state properties and pool counts. ```objc // 验证状态属性 XCTAssertTrue(connection.inUse); XCTAssertFalse(connection.isInvalidated); XCTAssertEqual([poolCount], expectedCount); ``` -------------------------------- ### Handling Stale Connections in Pool Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Illustrates the current code's behavior when encountering stale connections in the pool during dequeue operations. It checks `isViable` to reuse only valid connections, otherwise creating a new one. This highlights a potential risk if `isViable` checks are not comprehensive. ```objc for (HttpdnsNWReusableConnection *candidate in pool) { if (!candidate.inUse && [candidate isViable]) { // ← isViable 检查 // 只复用有效连接 } } // 如果所有连接都 !isViable,会创建新连接 ``` -------------------------------- ### Conditional Logging for Debug and Release Builds Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Conditionally enable logging for DEBUG builds and disable it for RELEASE builds to optimize performance in production environments. This is a common best practice for managing SDK logging. ```Objective-C #ifdef DEBUG [HttpdnsLog enableLog]; #else [HttpdnsLog disableLog]; #endif ``` -------------------------------- ### Add New Endpoint to Mock Server Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md To add a new endpoint, modify the `do_GET` method in `mock_server.py` and implement a handler function for your custom endpoint. ```python def do_GET(self): path = urlparse(self.path).path if path == '/your-new-endpoint': self._handle_your_endpoint() # ... 其他 endpoints def _handle_your_endpoint(self): """处理自定义 endpoint""" data = {'custom': 'data'} self._send_json(200, data) ``` -------------------------------- ### Test Case: Verifying Pool State After Single Timeout Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md This test case initiates a request with a short timeout to simulate a timeout scenario. It then asserts that the timed-out connection is removed from the pool and verifies overall connection counts. ```Objective-C [client resetPoolStatistics]; // 发起超时请求 NSError *error = nil; HttpdnsNWHTTPClientResponse *response = [client performRequestWithURLString:@"http://127.0.0.1:11080/delay/10" userAgent:@"TimeoutTest" timeout:1.0 error:&error]; XCTAssertNil(response); XCTAssertNotNil(error); // 验证池状态 NSString *poolKey = @"127.0.0.1:11080:tcp"; XCTAssertEqual([client connectionPoolCountForKey:poolKey], 0, @"Timed-out connection should be removed"); XCTAssertEqual([client totalConnectionCount], 0, @"No connections should remain"); XCTAssertEqual(client.connectionCreationCount, 1, @"Should have created 1 connection"); XCTAssertEqual(client.connectionReuseCount, 0, @"No reuse for timed-out connection"); ``` -------------------------------- ### Handle Connection Open Failure Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Invalidates and discards a connection if it fails to open within the timeout period. ```objc if (![newConnection openWithTimeout:timeout error:error]) { [newConnection invalidate]; // ← 立即失效 return nil; // ← 不加入池 } ``` -------------------------------- ### IN_USE/IDLE to INVALIDATED Transition Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Handles the invalidation of a connection, moving it to the INVALIDATED state. This is triggered by conditions like `shouldClose` being true or the connection already being marked as invalidated. ```objc if (shouldClose || connection.isInvalidated) { [connection invalidate]; [pool removeObject:connection]; } ``` -------------------------------- ### Modify Mock Server Ports Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/MOCK_SERVER.md If ports are occupied, you can modify the mock_server.py script to use different ports. Remember to update the test code URLs accordingly. ```python # 修改端口号(同时需要更新测试代码中的 URL) run_http_server(port=8080) run_https_server(port=8443) ``` -------------------------------- ### Test Case for Stale Connection Scenario Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md A placeholder for a test case designed to verify the handling of stale connections within the pool. This test aims to ensure that the system correctly skips stale connections and proceeds to create a new one when necessary. ```objc testStateTransition_StaleConnectionInPool_SkipsAndCreatesNew ``` -------------------------------- ### HttpdnsNWHTTPClient.m: Timeout Handling Logic Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md This snippet shows the timeout handling flow within HttpdnsNWHTTPClient.m. If a raw response is not received, the connection is returned to the pool and marked for closure. ```Objective-C if (!rawResponse) { [self returnConnection:connection forKey:poolKey shouldClose:YES]; // 返回 nil,error 设置 } ``` -------------------------------- ### Prevent Double Return of Connections Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Checks if a connection is already in the pool before adding it to prevent duplicate entries. ```objc if (![pool containsObject:connection]) { [pool addObject:connection]; // ← 防止重复添加 } ``` -------------------------------- ### Connection State Properties Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Defines the properties that represent the state of a reusable connection within the pool: last used date, in-use status, and invalidated status. ```objc @property (nonatomic, strong) NSDate *lastUsedDate; // 最后使用时间 @property (nonatomic, assign) BOOL inUse; // 是否正在被使用 @property (nonatomic, assign, getter=isInvalidated, readonly) BOOL invalidated; // 是否已失效 ``` -------------------------------- ### Custom Log Level Control Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Implement a custom logger to selectively enable or disable logging for different levels (DEBUG, INFO, WARN, ERROR). This allows fine-grained control over log verbosity. The default configuration logs only WARN and ERROR messages. ```Objective-C @interface SelectiveLogger : NSObject @property (nonatomic, assign) BOOL logDebug; @property (nonatomic, assign) BOOL logInfo; @property (nonatomic, assign) BOOL logWarn; @property (nonatomic, assign) BOOL logError; @end @implementation SelectiveLogger - (instancetype)init { self = [super init]; if (self) { // 默认只记录WARN和ERROR _logDebug = NO; _logInfo = NO; _logWarn = YES; _logError = YES; } return self; } - (void)log:(NSString *)logStr { BOOL shouldLog = NO; if ([logStr containsString:@"[DEBUG]"] && self.logDebug) { shouldLog = YES; } else if ([logStr containsString:@"[INFO]"] && self.logInfo) { shouldLog = YES; } else if ([logStr containsString:@"[WARN]"] && self.logWarn) { shouldLog = YES; } else if ([logStr containsString:@"[ERROR]"] && self.logError) { shouldLog = YES; } if (shouldLog) { NSLog(@"[HTTPDNS] %@", logStr); } } @end // 使用 SelectiveLogger *logger = [[SelectiveLogger alloc] init]; logger.logDebug = YES; logger.logInfo = YES; logger.logWarn = YES; logger.logError = YES; HttpDnsService *service = [[HttpDnsService alloc] initWithAccountID:1000000 secretKey:@"secret"]; [service setLogHandler:logger]; [service setLogEnabled:YES]; ``` -------------------------------- ### Test Requirement for Error During Use Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying connection invalidation on error. ```objc testStateTransition_ErrorDuringUse_Invalidated ``` -------------------------------- ### Pool Invariant Verification Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Iterates through all connection pools to ensure they do not exceed the maximum size. ```objc // 验证池不变式 NSArray *keys = [client allConnectionPoolKeys]; for (NSString *key in keys) { NSUInteger count = [client connectionPoolCountForKey:key]; XCTAssertLessThanOrEqual(count, 4, @"Pool invariant: max 4 connections"); } ``` -------------------------------- ### Test Requirement for Open Failure Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying that failed connections are not added to the pool. ```objc testStateTransition_OpenFails_NotAddedToPool ``` -------------------------------- ### HttpdnsNWHTTPClient.m: returnConnection:forKey:shouldClose: Logic Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/TIMEOUT_ANALYSIS.md This function handles the return of a connection to the pool. If the connection should be closed or is invalidated, it is invalidated and removed from the pool. ```Objective-C if (shouldClose || connection.isInvalidated) { [connection invalidate]; // 取消底层 nw_connection [pool removeObject:connection]; // 从池中移除 } ``` -------------------------------- ### Check if Logging is Enabled Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Checks if the SDK's logging feature is currently enabled. Returns YES if enabled, NO otherwise. ```objc + (BOOL)isEnabled; ``` -------------------------------- ### isEnabled Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Checks if the log functionality is currently enabled. Returns YES if logs are enabled, and NO if they are disabled. ```APIDOC ## isEnabled ### Description Checks if the log functionality is currently enabled. ### Method `+ (BOOL)isEnabled;` ### Parameters This method takes no parameters. ### Response - **BOOL**: YES if logs are enabled, NO if logs are disabled. ### Example ```objc BOOL logEnabled = [HttpdnsLog isEnabled]; if (logEnabled) { NSLog(@"Log is enabled"); } ``` ``` -------------------------------- ### Test Requirement for Double Return Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying idempotent double return behavior. ```objc testStateTransition_DoubleReturn_Idempotent ``` -------------------------------- ### Test Requirement for Wrong Pool Key Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying isolation when returning to the wrong pool. ```objc testStateTransition_ReturnToWrongPool_Isolated ``` -------------------------------- ### Pruning Connection Pool (EXPIRED to INVALIDATED) Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Implements the logic to prune the connection pool, moving expired connections to the INVALIDATED state. It identifies idle connections exceeding the timeout and removes them, also enforcing a maximum pool size. ```objc - (void)pruneConnectionPool:(NSMutableArray *)pool referenceDate:(NSDate *)referenceDate { // ... NSMutableArray *toRemove = [NSMutableArray array]; for (HttpdnsNWReusableConnection *conn in pool) { if (conn.inUse) continue; // 跳过使用中的 NSTimeInterval idle = [referenceDate timeIntervalSinceDate:conn.lastUsedDate]; if (idle > kHttpdnsNWHTTPClientConnectionIdleTimeout) { // 30秒 [toRemove addObject:conn]; } } for (HttpdnsNWReusableConnection *conn in toRemove) { [conn invalidate]; [pool removeObject:conn]; } // 限制池大小 ≤ 4 while (pool.count > kHttpdnsNWHTTPClientMaxIdleConnectionsPerHost) { HttpdnsNWReusableConnection *oldest = pool.firstObject; [oldest invalidate]; [pool removeObject:oldest]; } } ``` -------------------------------- ### Pool Overflow Removal Strategy Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Removes the oldest connection when the pool exceeds the maximum allowed capacity. ```objc while (pool.count > kHttpdnsNWHTTPClientMaxIdleConnectionsPerHost) { HttpdnsNWReusableConnection *oldest = pool.firstObject; // ← 移除最老的 [oldest invalidate]; [pool removeObject:oldest]; } ``` -------------------------------- ### disableLog Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Disables the SDK's internal log output. This stops the SDK from logging internal information. ```APIDOC ## disableLog ### Description Disables the SDK's internal log output. ### Method `+ (void)disableLog;` ### Parameters This method takes no parameters. ### Response This method returns void. ### Example ```objc [HttpdnsLog disableLog]; ``` ``` -------------------------------- ### Test Requirement for Concurrent Dequeue and Prune Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying thread safety during pool operations. ```objc testStateTransition_ConcurrentDequeueAndPrune_NoCorruption ``` -------------------------------- ### Prune Connection Pool Concurrency Guard Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Skips connections currently in use during the pool pruning process to avoid race conditions. ```objc - (void)pruneConnectionPool:... { for (HttpdnsNWReusableConnection *conn in pool) { if (conn.inUse) continue; // ← 跳过使用中的 } } ``` -------------------------------- ### Test Requirement for Pool Overflow Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Identifier for the test case verifying the removal of the oldest connection. ```objc testStateTransition_PoolOverflow_RemovesOldest ``` -------------------------------- ### Disable SDK Logging Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/_autodocs/api-reference/HttpdnsLog.md Call this method to disable the SDK's internal log output. ```objc + (void)disableLog; ``` -------------------------------- ### Handle Connection Invalidation During Use Source: https://github.com/aliyun/alibabacloud-httpdns-ios-sdk/blob/master/AlicloudHttpDNSTests/Network/STATE_MACHINE_ANALYSIS.md Invalidates a connection if a network error occurs during request transmission. ```objc NSData *rawResponse = [connection sendRequestData:requestData ...]; if (!rawResponse) { [self returnConnection:connection forKey:poolKey shouldClose:YES]; // ← invalidated } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.