Wing 标准库 http 模块实战:基于 fetch.test.w 与 tf-aws 编译快照解析重定向与超时行为

原创2026-10-14 11:30:361,943 阅读
文章标签:编程语言编译器云原生语言运行时

Wing 标准库 http 模块实战:基于 fetch.test.w 与 tf-aws 编译快照解析重定向与超时行为

本篇技术指南以 Wing 仓库中 tests/sdk_tests/http/fetch.test.w 的端到端测试及其 hangar 快照 fetch.test.w_compile_tf-aws.md 为骨架,深入讲解 Wing 标准库 http 模块的用法与底层实现:包括默认跟随重定向与手动重定向模式的区别、请求超时机制的实现原理,以及一段简单 Wing 代码在编译到 tf-aws 目标时会被展开成哪些 AWS 基础设施资源。读完本文,你将能够熟练使用 http.get / http.fetch 编写云上 HTTP 客户端逻辑,并理解 Wing 一次编写、多目标部署背后的编译模型。

快照文档在仓库中的定位:hangar 测试体系

本仓库用 tools/hangar(Wing 工具链测试套件)驱动 E2E 测试:tests/sdk_tests/http 目录下的 fetch.test.w 是 SDK 标准库的端到端测试用例,而 tools/hangar/__snapshots__/test_corpus/sdk_tests/http/ 目录下保存的是测试执行产物的快照(snapshot)。其中:

这两份快照与测试源码一一对应,是理解 Wing 编译行为和运行时行为的第一手证据。

测试源码:一个覆盖重定向与超时三种场景的 HTTP 测试

先看被测程序 tests/sdk_tests/http/fetch.test.w 的完整逻辑。它首先引入标准库模块并声明云资源:

bring http;
bring expect;
bring cloud;
bring util;

let api = new cloud.Api();
let bucket = new cloud.Bucket();

这里出现了三个关键云抽象:cloud.Api(HTTP API 网关)、cloud.Bucket(对象存储)、http(标准库 HTTP 客户端)。http 模块的正式 API 文档位于 docs/api/04-standard-library/http/api-reference.md。

接下来向 Bucket 写入一个对象,内容是该 API 自身的访问地址:

bucket.addObject("url.txt", api.url);

这个细节很有意思:api.url 在预飞阶段(preflight)是一个令牌(token),真正取值发生在部署之后。编译到 AWS 时,它会被渲染成 API Gateway 的完整执行 URL(见下文 tf-aws 快照中的 Bucket_S3Object-urltxt_54506D60 资源)。

随后定义了三个路由,它们分别对应测试的三个场景:

api.get("/redirect", inflight () => {
  let url = bucket.get("url.txt");
  return {
    status: 301,
    headers: { Location: "{url}/target" }
  };
});

api.get("/target", inflight () => {
  return {
    status: 200,
    body: "I am the target"
  };
});

api.get("/delayed", inflight () => {
  util.sleep(2s);
  return {
    status: 200,
    body: "I am the target"
  };
});
  • /redirect:从 Bucket 读回 API 地址,返回 301 状态码并携带 Location 响应头指向 /target,用于测试重定向行为;
  • /target:返回 200 与固定文本 I am the target,是重定向的最终落点;
  • /delayed:先 util.sleep(2s) 再返回,用于测试请求超时。

最后是核心测试块:

test "fetch" {
  // "redirect is 'follow' by default"
  let redirectDefault = http.get("{api.url}/redirect");
  log(redirectDefault.body);
  expect.equal(redirectDefault.status, 200);
  expect.equal(redirectDefault.body, "I am the target");

  // "redirect 'manual'"
  let redirectManual = http.get("{api.url}/redirect", redirect: http.RequestRedirect.MANUAL);
  expect.equal(redirectManual.headers.get("location"), "{api.url}/target");
  expect.equal(redirectManual.status, 301);

  // timeout property -
  // timeout shorter than the request
  let var error = "";
  try {
    let timeout = http.get("{api.url}/delayed", timeout: 1s);
  } catch e {
    error = e;
  }
  expect.equal(error, "This operation was aborted");

    // timeout longer than the request
  try {
    let timeout = http.get("{api.url}/delayed", timeout: 3s);
  } catch e {
    assert(false);
  }
}

测试覆盖了三条关键语义:

  1. 重定向默认是 follow:直接请求 /redirect 时,客户端自动跟随 301 跳转,最终拿到的是 200 状态和 I am the target 正文;
  2. redirect: http.RequestRedirect.MANUAL:不跟随重定向,返回原始的 301 状态,并可从响应头 location 读取跳转目标;
  3. timeout 语义:请求 /delayed(延迟 2 秒),当 timeout: 1s 时请求被中止并抛出错误 "This operation was aborted";当 timeout: 3s 时请求正常完成,不会抛出异常。

