@capybara-hq/testing 0.0.0-stage → 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +2 -0
  3. package/README.md +40 -2
  4. package/dist/containers.d.ts +102 -0
  5. package/dist/containers.js +314 -0
  6. package/dist/dual-replica.d.ts +142 -0
  7. package/dist/dual-replica.js +270 -0
  8. package/dist/extension-config.d.ts +9 -0
  9. package/dist/extension-config.js +16 -0
  10. package/dist/fake-channel.d.ts +162 -0
  11. package/dist/fake-channel.js +325 -0
  12. package/dist/fake-e2b.d.ts +104 -0
  13. package/dist/fake-e2b.js +500 -0
  14. package/dist/fake-git-server.d.ts +57 -0
  15. package/dist/fake-git-server.js +323 -0
  16. package/dist/fake-lark.d.ts +234 -0
  17. package/dist/fake-lark.js +837 -0
  18. package/dist/fake-marketplace.d.ts +25 -0
  19. package/dist/fake-marketplace.js +58 -0
  20. package/dist/fake-mcp-server.d.ts +134 -0
  21. package/dist/fake-mcp-server.js +308 -0
  22. package/dist/fake-model-server.d.ts +28 -0
  23. package/dist/fake-model-server.js +67 -0
  24. package/dist/fake-npm-registry.d.ts +59 -0
  25. package/dist/fake-npm-registry.js +174 -0
  26. package/dist/fake-oauth-server.d.ts +63 -0
  27. package/dist/fake-oauth-server.js +284 -0
  28. package/dist/fake-openapi-server.d.ts +50 -0
  29. package/dist/fake-openapi-server.js +278 -0
  30. package/dist/fake-slack.d.ts +258 -0
  31. package/dist/fake-slack.js +654 -0
  32. package/dist/fixtures.d.ts +49 -0
  33. package/dist/fixtures.js +92 -0
  34. package/dist/global-setup.d.ts +15 -0
  35. package/dist/global-setup.js +58 -0
  36. package/dist/index.d.ts +25 -0
  37. package/dist/index.js +25 -0
  38. package/dist/kernel-helpers.d.ts +125 -0
  39. package/dist/kernel-helpers.js +336 -0
  40. package/dist/media-samples.d.ts +10 -0
  41. package/dist/media-samples.js +76 -0
  42. package/dist/model-conformance.d.ts +61 -0
  43. package/dist/model-conformance.js +287 -0
  44. package/dist/replica-runner.d.ts +1 -0
  45. package/dist/replica-runner.js +59 -0
  46. package/dist/sse.d.ts +20 -0
  47. package/dist/sse.js +87 -0
  48. package/fixtures/extensions/fake-bootstrap-a/.capybara-plugin/plugin.json +7 -0
  49. package/fixtures/extensions/fake-bootstrap-a/package.json +12 -0
  50. package/fixtures/extensions/fake-bootstrap-a/src/index.ts +62 -0
  51. package/fixtures/extensions/fake-bootstrap-b/.capybara-plugin/plugin.json +7 -0
  52. package/fixtures/extensions/fake-bootstrap-b/migrations/0001_init.sql +10 -0
  53. package/fixtures/extensions/fake-bootstrap-b/package.json +12 -0
  54. package/fixtures/extensions/fake-bootstrap-b/src/index.ts +123 -0
  55. package/fixtures/extensions/fake-connector/.capybara-plugin/plugin.json +7 -0
  56. package/fixtures/extensions/fake-connector/connectors/fake-demo.json +12 -0
  57. package/fixtures/extensions/fake-connector/package.json +13 -0
  58. package/fixtures/extensions/fake-connector/src/index.ts +477 -0
  59. package/fixtures/extensions/fake-dep-provider/.capybara-plugin/plugin.json +7 -0
  60. package/fixtures/extensions/fake-dep-provider/package.json +12 -0
  61. package/fixtures/extensions/fake-dep-provider/src/index.ts +19 -0
  62. package/fixtures/extensions/fake-dep-requirer/.capybara-plugin/plugin.json +8 -0
  63. package/fixtures/extensions/fake-dep-requirer/package.json +12 -0
  64. package/fixtures/extensions/fake-dep-requirer/src/index.ts +21 -0
  65. package/fixtures/extensions/fake-embed/.capybara-plugin/plugin.json +7 -0
  66. package/fixtures/extensions/fake-embed/package.json +12 -0
  67. package/fixtures/extensions/fake-embed/src/index.ts +207 -0
  68. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -0
  69. package/fixtures/extensions/fake-im/package.json +12 -0
  70. package/fixtures/extensions/fake-im/src/channel.ts +224 -0
  71. package/fixtures/extensions/fake-im/src/directory.ts +25 -0
  72. package/fixtures/extensions/fake-im/src/identity.ts +66 -0
  73. package/fixtures/extensions/fake-im/src/index.ts +91 -0
  74. package/fixtures/extensions/fake-object-store/.capybara-plugin/plugin.json +7 -0
  75. package/fixtures/extensions/fake-object-store/package.json +15 -0
  76. package/fixtures/extensions/fake-object-store/src/index.ts +210 -0
  77. package/fixtures/extensions/fake-openapi/.capybara-plugin/plugin.json +7 -0
  78. package/fixtures/extensions/fake-openapi/package.json +12 -0
  79. package/fixtures/extensions/fake-openapi/src/index.ts +258 -0
  80. package/fixtures/extensions/fake-storage-user/.capybara-plugin/plugin.json +7 -0
  81. package/fixtures/extensions/fake-storage-user/package.json +12 -0
  82. package/fixtures/extensions/fake-storage-user/src/index.ts +58 -0
  83. package/fixtures/extensions/fake-tools-ui/.capybara-plugin/plugin.json +7 -0
  84. package/fixtures/extensions/fake-tools-ui/connectors/fake-notes.json +11 -0
  85. package/fixtures/extensions/fake-tools-ui/migrations/0001_init.sql +7 -0
  86. package/fixtures/extensions/fake-tools-ui/package.json +12 -0
  87. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +7 -0
  88. package/fixtures/extensions/fake-tools-ui/src/index.ts +140 -0
  89. package/package.json +67 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Capybara
