Debugging
When something’s wrong with your app it can be hugely frustrating; so we want to make it as easy as we can for you to get to the bottom of these issues! But first, you need to figure out what type of issue you have...
应用出故障时难免让人抓狂,因此我们希望尽可能帮你快速定位并解决问题的根源!但在动手排查之前,你需要先弄清楚遇到的是哪一类问题……
Something is wrong in a GraphQL requestGraphQL 请求出现异常
Check you’re requesting what you think you’re requesting确认实际发出的请求与预期一致
Often issues occur because your client code isn’t doing what you think it’s doing. The first step here is to determine exactly what’s being sent over the network. If you’re building a website you can easily use Google Chrome’s Network Devtools to see exactly what’s being sent and received.
很多问题其实是因为客户端代码的行为与你的预期不符。排查的第一步,是确认网络上实际发送和接收的数据到底是什么。如果你在开发 Web 应用,可以直接使用 Google Chrome 开发者工具中的 Network 面板来查看完整的请求与响应内容。
-
Open your website in Chrome
在 Chrome 中打开你的网站
-
Right click, and select ‘Inspect’
右键点击页面,选择“检查(Inspect)”
-
Select the ‘Network’ tab in the developer tools
在开发者工具中切换到“Network(网络)”标签页
-
In the filter box, enter ‘/graphql’ (or whatever path you have configured your API to use)
在过滤框中输入“/graphql”(或你为 API 配置的实际路径)
-
Ensure that ‘All’ is selected to the right of the filter box
确保过滤框右侧已选中“All(全部)”
-
Trigger your GraphQL request (either by reloading the page or by clicking the relevant element on the screen)
触发 GraphQL 请求(刷新页面或点击界面上对应的交互元素)
-
Review the network requests that have arrived to ensure they’re what you’d expect, that no variables are unexpectedly null, that the relevant access tokens are being set in the request headers, etc
检查捕获到的网络请求是否符合预期:例如变量是否意外为 null、请求头中是否正确携带了访问令牌(access token)等
Try your query in Ruru or GraphiQL在 Ruru 或 GraphiQL 中重放查询
It sometimes helps to try doing the same thing a different way, and this is
where Ruru (or any GraphiQL) comes in handy. Take the query you’re running and
execute it via Ruru. Is it producing the same issue? Note that you can set
headers in Ruru via the Headers tab at the bottom, where variables are
entered.
换个途径复现同一操作往往很有帮助,这时 Ruru(或任意 GraphiQL 工具)就能派上用场。把你正在运行的查询拿到 Ruru 中直接执行,看看是否还会出现相同问题。注意:你可以在 Ruru 底部(输入变量的区域旁)通过 Headers 标签页设置请求头。
Increase PostGraphile’s logging增强 PostGraphile 的错误日志输出
GraphQL errors are masked by default and logged on the server, but if you
disable error masking then they will be sent through to the client and not
logged on the server - in which case you can use preset.grafserv.maskError to
output the error details on the server side (and to manipulate them before
they’re returned to the client).
默认情况下,GraphQL 错误会被脱敏(mask)处理并在服务端记录日志;如果你禁用了错误脱敏,错误信息会直接透传给客户端,而不再输出到服务端日志。此时可以通过 preset.grafserv.maskError 在服务端打印错误详情(并在返回给客户端之前对其进行处理)。
The default implementation of maskError trims out a lot of
details for security reasons, if you replace it be sure that you are also being
cautious about what you’re outputting to potential attackers.
出于安全考虑,maskError 的默认实现会裁剪掉大量错误细节。如果你要自行替换该实现,务必谨慎评估暴露给潜在攻击者的信息范围。
import { GraphQLError } from "postgraphile/graphql";
import { isSafeError } from "postgraphile/grafast";
import { createHash } from "node:crypto";
const sha1 = (text: string) =>
createHash("sha1").update(text).digest("base64url");
export default {
//...
grafserv: {
maskError(error) {
console.error("maskError was called with the following error:");
console.error(error);
console.error("which had an originalError of:");
console.error(error.originalError);
// You probably don't want this level of debugging in production as the
// results are sent to the client and it may leak implementation details
// you wish to keep private.
//
// return error;
// Here's a more careful implementation:
if (error.originalError instanceof GraphQLError) {
return error;
} else if (
error.originalError != null &&
isSafeError(error.originalError)
) {
return new GraphQLError(
error.originalError.message,
error.nodes,
error.source,
error.positions,
error.path,
error.originalError,
error.originalError.extensions ?? null,
);
} else {
// Hash so that similar errors can easily be grouped
const hash = sha1(String(error));
console.error(`Masked GraphQL error (hash: '${hash}')`, error);
return new GraphQLError(
`An error occurred (logged with hash: '${hash}')`,
error.nodes,
error.source,
error.positions,
error.path,
error.originalError,
// Deliberately wipe the extensions
{},
);
}
},
},
};
originalError property善用 originalError 属性GraphQLError instances have an error.originalError property that can be used
to retrieve the underlying error, this typically contains more actionable
information than the GraphQL error itself.
GraphQLError 实例带有 error.originalError 属性,可用于获取底层原始错误——相比 GraphQL 错误本身,它通常包含更有价值、可直接用于排查的细节信息。
Viewing the generated SQL查看生成的 SQL 语句
Assuming that the error is coming from within the database, you can see what SQL statements PostGraphile is generating.
如果错误来自数据库内部,你可以查看 PostGraphile 实际生成并执行了哪些 SQL 语句。
Via Ruru ‘Explain’通过 Ruru 的“Explain”功能查看
One way to do so is via the “Explain” feature available in Ruru. To use this,
you must ensure that preset.grafast.explain is enabled in your configuration:
一种方式是使用 Ruru 内置的“Explain”功能。使用前,请确保在配置中启用了 preset.grafast.explain:
export default {
// ...
grafast: {
explain: true,
},
};
Explain should be disabled in production since it could leak information about the internals of your schema that would be useful to an attacker.
生产环境中务必禁用 Explain,否则可能泄露 schema 内部实现细节,给攻击者提供可乘之机。
Once enabled, visit Ruru (by default this will be at
http://localhost:5678/graphiql) and open the Explain tab on the left — the
icon looks like a magnifying glass 🔍. You should see the query that was
executed and the associated Grafast operation plan, and from the dropdown you
can select the various SQL queries and their explain results.
开启后,访问 Ruru(默认地址为 http://localhost:5678/graphiql)并点击左侧栏中形似放大镜 🔍 的 Explain 标签页。你可以在这里看到已执行的查询以及对应的 Grafast 操作执行计划(operation plan),并通过下拉菜单选择查看各条 SQL 查询及其 EXPLAIN 分析结果。
Currently SQL EXPLAIN can only be enabled via DEBUG envvar. This is a known
issue that we plan to address.
目前 SQL EXPLAIN 仅能通过 DEBUG 环境变量开启,这是一个已知问题,我们计划在后续版本中修复。
Via DEBUG envvar通过 DEBUG 环境变量查看
Another way is to set the relevant DEBUG environmental variable before running PostGraphile. For example:
另一种方式是在启动 PostGraphile 前设置对应的 DEBUG 环境变量。例如:
# Bash (Linux, macOS, etc)
export DEBUG="@dataplan/pg:PgExecutor:explain"
postgraphile
# Windows Console
set DEBUG=@dataplan/pg:PgExecutor:explain & postgraphile
# Windows PowerShell
$env:DEBUG='@dataplan/pg:PgExecutor:explain'; postgraphile
The above examples assume you already have a graphile.config.* file in your
working directory. If you do not, add your connection details and preset via CLI
flags instead.
上述示例假定当前工作目录下已经存在 graphile.config.* 配置文件;如果还没有,请改用 CLI 参数传入数据库连接信息和 preset。
Something is in my GraphQL schema that shouldn't beGraphQL schema 中出现了不该暴露的内容
This could be for a number of reasons...
这可能由多种原因导致……
Filtering database schemas过滤数据库 schema
Be sure to only include the database schemas you wish to expose in your schemas
list. By default this is public.
请确认你的 schemas 列表中只包含了确实希望对外暴露的数据库 schema,该配置默认值为 public。
Hiding PostgreSQL extensions隐藏 PostgreSQL 扩展对象
By default, PgRemoveExtensionResourcesPlugin removes resources and codecs that
come from extensions from your
schema. Be sure it's enabled via npx graphile config print plugins.
默认情况下,PgRemoveExtensionResourcesPlugin 会将来自 PostgreSQL 扩展的 resource 和 codec 从你的 schema 中移除。你可以通过 npx graphile config print plugins 确认该插件处于启用状态。
Hiding with permissions通过数据库权限控制隐藏
PgRBACPlugin limits the contents of your schema to only those things the
introspecting user has access to. If you disabled this plugin, this omission
will not occur. Use npx graphile config print plugins to see what plugins you have
in your resolved configuration.
PgRBACPlugin 会根据执行 introspection 的数据库用户权限,将 schema 内容限制为该用户有权访问的对象;如果你禁用了该插件,这些无权限对象就不会被过滤。运行 npx graphile config print plugins 即可查看最终解析出的配置中启用了哪些插件。
If you're connecting with the superuser or database owner role, then everything is permitted! Ensure you're connecting with a user with minimal permissions - see creating roles in required knowledge, and especially the "authenticator" role which should be the role used in your connection string.
如果你使用超级用户或数据库所有者角色连接数据库,那几乎所有操作都会被放行!请务必改用具备最小权限的用户进行连接——具体请参阅前置知识中的“创建角色”,尤其是应当放在连接字符串中使用的“authenticator”角色。
Maybe you didn't grant the permission correctly? Check out the \dp+ command in
psql to see full permissions for a table.
也可能是权限授予有误。可以在 psql 中执行 \dp+ 命令,查看某张表的完整权限分配情况。
Hiding with smart tags通过 smart tag 隐藏
@omit only works with the V4 preset; people using the Amber preset only should
use @behavior instead.
@omit 仅在使用 V4 preset 时生效;如果你只使用了 Amber preset,请改用 @behavior。
When you add a behavior (including the behaviors that the V4 preset converts
@omit into), you can debug it - see hiding with
behaviors.
无论你添加的是哪种 behavior(包括 V4 preset 将 @omit 自动转换后的 behavior),都可以对其进行调试——详情见下文通过 behavior 隐藏。
Hiding with behaviors通过 behavior 隐藏
To debug your behavior, use the npx graphile behavior debug command; you'll
be asked to choose a scope:
要调试 behavior,可以运行 npx graphile behavior debug 命令,系统会提示你选择一个作用域(scope):
-
pgResource - somewhere you can
SELECTdata from: a table, function, view, materialized view, etcpgResource —— 可从中
SELECT数据的数据源,如表、函数、视图、物化视图等 -
pgResourceUnique - a unique constraint on a table/materialized view
pgResourceUnique —— 表或物化视图上的唯一约束
-
pgCodec - represents scalars, ranges, enums, domains and composite types (no storage!)
pgCodec —— 表示标量、范围类型、枚举、域类型(domain)及复合类型(不对应实际存储!)
-
pgCodecAttrbute - represents an attribute (column) on a composite type
pgCodecAttrbute —— 表示复合类型上的某个属性(列)
-
pgCodecRelation - a relation between a codec and a resource
pgCodecRelation —— codec 与 resource 之间的 relation
-
pgRefDefinition - the definition of a
@refpgRefDefinition ——
@ref的定义 -
pgCodecRef - an applied
@refpgCodecRef —— 已应用的
@ref
Run the command again with the scope added (e.g. npx graphile behavior debug pgResource) and you'll be greeted with a list of entities of that type.
在命令后附上对应的作用域再次运行(例如 npx graphile behavior debug pgResource),即可看到该类别下的全部实体列表。
Run the command again with the entity identifier added (e.g. npx graphile behavior debug pgResource users) and you'll be told the final behavior string for
that entity, along with its derivation (which plugins added/removed which
behaviors). Note __ApplyBehaviors_*__ is a workaround for the new behavior
system - it represents "multiplying" the defaultBehaviors with the available
behaviors - and PgBasicsPlugin.schema.entityBehavior.*.override is typically
the overrides that come from your smart tags (@omit, @behavior, etc).
继续在命令后加上实体标识符(例如 npx graphile behavior debug pgResource users),命令就会输出该实体最终生效的 behavior 字符串及其推导过程(包括哪些插件增删了哪些 behavior)。注意:__ApplyBehaviors_*__ 是新 behavior 系统中的过渡机制,表示将 defaultBehaviors 与可用 behavior 进行“叠加组合”;而 PgBasicsPlugin.schema.entityBehavior.*.override 通常对应来自 smart tag(如 @omit、@behavior 等)的覆盖配置。
Something is not in my schema that should beGraphQL schema 中缺少了预期应有的内容
Kind of the inverse of the above, check:
这与上面的情况正好相反,请逐项检查以下几点:
-
Functions that use
returns table(...)cannot have this return type augmented with comments and smart tags (nor can you comment on/tweak the attributes); the return type will be exposed as a GraphQL type with an autogenerated name. Avoid this construct; instead, you should always prefer explicit named types (returns setof my_type) - see Adding a field to a function-derived type使用
returns table(...)的函数无法通过注释和 smart tag 对其返回类型进行增强(也无法对其属性添加注释或微调),且该返回类型在 GraphQL 中只能以自动生成的名称暴露。建议避免这种写法,始终优先使用显式的具名类型(returns setof my_type)——详情参见为函数派生类型添加字段 -
Computed columns must follow the naming and signature rules in Computed columns (remember
STABLE!), and must be in the same PostgreSQL schema as the table they apply to计算列必须遵守计算列中的命名与函数签名规范(别忘了标记
STABLE!),并且必须与目标表位于同一个 PostgreSQL schema 中 -
Are you listing the correct database schemas in your config?
检查配置中是否列出了正确的数据库 schema
-
If the resource is coming from a PostgreSQL extension, either disable
PgRemoveExtensionResourcesPluginor override the behaviors on the relevant resource.如果某个 resource 来自 PostgreSQL 扩展,你可以禁用
PgRemoveExtensionResourcesPlugin,或者覆盖该 resource 上的 behavior 配置。 -
If you're using
PgRBACPlugin(enabled by default), check you've granted permissions to the relevant visitor role, and that the database connection role (the "authenticator" role) has been granted the relevant visitor role (even withnoinherit).如果你使用了
PgRBACPlugin(默认启用),请检查是否已将权限授予对应的访客角色(visitor role),以及数据库连接角色(即“authenticator”角色)是否已被授予该访客角色(即使带有noinherit属性也需要授予)。 -
Check smart tags and behaviors - see
npx graphile behavior debug(described above)检查 smart tag 与 behavior 设置——使用前文介绍的
npx graphile behavior debug命令进行排查 -
If it's an "advanced" or non-core feature, check the relevant plugin is enabled (e.g. for advanced filtering, use
postgraphile-plugin-connection-filter) - usenpx graphile config print pluginsto see what plugins you have如果缺失的是“高级”或非核心功能,请确认对应插件已启用(例如高级过滤需使用
postgraphile-plugin-connection-filter)——可运行npx graphile config print plugins查看当前启用的插件列表 -
If it's an accessor (a root level "finder" field), check you're using a constraint not an index (see below)
如果缺失的是访问器(accessor,即根级别的“查找”字段),请确认你创建的是唯一约束而非普通唯一索引(见下文)
-
If it's a relation, check for missing constraints or missing indexes (see below)
如果缺失的是 relation,请检查是否缺少外键约束或索引(见下文)
Missing constraints缺少数据库约束
By default, PostGraphile only adds relations and accessors (a root level "finder" field) to your schema based on database constraints.
默认情况下,PostGraphile 只会根据数据库约束在 schema 中生成 relation 和访问器(根级别的“查找”字段)。
For accessors, a unique index is not sufficient - an index is an optimization,
whereas a constraint is something you state will remain true about your data.
For example, for a userByUsername: User field, you would add a unique
constraint (not index):
对于访问器而言,仅有唯一索引是不够的——索引只是一种性能优化手段,而约束才是你对数据不变性作出的语义声明。例如,要生成 userByUsername: User 字段,你需要添加唯一约束(而不是索引):
alter table users
add constraint uniq_users_username
unique (username);
For relations, just naming the column with a convention is insufficient - we could infer the wrong thing - so you must add a constraint to show the relationship:
对于 relation 而言,仅仅按命名约定给字段取名也不够——那样很容易推导出错——因此你必须显式添加外键约束来表明表间关联关系:
alter table posts
add constraint fk_posts_author
foreign key (author_id) references users (id);
create index on posts (author_id);
Missing indexes缺少索引
By default, PostGraphile does not add "reverse" relationships to the schema unless there is a matching index - this is because without an index PostgreSQL might have to do a table scan to find the matching records, which is incredibly expensive.
默认情况下,如果没有匹配的索引,PostGraphile 不会在 schema 中生成“反向”关联关系——因为缺少索引时,PostgreSQL 可能需要执行全表扫描来查找匹配记录,代价极其高昂。
To solve this, create an index that matches the relationship (including ensuring the columns are in the same order); for example:
要解决该问题,请创建一个与该关联关系相匹配的索引(并确保列的顺序完全一致),例如:
alter table posts
add constraint fk_posts_author
foreign key (organization_id, author_id) references users (organization_id, id);
create index on posts (organization_id, author_id);
:::
Poor performance性能不佳
If you have a well designed database schema, you should find PostGraphile's performance to be stellar; however if you're new to database design then there are a lot of potential sources for poor performance. Use the Viewing the generated SQL above, and then consider these things:
只要你的数据库 schema 设计合理,PostGraphile 通常都能发挥出极为出色的性能;但如果你刚开始接触数据库设计,很多环节都可能成为性能瓶颈。请先参考上文的查看生成的 SQL 语句定位实际 SQL,再从以下几个方面着手排查:
-
If the same query ran directly is much faster than when ran through PostGraphile, chances are your RLS policies have poor perfomance. This is by far the most common performance issue PostGraphile users face, but it's easy to fix.
如果同一条查询直接运行很快,通过 PostGraphile 执行却慢得多,多半是你的 RLS 策略性能有问题。这是 PostGraphile 用户最常遇到的性能瓶颈,而且通常很容易修复。
-
Fetch only what you render
只获取需要渲染的数据
-
Indexes
索引
-
Functions
函数
-
Views
视图
-
Materialized views
物化视图
-
Plugins
插件
-
Complex filters
复杂过滤条件
RLS performanceRLS 性能
See Writing performant RLS policies in required knowledge.
请参阅前置知识中的编写高性能的 RLS 策略。
Functions函数
Fetch only what you render只获取需要渲染的数据
GraphQL is designed to fetch what you request - no more, no less.
GraphQL 的设计初衷就是按需取数——不多也不少。
Overfetching过度获取(Overfetching)
Everything you fetch should be rendered almost immediately to the user. If something you fetch is not to be shown to the user until an interaction occurs - for example a click on the "next page" or "expand" or "details" button - then that data should be fetched in a follow-up request.
每次请求获取的所有数据都应当几乎立即呈现给用户。如果某些数据要等用户触发交互之后才会展示——例如点击“下一页”、“展开”或“查看详情”按钮——那就应该放到后续的按需请求中再去获取。
Fetch everything you need for the current view in a single round-trip, but only fetch what you need, not what you think might be needed in a few seconds time.
在一次网络往返中取回当前视图所需的全部数据,但仅限当前真正需要的数据,不要提前预取“过几秒钟可能会用到”的字段。
The most common causes of overfetching are:
造成过度获取最常见的原因有:
-
Lack of pagination
未做分页限制
-
Incorrect use of fragments
Fragment 使用方式不当
Pagination分页
If you tell GraphQL to fetch all your emails, but then you only render the first 25, then you're doing a poor job of telling GraphQL what you need. Every list fetch should include pagination limits.
如果你让 GraphQL 拉取全部邮件,界面上却只渲染前 25 封,那显然没有准确向 GraphQL 描述你的需求。所有列表查询都应该包含分页数量限制。
When you render page two of a collection, you should NOT use the same query again (since it may fetch ancilliary data that you don't need a second time), instead use a new query that uses the same fragment:
渲染列表第二页时,不要再次发送同一个查询(因为那样可能会重复拉取不需要再次获取的附属数据),而应当使用一个新的查询并复用同一个 Fragment:
# Use this to render the main page
query MainPage {
notifications {
count
}
me {
avatarUrl
name
}
feedItems(first: 5) {
...FeedItems
}
}
# When they click to view page two (or scroll down for infinite scroll), fetch
# the next set of feed items WITHOUT re-fetching ancilliary data
query MainPageMoreFeedItems($cursor: Cursor!) {
feedItems(first: 5, after: $cursor) {
...FeedItems
}
}
# The data requirements for feed items is shared between both queries
fragment FeedItems on FeedItemsConnection {
nodes {
title
description
author {
name
avatar
}
}
pageInfo {
hasNextPage
endCursor
}
}
Fragment usageFragment 的正确用法
Fragments aren't to DRY up your code, they are instead to help you locate your data requirements with the elements of your application that consume that data (functions, React components, etc). The fragments for components being rendered should then be combined into a single query that can be issued to the server, ensuring that all of the data required by the components (and nothing more!) is fetched.
Fragment 的意义并不在于消除代码重复(DRY),而是让你把数据依赖声明就近放在消费这些数据的应用单元旁(如函数、React 组件等)。随后,将正在渲染的各个组件对应的 Fragment 组合成一条完整的查询发往服务端,从而确保只获取组件所需的数据,绝不冗余!
For a great tutorial on this, see: How to use fragments (they're not for re-use!) by Janette Cheng of Meta.
关于这一点,推荐观看 Meta 的 Janette Cheng 主讲的精彩分享:如何使用 Fragment(Fragment 并非用于复用!)。
Other DEBUG envvars其他常用 DEBUG 环境变量
We use a lot of DEBUG envvars for different parts of the system. Here’s some of the ones you might care about:
系统内部为不同模块设置了许多 DEBUG 环境变量,以下是最常用的几个:
-
graphile-build:warn- details of “recoverable” errors that occurred during schema construction. Often include details of how to fix the issue.graphile-build:warn—— schema 构建过程中发生的“可恢复”错误详情,日志中通常会附带具体的修复建议。 -
graphile-build:SchemaBuilder- this hook is useful for understanding the order in which hooks execute, and how hook executions can nest - a must for people getting started with graphile-build pluginsgraphile-build:SchemaBuilder—— 用于查看各个 hook 的执行顺序以及 hook 之间的嵌套调用关系,是初学编写 graphile-build 插件的必备调试利器。 -
@dataplan/pg:PgExecutor- details of the SQL queries being executed, their inputs, and their results@dataplan/pg:PgExecutor—— 输出正在执行的 SQL 查询、输入参数以及查询结果的详细信息。 -
@dataplan/pg:PgExecutor:explain- as above, but also their EXPLAIN results@dataplan/pg:PgExecutor:explain—— 包含上述信息,并额外输出每条查询的 EXPLAIN 分析结果。
To enable these DEBUG modes, join them with commas when setting a DEBUG envvar, then run PostGraphile or your Node.js server in the same terminal:
若要同时开启多个 DEBUG 调试项,只需用英文逗号将它们拼接起来设为 DEBUG 环境变量,然后在同一终端中启动 PostGraphile 或你的 Node.js 服务即可:
# Bash (Linux, macOS, etc)
export DEBUG="graphile-build:warn,@dataplan/pg:*"
postgraphile
# Windows Console
set DEBUG=graphile-build:warn,@dataplan/pg:* & postgraphile
# Windows PowerShell
$env:DEBUG = "graphile-build:warn,@dataplan/pg:*"; postgraphile
Something is wrong in PostGraphilePostGraphile 本身存在异常
If you’re a plugin author, you think you’ve discovered an issue in PostGraphile, or you just like seeing how things work, you can use the Chrome Debug tools to debug the node process — add breakpoints, break on exceptions, and step through code execution.
如果你是插件作者、怀疑自己发现了 PostGraphile 的 Bug,或者单纯想深入观察内部运行机制,都可以借助 Chrome 调试工具来调试 Node.js 进程——添加断点、在异常处中断以及单步跟踪代码执行。
-
Visit
chrome://inspectin Google Chrome (we can’t hyperlink it for security reasons).在 Google Chrome 中访问
chrome://inspect(出于安全限制,这里无法直接做成超链接)。 -
Select ‘Open dedicated DevTools for Node’, a new devtools window should open - don’t close this!
点击“Open dedicated DevTools for Node”,此时会弹出一个新的开发者工具窗口——请不要关闭它!
-
Run your server or PostGraphile via Node.js directly, in
--inspectmode, e.g.:直接通过 Node.js 以
--inspect模式启动你的服务或 PostGraphile,例如:
# For globally installed PostGraphile:
node --inspect `which postgraphile` -c postgres://...
# or for locally installed PostGraphile:
node --inspect node_modules/.bin/postgraphile
# or, if you have your own Node.js app in `server.js`:
node --inspect server.js