SDK 源码解析:RequestOptions、RequestRedirect 与超时实现

http 模块的实现位于 packages/@winglang/sdk/src/http/http.ts,测试中使用到的类型都能在此找到对应定义。

请求选项 RequestOptions

测试里用到的 redirect、timeout 两个命名参数,都定义在 RequestOptions 接口中:

export interface RequestOptions {
  readonly method?: HttpMethod;        // 默认 GET
  readonly headers?: Record<string, string>;
  readonly body?: string;              // GET/HEAD 请求不能携带 body
  readonly cache?: RequestCache;       // 默认 RequestCache.DEFAULT
  readonly redirect?: RequestRedirect; // 默认 RequestRedirect.FOLLOW
  readonly referrer?: string;          // 默认 "about:client"
  readonly timeout?: Duration;         // 未定义时无超时
}

注意 timeout 的类型是 Wing 标准库的 Duration(时长类型),这正是测试中可以直接写 timeout: 1s、timeout: 3s 的原因。默认选项 defaultOptions 中 redirect 被固定为 FOLLOW,与测试注释 "redirect is 'follow' by default" 完全一致。

重定向模式 RequestRedirect

export enum RequestRedirect {
  MANUAL = "manual", // 不自动跟随,Location 响应头保留跳转目标
  FOLLOW = "follow", // 跟随所有重定向
  ERROR = "error",   // 遇到重定向时返回网络错误
}

测试中对 MANUAL 模式的断言(读取 location 头、断言状态码为 301)与枚举注释描述的行为一一对应。

fetch 的底层实现与超时机制

所有方法(get/post/put/patch/delete/connect/trace)最终都汇聚到静态方法 fetch,其超时实现非常直观:

public static async fetch(url: string, options?: RequestOptions): Promise<Response> {
  if (options?.timeout) {
    const abortController = new AbortController();
    setTimeout(() => {
      abortController.abort();
    }, options.timeout.milliseconds);

    return this._formatResponse(
      await fetch(url, {
        ...defaultOptions,
        ...options,
        signal: abortController.signal,
      }),
    );
  }
  return this._formatResponse(
    await fetch(url, { ...defaultOptions, ...options }),
  );
}

超时的实现思路是:把 Duration 换算成毫秒(options.timeout.milliseconds)后,用 setTimeout 触发 AbortController.abort(),并将 abortController.signal 传给底层 fetch。因此当超时发生时,底层 fetch 会抛出中止异常,测试断言中的错误信息 "This operation was aborted" 正是 Node 环境对该中止的标准错误文本。这解释了为什么 timeout: 1s 会抛错而 timeout: 3s 能正常返回。

_formatResponse 会把浏览器/Node 的 Response 对象规范化为 SDK 的 Response 结构(status、url、ok、headers、body),其中 headers 会被展开成普通对象,body 通过 response.text() 读取。这也是测试中 redirectDefault.body 能直接和字符串比较的原因。

编译快照解读:一段 Wing 代码如何变成 AWS 基础设施

回到关联文档 fetch.test.w_compile_tf-aws.md,它以 # <a href="https://link.gitcode.com/i/3ebc7d9e2b5c7bbb9d0e58e7c8d6b807" target="_blank">fetch.test.w</a> | compile | tf-aws 开头,随后完整展示了编译生成的 main.tf.json(哈希前缀、uniqueId 等细节因路径不同可能变化,但资源结构是稳定的)。从这份 JSON 可以看到 Wing 把上述短短几十行代码展开成了如下 AWS 资源:

API 网关层

  • aws_api_gateway_rest_api(Api_api_91C07D84):OpenAPI 3.0.3 定义的 REST API,body 中包含 /redirect、/target、/delayed 三个 GET 方法,每个方法通过 x-amazon-apigateway-integration 以 aws_proxy 方式指向对应 Lambda;另外还自动生成了 /{proxy+} 兜底路由,对未匹配路径返回 404(mock 集成,消息为 Error: Resource not found);
  • aws_api_gateway_deployment:绑定 create_before_destroy 生命周期与基于 API body 的 sha256 触发重部署;
  • aws_api_gateway_stage:阶段名为 prod。