2
+ Copyright 2026 Meta-1 (Tianjin Yuanyilian Technology Co., Ltd.)
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @capybara-hq/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for [Capybara](https://github.com/capybara-hq/core) extensions and the kernel: PostgreSQL / Valkey / S3 test containers,
4
+ a dual-replica harness that runs two kernel replicas against the same database and Redis, and fake
5
+ third-party servers (model providers, MCP, OpenAPI, OAuth, Slack, Lark and others). Use it as a
6
+ devDependency in an extension's tests; it needs Docker.
7
+
8
+ ```bash
9
+ npm install --save-dev @capybara-hq/testing
10
+ ```
11
+
12
+ - Fake extensions, one or more per extension point (connector, object store, tools and views,
13
+ storage use, embeds, bootstrap model provider and object store, a dependency pair, a whole IM
14
+ platform), live in
15
+ `fixtures/extensions/<name>` in the plugin pack layout; `packFixture(name, outDir)` packs one
16
+ into a plugin tgz (needs the optional peer `@capybara-hq/plugin-tools` installed), `fakeExtensionEntry(name)` gives its
17
+ `src/index.ts` for loading by path (in `createDualReplicaHarness` wherever this package is
18
+ installed; in an in-process kernel when vitest transforms the kernel). A test that edits a fake before packing
19
+ (bump the version, add a migration) packs a copy of `fakeExtensionDir(name)` instead, e.g. with
20
+ the kernel tests' `packPluginDir(fakeExtensionDir("fake-tools-ui"), edit)`, which copies the
21
+ directory to a temp dir and runs `edit` on the copy.
22
+ - Kernel-level helpers for an extension's own tests: `startTestKernel(testKernelConfig(urls, {
23
+ extensions }))` for one in-process kernel, accounts and sign-in (`createLocalAccount`, `login`,
24
+ `joinOrg`), orgs, agents, conversations and messages, event waits (`eventsOf`, `waitForTerminal`),
25
+ `openSse`, `truncateTables`, `pidOwningLocalPort`, and the kernel's `createDb` / `kernelDb`. With
26
+ these a plugin's tests import only the SDK and this package (plus model-fake, the scripted model
27
+ provider, to drive agent runs).
28
+ - `createDualReplicaHarness` starts each replica as a plain `node` child process. When an entry of
29
+ `extensions` is a TypeScript file (the plugin under test's `src/index.ts`, whose imports say
30
+ `./x.js`, or `fakeExtensionEntry(name)`), the replicas run under tsx, a dependency of this
31
+ package, resolved from it; no `NODE_OPTIONS` loader is needed. Packed plugins and package names
32
+ load in plain Node, as in production.
33
+ - How extension tests are written: "Test template (dual-replica)" in
34
+ [.agents/skills/writing-extensions](https://github.com/capybara-hq/core/tree/main/.agents/skills/writing-extensions).
35
+ - The repository: [capybara-hq/core](https://github.com/capybara-hq/core).
36
+
37
+ Capybara is on 0.x: these helpers may change in breaking ways between minor versions.
38
+
39
+ ## License
40
+
41
+ [Apache-2.0](https://github.com/capybara-hq/core/blob/main/LICENSE). See `NOTICE`.
@@ -0,0 +1,102 @@
1
+ import { Redis } from "ioredis";
2
+ /** 测试容器句柄:连接串与停止函数。 */
3
+ export interface TestContainer {
4
+ url: string;
5
+ stop(): Promise<void>;
6
+ }
7
+ /** Admin URL of the run-wide PostgreSQL started by the vitest globalSetup (see `global-setup.ts`). */
8
+ export declare const PG_ADMIN_URL_ENV = "CAPYBARA_TEST_PG_ADMIN_URL";
9
+ /** URL of the run-wide Valkey started by the vitest globalSetup. */
10
+ export declare const REDIS_URL_ENV = "CAPYBARA_TEST_REDIS_URL";
11
+ /** Set to `1` to turn sharing off: every caller starts its own containers (for debugging). */
12
+ export declare const NO_SHARED_ENV = "CAPYBARA_TEST_NO_SHARED";
13
+ /** Logical databases of the shared Valkey: DB 0 holds the allocation counter, callers get 1..1023. */
14
+ export declare const SHARED_REDIS_DATABASES = 1024;
15
+ /**
16
+ * Number of logical databases of the shared Redis, set by the globalSetup (read with
17
+ * `CONFIG GET databases` when the Redis was provided externally). Unset = {@link SHARED_REDIS_DATABASES}.
18
+ */
19
+ export declare const REDIS_DATABASES_ENV = "CAPYBARA_TEST_REDIS_DATABASES";
20
+ /** True when `CAPYBARA_TEST_NO_SHARED=1`. */
21
+ export declare function sharingDisabled(): boolean;
22
+ /** The shared PostgreSQL admin URL, or undefined when not running under the globalSetup / sharing is off. */
23
+ export declare function sharedPgAdminUrl(): string | undefined;
24
+ /** The shared Valkey URL, or undefined when not running under the globalSetup / sharing is off. */
25
+ export declare function sharedRedisUrl(): string | undefined;
26
+ /**
27
+ * Concurrent container starts allowed across all workers of a run (env
28
+ * `CAPYBARA_TEST_CONTAINER_STARTS`, default {@link DEFAULT_CONTAINER_STARTS}).
29
+ */
30
+ export declare const CONTAINER_STARTS_ENV = "CAPYBARA_TEST_CONTAINER_STARTS";
31
+ export declare const DEFAULT_CONTAINER_STARTS = 4;
32
+ /**
33
+ * Run `start` (a container start) while holding one of the run-wide start slots. Under a full
34
+ * parallel run every file starting its own Valkey at once overloads the Docker daemon, and
35
+ * testcontainers' fixed 30 s wait for the port binding times out. Limiting how many containers start
36
+ * at the same time keeps each start fast; the wait for a slot is plain queueing, not a retry. Without
37
+ * the globalSetup's Valkey (sharing disabled, or the globalSetup's own starts) it starts directly.
38
+ * `key` is the slot set (tests use their own).
39
+ */
40
+ export declare function withStartSlot<T>(start: () => Promise<T>, key?: string): Promise<T>;
41
+ /**
42
+ * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
43
+ * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
44
+ */
45
+ export declare function startPostgresContainer(opts?: {
46
+ tuned?: boolean;
47
+ }): Promise<TestContainer>;
48
+ /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
49
+ export declare function startRedisContainer(opts?: {
50
+ databases?: number;
51
+ }): Promise<TestContainer>;
52
+ /**
53
+ * Create a randomly named database on the server behind `adminUrl` (a connection that may
54
+ * `CREATE DATABASE`); `drop()` removes it with `DROP DATABASE … WITH (FORCE)`.
55
+ */
56
+ export declare function createFreshDatabase(adminUrl: string): Promise<{
57
+ url: string;
58
+ drop(): Promise<void>;
59
+ }>;
60
+ /**
61
+ * A PostgreSQL for one test file. Under the vitest globalSetup (shared mode) this is a fresh random
62
+ * database on the run-wide server and `stop()` drops it; otherwise (no globalSetup, or
63
+ * `CAPYBARA_TEST_NO_SHARED=1`) it starts a dedicated PostgreSQL 17 container and `stop()` stops it.
64
+ * Either way the URL points at an empty database the caller owns.
65
+ */
66
+ export declare function startTestPostgres(): Promise<TestContainer>;
67
+ /**
68
+ * A Redis (Valkey 8) for one test file, `redis://host:port[/db]`.
69
+ *
70
+ * By default it starts a dedicated container: bus channels (`cap:<namespace>:<topic>`) ignore the
71
+ * database number, so files that subscribe to the bus (anything that boots a kernel) must not share
72
+ * an instance. `{ shared: true }` is opt-in for callers that never subscribe to pub/sub: under the
73
+ * globalSetup it hands out a free logical database of the run-wide Valkey (`stop()` = `FLUSHDB`);
74
+ * without one it falls back to a dedicated container.
75
+ */
76
+ export declare function startTestRedis(opts?: {
77
+ shared?: boolean;
78
+ }): Promise<TestContainer>;
79
+ /** Run one command batch on a short-lived connection. */
80
+ export declare function withRedis<T>(url: string, fn: (r: Redis) => Promise<T>): Promise<T>;
81
+ /**
82
+ * S3 兼容存储的测试镜像:官方 SeaweedFS(`chrislusf/seaweedfs`,Apache-2.0),按标签加摘要固定。
83
+ * 它的 S3 网关会校验 POST 策略的 `content-length-range`、`eq $Content-Type` 与 `key` 条件。
84
+ * 可用环境变量 `CAPYBARA_TEST_S3_IMAGE` 换成私有镜像源。
85
+ */
86
+ export declare const TEST_S3_IMAGE: string;
87
+ /** {@link startTestS3} 的句柄:S3 端点、凭据与已建好的桶。 */
88
+ export interface TestS3 {
89
+ /** `http://host:port`(S3 API;用路径风格访问)。 */
90
+ endpoint: string;
91
+ accessKey: string;
92
+ secretKey: string;
93
+ bucket: string;
94
+ region: string;
95
+ stop(): Promise<void>;
96
+ }
97
+ /**
98
+ * 启动一个临时 SeaweedFS(`weed server -s3`,单容器含 master / volume / filer / S3 网关),
99
+ * 启用带凭据的 S3 鉴权,经 S3 API 建好桶 `capybara`,返回端点、凭据与停止函数。
100
+ * Returns only after one object write succeeded (the volume server has joined the master).
101
+ */
102
+ export declare function startTestS3(): Promise<TestS3>;
@@ -0,0 +1,314 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { CreateBucketCommand, DeleteObjectCommand, PutObjectCommand, S3Client, } from "@aws-sdk/client-s3";
3
+ import { PostgreSqlContainer } from "@testcontainers/postgresql";
4
+ import { Redis } from "ioredis";
5
+ import pg from "pg";
6
+ import { GenericContainer, Wait } from "testcontainers";
7
+ /** Admin URL of the run-wide PostgreSQL started by the vitest globalSetup (see `global-setup.ts`). */
8
+ export const PG_ADMIN_URL_ENV = "CAPYBARA_TEST_PG_ADMIN_URL";
9
+ /** URL of the run-wide Valkey started by the vitest globalSetup. */
10
+ export const REDIS_URL_ENV = "CAPYBARA_TEST_REDIS_URL";
11
+ /** Set to `1` to turn sharing off: every caller starts its own containers (for debugging). */
12
+ export const NO_SHARED_ENV = "CAPYBARA_TEST_NO_SHARED";
13
+ /** Logical databases of the shared Valkey: DB 0 holds the allocation counter, callers get 1..1023. */
14
+ export const SHARED_REDIS_DATABASES = 1024;
15
+ /**
16
+ * Number of logical databases of the shared Redis, set by the globalSetup (read with
17
+ * `CONFIG GET databases` when the Redis was provided externally). Unset = {@link SHARED_REDIS_DATABASES}.
18
+ */
19
+ export const REDIS_DATABASES_ENV = "CAPYBARA_TEST_REDIS_DATABASES";
20
+ /** Counter key (in DB 0 of the shared Valkey) that hands out database numbers. */
21
+ const REDIS_DB_COUNTER = "capybara-test:db";
22
+ /** True when `CAPYBARA_TEST_NO_SHARED=1`. */
23
+ export function sharingDisabled() {
24
+ return process.env[NO_SHARED_ENV] === "1";
25
+ }
26
+ /** The shared PostgreSQL admin URL, or undefined when not running under the globalSetup / sharing is off. */
27
+ export function sharedPgAdminUrl() {
28
+ return sharingDisabled() ? undefined : process.env[PG_ADMIN_URL_ENV] || undefined;
29
+ }
30
+ /** The shared Valkey URL, or undefined when not running under the globalSetup / sharing is off. */
31
+ export function sharedRedisUrl() {
32
+ return sharingDisabled() ? undefined : process.env[REDIS_URL_ENV] || undefined;
33
+ }
34
+ /**
35
+ * Concurrent container starts allowed across all workers of a run (env
36
+ * `CAPYBARA_TEST_CONTAINER_STARTS`, default {@link DEFAULT_CONTAINER_STARTS}).
37
+ */
38
+ export const CONTAINER_STARTS_ENV = "CAPYBARA_TEST_CONTAINER_STARTS";
39
+ export const DEFAULT_CONTAINER_STARTS = 4;
40
+ /** Sorted set (DB 0 of the shared Valkey) of the start slots in use, scored by acquisition time. */
41
+ const START_SLOTS_KEY = "capybara-test:container-starts";
42
+ /** A slot older than this is taken to belong to a crashed worker and is reclaimed. */
43
+ const START_SLOT_TTL_MS = 120_000;
44
+ const START_SLOT_POLL_MS = 100;
45
+ const ACQUIRE_SLOT = `
46
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', tonumber(ARGV[1]) - tonumber(ARGV[2]))
47
+ if redis.call('ZCARD', KEYS[1]) < tonumber(ARGV[3]) then
48
+ redis.call('ZADD', KEYS[1], ARGV[1], ARGV[4])
49
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
50
+ return 1
51
+ end
52
+ return 0`;
53
+ /**
54
+ * Run `start` (a container start) while holding one of the run-wide start slots. Under a full
55
+ * parallel run every file starting its own Valkey at once overloads the Docker daemon, and
56
+ * testcontainers' fixed 30 s wait for the port binding times out. Limiting how many containers start
57
+ * at the same time keeps each start fast; the wait for a slot is plain queueing, not a retry. Without
58
+ * the globalSetup's Valkey (sharing disabled, or the globalSetup's own starts) it starts directly.
59
+ * `key` is the slot set (tests use their own).
60
+ */
61
+ export async function withStartSlot(start, key = START_SLOTS_KEY) {
62
+ const url = sharingDisabled() ? undefined : process.env[REDIS_URL_ENV] || undefined;
63
+ if (url === undefined)
64
+ return start();
65
+ // Unset or not a number: the default. Otherwise at least one slot: 0, a negative or a fractional
66
+ // value below 1 would wait forever.
67
+ const raw = Number(process.env[CONTAINER_STARTS_ENV] || Number.NaN);
68
+ const limit = Number.isFinite(raw) ? Math.max(1, Math.floor(raw)) : DEFAULT_CONTAINER_STARTS;
69
+ const token = `${process.pid}-${randomBytes(6).toString("hex")}`;
70
+ const r = new Redis(url, { lazyConnect: true, maxRetriesPerRequest: 1 });
71
+ try {
72
+ await r.connect();
73
+ for (;;) {
74
+ const got = await r.eval(ACQUIRE_SLOT, 1, key, Date.now(), START_SLOT_TTL_MS, limit, token);
75
+ if (got === 1)
76
+ break;
77
+ await new Promise((resolve) => setTimeout(resolve, START_SLOT_POLL_MS));
78
+ }
79
+ try {
80
+ return await start();
81
+ }
82
+ finally {
83
+ // Releasing must not mask the start's result; an unreleased slot expires after the TTL.
84
+ await r.zrem(key, token).catch((err) => {
85
+ console.warn(`container start slot ${token} not released: ${String(err)}`);
86
+ });
87
+ }
88
+ }
89
+ finally {
90
+ r.disconnect();
91
+ }
92
+ }
93
+ /**
94
+ * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
95
+ * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
96
+ */
97
+ export async function startPostgresContainer(opts = {}) {
98
+ const image = new PostgreSqlContainer("postgres:17");
99
+ if (opts.tuned) {
100
+ image.withCommand([
101
+ "postgres",
102
+ "-c",
103
+ "max_connections=2000",
104
+ "-c",
105
+ "fsync=off",
106
+ "-c",
107
+ "synchronous_commit=off",
108
+ "-c",
109
+ "full_page_writes=off",
110
+ ]);
111
+ }
112
+ const container = await withStartSlot(() => image.start());
113
+ return {
114
+ url: container.getConnectionUri(),
115
+ stop: async () => {
116
+ await container.stop();
117
+ },
118
+ };
119
+ }
120
+ /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
121
+ export async function startRedisContainer(opts = {}) {
122
+ const image = new GenericContainer("valkey/valkey:8")
123
+ .withExposedPorts(6379)
124
+ .withWaitStrategy(Wait.forLogMessage("Ready to accept connections"));
125
+ if (opts.databases !== undefined) {
126
+ image.withCommand(["valkey-server", "--databases", String(opts.databases)]);
127
+ }
128
+ const container = await withStartSlot(() => image.start());
129
+ return {
130
+ url: `redis://${container.getHost()}:${container.getMappedPort(6379)}`,
131
+ stop: async () => {
132
+ await container.stop();
133
+ },
134
+ };
135
+ }
136
+ /**
137
+ * Create a randomly named database on the server behind `adminUrl` (a connection that may
138
+ * `CREATE DATABASE`); `drop()` removes it with `DROP DATABASE … WITH (FORCE)`.
139
+ */
140
+ export async function createFreshDatabase(adminUrl) {
141
+ const name = `cap_${randomBytes(6).toString("hex")}`;
142
+ const admin = async (sql) => {
143
+ const client = new pg.Client({ connectionString: adminUrl });
144
+ await client.connect();
145
+ try {
146
+ await client.query(sql);
147
+ }
148
+ finally {
149
+ await client.end();
150
+ }
151
+ };
152
+ await admin(`CREATE DATABASE ${name}`);
153
+ const url = new URL(adminUrl);
154
+ url.pathname = `/${name}`;
155
+ return {
156
+ url: url.toString(),
157
+ drop: () => admin(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`),
158
+ };
159
+ }
160
+ /**
161
+ * A PostgreSQL for one test file. Under the vitest globalSetup (shared mode) this is a fresh random
162
+ * database on the run-wide server and `stop()` drops it; otherwise (no globalSetup, or
163
+ * `CAPYBARA_TEST_NO_SHARED=1`) it starts a dedicated PostgreSQL 17 container and `stop()` stops it.
164
+ * Either way the URL points at an empty database the caller owns.
165
+ */
166
+ export async function startTestPostgres() {
167
+ const adminUrl = sharedPgAdminUrl();
168
+ if (adminUrl === undefined)
169
+ return startPostgresContainer();
170
+ const db = await createFreshDatabase(adminUrl);
171
+ let stopped;
172
+ return {
173
+ url: db.url,
174
+ stop: () => {
175
+ stopped ??= db.drop();
176
+ return stopped;
177
+ },
178
+ };
179
+ }
180
+ /**
181
+ * A Redis (Valkey 8) for one test file, `redis://host:port[/db]`.
182
+ *
183
+ * By default it starts a dedicated container: bus channels (`cap:<namespace>:<topic>`) ignore the
184
+ * database number, so files that subscribe to the bus (anything that boots a kernel) must not share
185
+ * an instance. `{ shared: true }` is opt-in for callers that never subscribe to pub/sub: under the
186
+ * globalSetup it hands out a free logical database of the run-wide Valkey (`stop()` = `FLUSHDB`);
187
+ * without one it falls back to a dedicated container.
188
+ */
189
+ export async function startTestRedis(opts = {}) {
190
+ const sharedUrl = opts.shared ? sharedRedisUrl() : undefined;
191
+ if (sharedUrl === undefined)
192
+ return startRedisContainer();
193
+ const databases = Number(process.env[REDIS_DATABASES_ENV]) || SHARED_REDIS_DATABASES;
194
+ const n = await withRedis(sharedUrl, (r) => r.incr(REDIS_DB_COUNTER));
195
+ // Wrap around over 1..databases-1 (DB 0 holds the counter). The FLUSHDB below can only hit a file
196
+ // that is still using the database after more than databases-1 allocations in one run (1023 with
197
+ // the default container); a run makes about 15, so a reused database is long released.
198
+ const db = 1 + ((n - 1) % (databases - 1));
199
+ const url = new URL(sharedUrl);
200
+ url.pathname = `/${db}`;
201
+ const dbUrl = url.toString();
202
+ // Start clean even if the counter wrapped around onto a database used earlier in the run.
203
+ await withRedis(dbUrl, (r) => r.flushdb());
204
+ let stopped;
205
+ return {
206
+ url: dbUrl,
207
+ stop: () => {
208
+ stopped ??= withRedis(dbUrl, (r) => r.flushdb()).then(() => undefined);
209
+ return stopped;
210
+ },
211
+ };
212
+ }
213
+ /** Run one command batch on a short-lived connection. */
214
+ export async function withRedis(url, fn) {
215
+ const r = new Redis(url, { lazyConnect: true, maxRetriesPerRequest: 1 });
216
+ try {
217
+ await r.connect();
218
+ return await fn(r);
219
+ }
220
+ finally {
221
+ r.disconnect();
222
+ }
223
+ }
224
+ /**
225
+ * S3 兼容存储的测试镜像:官方 SeaweedFS(`chrislusf/seaweedfs`,Apache-2.0),按标签加摘要固定。
226
+ * 它的 S3 网关会校验 POST 策略的 `content-length-range`、`eq $Content-Type` 与 `key` 条件。
227
+ * 可用环境变量 `CAPYBARA_TEST_S3_IMAGE` 换成私有镜像源。
228
+ */
229
+ export const TEST_S3_IMAGE = process.env.CAPYBARA_TEST_S3_IMAGE ||
230
+ "chrislusf/seaweedfs:4.48@sha256:4e61d15fd35994cb1e43e1e553dff106794841fd9a99ade2fc8c8bfce4d7872d";
231
+ /** Upper bound for creating the bucket and the first write (gateway, filer and volume server ready). */
232
+ const S3_READY_TIMEOUT_MS = 60_000;
233
+ /**
234
+ * 启动一个临时 SeaweedFS(`weed server -s3`,单容器含 master / volume / filer / S3 网关),
235
+ * 启用带凭据的 S3 鉴权,经 S3 API 建好桶 `capybara`,返回端点、凭据与停止函数。
236
+ * Returns only after one object write succeeded (the volume server has joined the master).
237
+ */
238
+ export async function startTestS3() {
239
+ const accessKey = "capybara-test";
240
+ const secretKey = "capybara-test-secret";
241
+ const bucket = "capybara";
242
+ const region = "us-east-1";
243
+ const s3Config = JSON.stringify({
244
+ identities: [
245
+ {
246
+ name: "admin",
247
+ credentials: [{ accessKey, secretKey }],
248
+ actions: ["Admin", "Read", "List", "Tagging", "Write"],
249
+ },
250
+ ],
251
+ });
252
+ const image = new GenericContainer(TEST_S3_IMAGE)
253
+ .withCopyContentToContainer([{ content: s3Config, target: "/etc/seaweedfs/s3.json" }])
254
+ .withCommand(["server", "-s3", "-s3.config=/etc/seaweedfs/s3.json", "-dir=/data"])
255
+ .withExposedPorts(8333)
256
+ .withWaitStrategy(Wait.forLogMessage(/Starting S3 API Server/));
257
+ const container = await withStartSlot(() => image.start());
258
+ const endpoint = `http://${container.getHost()}:${container.getMappedPort(8333)}`;
259
+ const client = new S3Client({
260
+ endpoint,
261
+ region,
262
+ forcePathStyle: true,
263
+ credentials: { accessKeyId: accessKey, secretAccessKey: secretKey },
264
+ });
265
+ try {
266
+ // 网关先于 filer 就绪:建桶失败时重试,直到超时
267
+ const deadline = Date.now() + S3_READY_TIMEOUT_MS;
268
+ for (;;) {
269
+ try {
270
+ await client.send(new CreateBucketCommand({ Bucket: bucket }));
271
+ break;
272
+ }
273
+ catch (e) {
274
+ if (Date.now() > deadline)
275
+ throw e;
276
+ await new Promise((r) => setTimeout(r, 250));
277
+ }
278
+ }
279
+ // The gateway and the bucket can be ready before the volume server's first heartbeat reaches
280
+ // the master: until then the master cannot grow volumes ("Not enough data nodes found") and the
281
+ // first write blocks for ~5 s, longer than a local test's 5 s timeout. Write (and delete) one
282
+ // object here, so the first write of a test never pays for that.
283
+ const warmKey = "capybara-test-warmup";
284
+ for (;;) {
285
+ try {
286
+ await client.send(new PutObjectCommand({ Bucket: bucket, Key: warmKey, Body: new Uint8Array([1]) }));
287
+ await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: warmKey }));
288
+ break;
289
+ }
290
+ catch (e) {
291
+ if (Date.now() > deadline)
292
+ throw e;
293
+ await new Promise((r) => setTimeout(r, 250));
294
+ }
295
+ }
296
+ }
297
+ catch (e) {
298
+ await container.stop();
299
+ throw e;
300
+ }
301
+ finally {
302
+ client.destroy();
303
+ }
304
+ return {
305
+ endpoint,
306
+ accessKey,
307
+ secretKey,
308
+ bucket,
309
+ region,
310
+ stop: async () => {
311
+ await container.stop();
312
+ },
313
+ };
314
+ }