三个 Lambda 函数

  • Api_get_redirect0_61A02C26、Api_get_target0_6A24458B、Api_get_delayed0_04F37C13,每个函数的关键配置包括:运行时 nodejs20.x、架构 arm64、内存 1024、超时 60 秒、日志格式 JSON、通过 s3_bucket + s3_key 从代码桶加载部署包。
  • 特别值得注意的是 Api_get_redirect0 的环境变量里出现了 BUCKET_NAME_1357ca3a: ${aws_s3_bucket.Bucket.bucket}——这正是 Wing 闭包捕获(lift)机制的体现:/redirect 处理器在 inflight 代码中调用了 bucket.get("url.txt"),编译期就把对 Bucket 的访问自动提升为 Lambda 环境变量,运行时通过环境变量拿到真实桶名。
  • 每个函数都配了 aws_lambda_permission,授权 apigateway.amazonaws.com 以 lambda:InvokeFunction 调用它,source_arn 精确限定到 */*/GET/<path>。

IAM 与日志

  • 每个函数一个 aws_iam_role(假设策略为 sts:AssumeRole,Principal 为 lambda.amazonaws.com)和 AWSLambdaBasicExecutionRole 策略附件;
  • Api_get_redirect0 的 aws_iam_role_policy 显式包含 s3:List*、s3:GetObject*、s3:GetBucket* 权限——这是它对 Bucket 执行读操作所需的权限;
  • 每个函数一个 aws_cloudwatch_log_group(保留 30 天)。

对象存储

  • Bucket:bucket_prefix: "bucket-c88fdc5f-",force_destroy: false;
  • Bucket_CorsConfiguration-1357ca3a_A4CCA40A:自动为 Bucket 配置了允许 * 来源、GET/POST/PUT/DELETE/HEAD 方法的 CORS 规则;
  • Bucket_S3Object-urltxt_54506D60:把预飞阶段的 api.url 令牌解析成 https://${aws_api_gateway_rest_api...id}.execute-api.${region}.amazonaws.com/${stage_name} 的完整 URL,作为内容写入 url.txt 对象——这就是测试里 /redirect 处理器能读回 API 地址的原因;
  • 另有 Code 桶用于存放三个 Lambda 的部署包(<ASSET_KEY> / <ASSET_SOURCE> 为资产占位符)。

这份快照直观展示了 Wing 的核心价值:开发者只需要面向 cloud.Api、cloud.Bucket 等抽象编程,编译器负责把资源依赖、权限、CORS、路由集成等 AWS 样板全部生成出来,产物是可直接交给 Terraform 执行的 main.tf.json。

模拟器运行结果:测试通过的直接证据

配套的 fetch.test.w_test_sim.md 记录了同一测试在 sim 平台上的执行结果:

[INFO] fetch | I am the target
pass ─ fetch.test.wsim » root/Default/test:fetch

Tests 1 passed (1)
Snapshots 1 skipped
Test Files 1 passed (1)

输出中的 I am the target 正是默认 follow 模式下重定向到达 /target 后返回的正文,验证了前两个断言;pass 说明包括超时场景在内的整个 test "fetch" 块全部通过。这印证了 Wing 的测试可以在本地模拟器中先行验证(无需真实云账号),再通过 tf-aws 等平台编译部署到云端。

实战扩展:在自己的 Wing 项目中发起 HTTP 请求

参考 docs/by-example/33-http-client.md,标准库 http 模块的典型用法是在 inflight 代码中调用 http.get,并对响应做结构化处理:

bring http;
bring cloud;

struct Pokemon {
  id: num;
  name: str;
  order: num;
  weight: num;
}

new cloud.Function(inflight () => {
  let x = http.get("https://pokeapi.co/api/v2/pokemon/ditto");

  // 响应状态码
  log(x.status);

  // 将字符串响应解析为 JSON 对象
  let data = Json.parse(x.body);

  // 将 JSON 响应转换为结构体
  let ditto = Pokemon.fromJson(data);
  log(ditto.name);
});

结合本文介绍的 RequestOptions,你可以按需扩展该模式:用 http.post / http.put / http.delete 发送其他方法;通过 headers 传入自定义请求头;通过 redirect: http.RequestRedirect.MANUAL 手动处理跳转;通过 timeout: 5s 给请求设置超时上限;用 http.parseUrl / http.formatUrl 处理 URL 解析与序列化(相关用法见 tests/sdk_tests/http/url.test.w)。

关联文件速查

通过「测试源码 + SDK 实现 + 编译快照 + 运行快照」四者的对照阅读,你可以最直观地掌握 Wing 中 HTTP 客户端的行为语义,以及 Wing 从代码到云资源的完整映射链路。

登录后查看全文
wing