@distilled.cloud/namespacelabs 0.0.0 → 1.0.0-rc.21

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 (219) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +130 -4
  3. package/lib/.lazy.json +1 -0
  4. package/lib/_bundle/lazy.js +4 -0
  5. package/lib/_bundle/sdk.js +2 -0
  6. package/lib/_bundle/sdk.js.map +1 -0
  7. package/lib/credentials.d.ts +73 -0
  8. package/lib/credentials.d.ts.map +1 -0
  9. package/lib/credentials.js +1 -0
  10. package/lib/errors.d.ts +59 -0
  11. package/lib/errors.d.ts.map +1 -0
  12. package/lib/errors.js +1 -0
  13. package/lib/index.d.ts +44 -0
  14. package/lib/index.d.ts.map +1 -0
  15. package/lib/index.js +6 -0
  16. package/lib/pagination.d.ts +2 -0
  17. package/lib/pagination.d.ts.map +1 -0
  18. package/lib/pagination.js +1 -0
  19. package/lib/protocol.d.ts +19 -0
  20. package/lib/protocol.d.ts.map +1 -0
  21. package/lib/protocol.js +1 -0
  22. package/lib/retry.d.ts +12 -0
  23. package/lib/retry.d.ts.map +1 -0
  24. package/lib/retry.js +1 -0
  25. package/lib/services/buildkite_jobs.d.ts +129 -0
  26. package/lib/services/buildkite_jobs.d.ts.map +1 -0
  27. package/lib/services/buildkite_jobs.js +2 -0
  28. package/lib/services/buildkite_jobs.js.map +1 -0
  29. package/lib/services/buildkite_queue.d.ts +186 -0
  30. package/lib/services/buildkite_queue.d.ts.map +1 -0
  31. package/lib/services/buildkite_queue.js +2 -0
  32. package/lib/services/buildkite_queue.js.map +1 -0
  33. package/lib/services/index.d.ts +3 -0
  34. package/lib/services/index.d.ts.map +1 -0
  35. package/lib/services/index.js +2 -0
  36. package/lib/services.lazy/buildkite_jobs.js +1 -0
  37. package/lib/services.lazy/buildkite_queue.js +1 -0
  38. package/lib/services.lazy/index.js +3 -0
  39. package/lib/traits.d.ts +3 -0
  40. package/lib/traits.d.ts.map +1 -0
  41. package/lib/traits.js +1 -0
  42. package/lib/unstable-services/artifacts.d.ts +268 -0
  43. package/lib/unstable-services/artifacts.d.ts.map +1 -0
  44. package/lib/unstable-services/artifacts.js +2 -0
  45. package/lib/unstable-services/artifacts.js.map +1 -0
  46. package/lib/unstable-services/audit.d.ts +157 -0
  47. package/lib/unstable-services/audit.d.ts.map +1 -0
  48. package/lib/unstable-services/audit.js +2 -0
  49. package/lib/unstable-services/audit.js.map +1 -0
  50. package/lib/unstable-services/bazel.d.ts +181 -0
  51. package/lib/unstable-services/bazel.d.ts.map +1 -0
  52. package/lib/unstable-services/bazel.js +2 -0
  53. package/lib/unstable-services/bazel.js.map +1 -0
  54. package/lib/unstable-services/bazel_cache.d.ts +126 -0
  55. package/lib/unstable-services/bazel_cache.d.ts.map +1 -0
  56. package/lib/unstable-services/bazel_cache.js +2 -0
  57. package/lib/unstable-services/bazel_cache.js.map +1 -0
  58. package/lib/unstable-services/builder.d.ts +242 -0
  59. package/lib/unstable-services/builder.d.ts.map +1 -0
  60. package/lib/unstable-services/builder.js +2 -0
  61. package/lib/unstable-services/builder.js.map +1 -0
  62. package/lib/unstable-services/compute.d.ts +1124 -0
  63. package/lib/unstable-services/compute.d.ts.map +1 -0
  64. package/lib/unstable-services/compute.js +47 -0
  65. package/lib/unstable-services/compute.js.map +1 -0
  66. package/lib/unstable-services/compute_command.d.ts +120 -0
  67. package/lib/unstable-services/compute_command.d.ts.map +1 -0
  68. package/lib/unstable-services/compute_command.js +2 -0
  69. package/lib/unstable-services/compute_command.js.map +1 -0
  70. package/lib/unstable-services/compute_observability.d.ts +165 -0
  71. package/lib/unstable-services/compute_observability.d.ts.map +1 -0
  72. package/lib/unstable-services/compute_observability.js +2 -0
  73. package/lib/unstable-services/compute_observability.js.map +1 -0
  74. package/lib/unstable-services/compute_storage.d.ts +379 -0
  75. package/lib/unstable-services/compute_storage.d.ts.map +1 -0
  76. package/lib/unstable-services/compute_storage.js +33 -0
  77. package/lib/unstable-services/compute_storage.js.map +1 -0
  78. package/lib/unstable-services/compute_usage.d.ts +283 -0
  79. package/lib/unstable-services/compute_usage.d.ts.map +1 -0
  80. package/lib/unstable-services/compute_usage.js +2 -0
  81. package/lib/unstable-services/compute_usage.js.map +1 -0
  82. package/lib/unstable-services/egress.d.ts +191 -0
  83. package/lib/unstable-services/egress.d.ts.map +1 -0
  84. package/lib/unstable-services/egress.js +2 -0
  85. package/lib/unstable-services/egress.js.map +1 -0
  86. package/lib/unstable-services/experimental_compute_reservation.d.ts +672 -0
  87. package/lib/unstable-services/experimental_compute_reservation.d.ts.map +1 -0
  88. package/lib/unstable-services/experimental_compute_reservation.js +23 -0
  89. package/lib/unstable-services/experimental_compute_reservation.js.map +1 -0
  90. package/lib/unstable-services/experimental_remote_results.d.ts +496 -0
  91. package/lib/unstable-services/experimental_remote_results.d.ts.map +1 -0
  92. package/lib/unstable-services/experimental_remote_results.js +2 -0
  93. package/lib/unstable-services/experimental_remote_results.js.map +1 -0
  94. package/lib/unstable-services/github_image.d.ts +162 -0
  95. package/lib/unstable-services/github_image.d.ts.map +1 -0
  96. package/lib/unstable-services/github_image.js +2 -0
  97. package/lib/unstable-services/github_image.js.map +1 -0
  98. package/lib/unstable-services/github_jobs.d.ts +183 -0
  99. package/lib/unstable-services/github_jobs.d.ts.map +1 -0
  100. package/lib/unstable-services/github_jobs.js +2 -0
  101. package/lib/unstable-services/github_jobs.js.map +1 -0
  102. package/lib/unstable-services/github_profile.d.ts +296 -0
  103. package/lib/unstable-services/github_profile.d.ts.map +1 -0
  104. package/lib/unstable-services/github_profile.js +2 -0
  105. package/lib/unstable-services/github_profile.js.map +1 -0
  106. package/lib/unstable-services/gradle_cache.d.ts +125 -0
  107. package/lib/unstable-services/gradle_cache.d.ts.map +1 -0
  108. package/lib/unstable-services/gradle_cache.js +2 -0
  109. package/lib/unstable-services/gradle_cache.js.map +1 -0
  110. package/lib/unstable-services/httpcache.d.ts +125 -0
  111. package/lib/unstable-services/httpcache.d.ts.map +1 -0
  112. package/lib/unstable-services/httpcache.js +2 -0
  113. package/lib/unstable-services/httpcache.js.map +1 -0
  114. package/lib/unstable-services/iam_tenant.d.ts +457 -0
  115. package/lib/unstable-services/iam_tenant.d.ts.map +1 -0
  116. package/lib/unstable-services/iam_tenant.js +45 -0
  117. package/lib/unstable-services/iam_tenant.js.map +1 -0
  118. package/lib/unstable-services/iam_tenant_membership.d.ts +114 -0
  119. package/lib/unstable-services/iam_tenant_membership.d.ts.map +1 -0
  120. package/lib/unstable-services/iam_tenant_membership.js +2 -0
  121. package/lib/unstable-services/iam_tenant_membership.js.map +1 -0
  122. package/lib/unstable-services/iam_token.d.ts +257 -0
  123. package/lib/unstable-services/iam_token.d.ts.map +1 -0
  124. package/lib/unstable-services/iam_token.js +2 -0
  125. package/lib/unstable-services/iam_token.js.map +1 -0
  126. package/lib/unstable-services/image.d.ts +222 -0
  127. package/lib/unstable-services/image.d.ts.map +1 -0
  128. package/lib/unstable-services/image.js +2 -0
  129. package/lib/unstable-services/image.js.map +1 -0
  130. package/lib/unstable-services/index.d.ts +28 -0
  131. package/lib/unstable-services/index.d.ts.map +1 -0
  132. package/lib/unstable-services/index.js +27 -0
  133. package/lib/unstable-services/private_devbox.d.ts +1180 -0
  134. package/lib/unstable-services/private_devbox.d.ts.map +1 -0
  135. package/lib/unstable-services/private_devbox.js +81 -0
  136. package/lib/unstable-services/private_devbox.js.map +1 -0
  137. package/lib/unstable-services/private_user_sessions.d.ts +145 -0
  138. package/lib/unstable-services/private_user_sessions.d.ts.map +1 -0
  139. package/lib/unstable-services/private_user_sessions.js +2 -0
  140. package/lib/unstable-services/private_user_sessions.js.map +1 -0
  141. package/lib/unstable-services/registry.d.ts +373 -0
  142. package/lib/unstable-services/registry.d.ts.map +1 -0
  143. package/lib/unstable-services/registry.js +34 -0
  144. package/lib/unstable-services/registry.js.map +1 -0
  145. package/lib/unstable-services/testing.d.ts +160 -0
  146. package/lib/unstable-services/testing.d.ts.map +1 -0
  147. package/lib/unstable-services/testing.js +2 -0
  148. package/lib/unstable-services/testing.js.map +1 -0
  149. package/lib/unstable-services/vault.d.ts +203 -0
  150. package/lib/unstable-services/vault.d.ts.map +1 -0
  151. package/lib/unstable-services/vault.js +2 -0
  152. package/lib/unstable-services/vault.js.map +1 -0
  153. package/lib/unstable-services.lazy/artifacts.js +1 -0
  154. package/lib/unstable-services.lazy/audit.js +1 -0
  155. package/lib/unstable-services.lazy/bazel.js +1 -0
  156. package/lib/unstable-services.lazy/bazel_cache.js +1 -0
  157. package/lib/unstable-services.lazy/builder.js +1 -0
  158. package/lib/unstable-services.lazy/compute.js +4 -0
  159. package/lib/unstable-services.lazy/compute_command.js +1 -0
  160. package/lib/unstable-services.lazy/compute_observability.js +1 -0
  161. package/lib/unstable-services.lazy/compute_storage.js +4 -0
  162. package/lib/unstable-services.lazy/compute_usage.js +1 -0
  163. package/lib/unstable-services.lazy/egress.js +1 -0
  164. package/lib/unstable-services.lazy/experimental_compute_reservation.js +4 -0
  165. package/lib/unstable-services.lazy/experimental_remote_results.js +1 -0
  166. package/lib/unstable-services.lazy/github_image.js +1 -0
  167. package/lib/unstable-services.lazy/github_jobs.js +1 -0
  168. package/lib/unstable-services.lazy/github_profile.js +1 -0
  169. package/lib/unstable-services.lazy/gradle_cache.js +1 -0
  170. package/lib/unstable-services.lazy/httpcache.js +1 -0
  171. package/lib/unstable-services.lazy/iam_tenant.js +4 -0
  172. package/lib/unstable-services.lazy/iam_tenant_membership.js +1 -0
  173. package/lib/unstable-services.lazy/iam_token.js +1 -0
  174. package/lib/unstable-services.lazy/image.js +1 -0
  175. package/lib/unstable-services.lazy/index.js +3 -0
  176. package/lib/unstable-services.lazy/private_devbox.js +4 -0
  177. package/lib/unstable-services.lazy/private_user_sessions.js +1 -0
  178. package/lib/unstable-services.lazy/registry.js +4 -0
  179. package/lib/unstable-services.lazy/testing.js +1 -0
  180. package/lib/unstable-services.lazy/vault.js +1 -0
  181. package/package.json +89 -2
  182. package/src/credentials.ts +208 -0
  183. package/src/errors.ts +71 -0
  184. package/src/index.ts +50 -0
  185. package/src/pagination.ts +1 -0
  186. package/src/protocol.ts +83 -0
  187. package/src/retry.ts +28 -0
  188. package/src/services/buildkite_jobs.ts +230 -0
  189. package/src/services/buildkite_queue.ts +453 -0
  190. package/src/services/index.ts +3 -0
  191. package/src/traits.ts +36 -0
  192. package/src/unstable-services/artifacts.ts +769 -0
  193. package/src/unstable-services/audit.ts +323 -0
  194. package/src/unstable-services/bazel.ts +423 -0
  195. package/src/unstable-services/bazel_cache.ts +219 -0
  196. package/src/unstable-services/builder.ts +576 -0
  197. package/src/unstable-services/compute.ts +2991 -0
  198. package/src/unstable-services/compute_command.ts +220 -0
  199. package/src/unstable-services/compute_observability.ts +436 -0
  200. package/src/unstable-services/compute_storage.ts +1167 -0
  201. package/src/unstable-services/compute_usage.ts +738 -0
  202. package/src/unstable-services/egress.ts +516 -0
  203. package/src/unstable-services/experimental_compute_reservation.ts +1499 -0
  204. package/src/unstable-services/experimental_remote_results.ts +1165 -0
  205. package/src/unstable-services/github_image.ts +301 -0
  206. package/src/unstable-services/github_jobs.ts +389 -0
  207. package/src/unstable-services/github_profile.ts +729 -0
  208. package/src/unstable-services/gradle_cache.ts +271 -0
  209. package/src/unstable-services/httpcache.ts +271 -0
  210. package/src/unstable-services/iam_tenant.ts +1720 -0
  211. package/src/unstable-services/iam_tenant_membership.ts +253 -0
  212. package/src/unstable-services/iam_token.ts +788 -0
  213. package/src/unstable-services/image.ts +602 -0
  214. package/src/unstable-services/index.ts +28 -0
  215. package/src/unstable-services/private_devbox.ts +4256 -0
  216. package/src/unstable-services/private_user_sessions.ts +410 -0
  217. package/src/unstable-services/registry.ts +1242 -0
  218. package/src/unstable-services/testing.ts +394 -0
  219. package/src/unstable-services/vault.ts +522 -0
@@ -0,0 +1,208 @@
1
+ import * as EffectConfig from "@distilled.cloud/core/config";
2
+ import { ConfigError } from "@distilled.cloud/core/errors";
3
+ import { invalidHostLabelConfig } from "@distilled.cloud/core/protocol-http";
4
+ import * as Context from "effect/Context";
5
+ import * as Effect from "effect/Effect";
6
+ import * as FileSystem from "effect/FileSystem";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Option from "effect/Option";
9
+ import * as Redacted from "effect/Redacted";
10
+ import { TokenFileUnreadable } from "./errors.ts";
11
+
12
+ export const DEFAULT_REGION = "us";
13
+ export const DEFAULT_GLOBAL_BASE_URL = "https://global.namespaceapis.com";
14
+ export const DEFAULT_PRIVATE_API_BASE_URL = "https://private-api.global.namespaceapis.com";
15
+ /** Where a Namespace instance or runner mounts its workload token. */
16
+ export const DEFAULT_TOKEN_FILE = "/var/run/nsc/token.json";
17
+
18
+ export const computeBaseUrlFor = (region: string): string =>
19
+ `https://${region}.compute.namespaceapis.com`;
20
+ export const storageBaseUrlFor = (region: string): string =>
21
+ `https://${region}.storage.namespaceapis.com`;
22
+
23
+ export interface Config {
24
+ readonly token: Redacted.Redacted<string>;
25
+ readonly region: string;
26
+ /** `namespace.cloud.compute.*`, `builder`, `experimental.compute`: `https://<region>.compute.namespaceapis.com`. */
27
+ readonly computeBaseUrl: string;
28
+ /** `namespace.cloud.storage.*` (artifacts): `https://<region>.storage.namespaceapis.com`. */
29
+ readonly storageBaseUrl: string;
30
+ /** IAM, registry, vault, images, caches, egress and everything else global. */
31
+ readonly globalBaseUrl: string;
32
+ /** `namespace.private.*` (devboxes, sessions) and `namespace.cloud.github.*`. */
33
+ readonly privateApiBaseUrl: string;
34
+ }
35
+
36
+ export interface Hosts {
37
+ readonly region?: string;
38
+ readonly computeBaseUrl?: string;
39
+ readonly storageBaseUrl?: string;
40
+ readonly globalBaseUrl?: string;
41
+ readonly privateApiBaseUrl?: string;
42
+ }
43
+
44
+ export interface Options extends Hosts {
45
+ readonly token: Redacted.Redacted<string>;
46
+ }
47
+
48
+ export const resolveConfig = (options: Options): Config => {
49
+ const region = options.region ?? DEFAULT_REGION;
50
+ return {
51
+ token: options.token,
52
+ region,
53
+ computeBaseUrl: options.computeBaseUrl ?? computeBaseUrlFor(region),
54
+ storageBaseUrl: options.storageBaseUrl ?? storageBaseUrlFor(region),
55
+ globalBaseUrl: options.globalBaseUrl ?? DEFAULT_GLOBAL_BASE_URL,
56
+ privateApiBaseUrl: options.privateApiBaseUrl ?? DEFAULT_PRIVATE_API_BASE_URL,
57
+ };
58
+ };
59
+
60
+ /**
61
+ * `hosts`, failing with `ConfigError` when the region is not one DNS label:
62
+ * it becomes a label of the compute and storage host names. The layers run
63
+ * this once, when they are built.
64
+ */
65
+ const checkHosts = <H extends Hosts>(hosts: H): Effect.Effect<H, ConfigError> => {
66
+ const invalid =
67
+ hosts.region === undefined
68
+ ? undefined
69
+ : invalidHostLabelConfig("Namespace region", hosts.region);
70
+ return invalid === undefined ? Effect.succeed(hosts) : Effect.fail(invalid);
71
+ };
72
+
73
+ /**
74
+ * Resolves the current credentials on every request. A layer here reads and
75
+ * checks the region and host settings when it is built, so the effect fails
76
+ * only for what it does at run time: the token-file layers read the file
77
+ * again on every resolution, and fail with {@link TokenFileUnreadable}.
78
+ */
79
+ export class Credentials
80
+ extends /*@__PURE__*/ Context.Service<Credentials, Effect.Effect<Config, TokenFileUnreadable>>()(
81
+ "NamespaceLabsCredentials",
82
+ ) {}
83
+
84
+ const optionalString = (name: string) =>
85
+ EffectConfig.option(EffectConfig.String(name)).pipe(EffectConfig.map(Option.getOrUndefined));
86
+
87
+ /**
88
+ * `NSC_REGION` (default `us`) selects the compute and storage hosts.
89
+ * `NSC_COMPUTE_URL` (or `NSC_ENDPOINT`, which Namespace sets inside an
90
+ * instance), `NSC_STORAGE_URL`, `NSC_GLOBAL_URL` and `NSC_PRIVATE_API_URL`
91
+ * override a host.
92
+ */
93
+ const hostsConfig = /*@__PURE__*/ EffectConfig.all({
94
+ region: /*@__PURE__*/ EffectConfig.String("NSC_REGION").pipe(
95
+ /*@__PURE__*/ EffectConfig.withDefault(DEFAULT_REGION),
96
+ ),
97
+ computeBaseUrl: /*@__PURE__*/ EffectConfig.String("NSC_COMPUTE_URL").pipe(
98
+ /*@__PURE__*/ EffectConfig.orElse(() => EffectConfig.String("NSC_ENDPOINT")),
99
+ EffectConfig.option,
100
+ /*@__PURE__*/ EffectConfig.map(Option.getOrUndefined),
101
+ ),
102
+ storageBaseUrl: /*@__PURE__*/ optionalString("NSC_STORAGE_URL"),
103
+ globalBaseUrl: /*@__PURE__*/ optionalString("NSC_GLOBAL_URL"),
104
+ privateApiBaseUrl: /*@__PURE__*/ optionalString("NSC_PRIVATE_API_URL"),
105
+ });
106
+
107
+ const configError = (message: string) => () => new ConfigError({ message });
108
+
109
+ /**
110
+ * Credentials from the environment: `NSC_TOKEN` (required) plus the host
111
+ * variables. The environment is read, and the region checked, once: when
112
+ * the layer is built.
113
+ */
114
+ export const CredentialsFromEnv: Layer.Layer<Credentials, ConfigError> = /*@__PURE__*/ Layer.effect(
115
+ Credentials,
116
+ /*@__PURE__*/ EffectConfig.all({
117
+ token: /*@__PURE__*/ EffectConfig.Redacted("NSC_TOKEN"),
118
+ hosts: hostsConfig,
119
+ }).pipe(
120
+ /*@__PURE__*/ Effect.mapError(configError("NSC_TOKEN environment variable is required")),
121
+ /*@__PURE__*/ Effect.flatMap(({ token, hosts }) => checkHosts({ token, ...hosts })),
122
+ /*@__PURE__*/ Effect.map((options) => Effect.succeed(resolveConfig(options))),
123
+ ),
124
+ );
125
+
126
+ const readTokenFile = (
127
+ fs: FileSystem.FileSystem,
128
+ path: string,
129
+ ): Effect.Effect<Redacted.Redacted<string>, TokenFileUnreadable> => {
130
+ const unreadable = (message: string) => () => new TokenFileUnreadable({ message, path });
131
+ return fs.readFileString(path).pipe(
132
+ Effect.mapError(unreadable(`Namespace token file ${path} could not be read`)),
133
+ Effect.flatMap((text) => {
134
+ const parsed = Effect.try({
135
+ try: () => JSON.parse(text) as { readonly bearer_token?: unknown },
136
+ catch: unreadable(`Namespace token file ${path} is not JSON`),
137
+ });
138
+ return Effect.flatMap(parsed, ({ bearer_token }) =>
139
+ typeof bearer_token === "string" && bearer_token.length > 0
140
+ ? Effect.succeed(Redacted.make(bearer_token))
141
+ : Effect.fail(
142
+ unreadable(
143
+ `Namespace token file ${path} has no bearer_token; exchange a session token with privateUserSessions.issueTenantTokenFromSession`,
144
+ )(),
145
+ ),
146
+ );
147
+ }),
148
+ );
149
+ };
150
+
151
+ /** A layer for checked `hosts` that reads `bearer_token` from `path` on every resolution. */
152
+ const tokenFileLayer = (
153
+ settings: Effect.Effect<{ readonly path: string; readonly hosts: Hosts }, ConfigError>,
154
+ ): Layer.Layer<Credentials, ConfigError, FileSystem.FileSystem> =>
155
+ Layer.effect(
156
+ Credentials,
157
+ Effect.gen(function* () {
158
+ const fs = yield* FileSystem.FileSystem;
159
+ const { path, hosts: unchecked } = yield* settings;
160
+ const hosts = yield* checkHosts(unchecked);
161
+ return Effect.map(readTokenFile(fs, path), (token) => resolveConfig({ token, ...hosts }));
162
+ }),
163
+ );
164
+
165
+ /**
166
+ * Credentials from the token file a Namespace workload is given: `NSC_TOKEN_FILE`,
167
+ * else `/var/run/nsc/token.json`. The file is re-read on every resolution because
168
+ * Namespace refreshes it; host variables as in {@link CredentialsFromEnv}. The
169
+ * variables are read, and the region checked, once: when the layer is built.
170
+ */
171
+ export const CredentialsFromTokenFile: Layer.Layer<
172
+ Credentials,
173
+ ConfigError,
174
+ FileSystem.FileSystem
175
+ > = /*@__PURE__*/ tokenFileLayer(
176
+ /*@__PURE__*/ EffectConfig.all({
177
+ path: /*@__PURE__*/ EffectConfig.String("NSC_TOKEN_FILE").pipe(
178
+ /*@__PURE__*/ EffectConfig.withDefault(DEFAULT_TOKEN_FILE),
179
+ ),
180
+ hosts: hostsConfig,
181
+ }).pipe(
182
+ /*@__PURE__*/ Effect.mapError(configError("Namespace host configuration could not be read")),
183
+ ),
184
+ );
185
+
186
+ /**
187
+ * Convenience layer from a tenant token, an optional region and host
188
+ * overrides. The region is checked when the layer is built.
189
+ */
190
+ export const credentials = (options: Options): Layer.Layer<Credentials, ConfigError> =>
191
+ Layer.effect(
192
+ Credentials,
193
+ Effect.map(checkHosts(options), (checked) => Effect.succeed(resolveConfig(checked))),
194
+ );
195
+
196
+ /** Convenience layer from a tenant token alone. */
197
+ export const fromToken = (token: Redacted.Redacted<string>): Layer.Layer<Credentials> =>
198
+ Layer.succeed(Credentials, Effect.succeed(resolveConfig({ token })));
199
+
200
+ /**
201
+ * Convenience layer reading `bearer_token` from a token file on every
202
+ * resolution. The region is checked when the layer is built.
203
+ */
204
+ export const fromTokenFile = (
205
+ path: string,
206
+ hosts: Hosts = {},
207
+ ): Layer.Layer<Credentials, ConfigError, FileSystem.FileSystem> =>
208
+ tokenFileLayer(Effect.succeed({ path, hosts }));
package/src/errors.ts ADDED
@@ -0,0 +1,71 @@
1
+ export {
2
+ API_ERRORS,
3
+ BadGateway,
4
+ BadRequest,
5
+ Conflict,
6
+ ConfigError,
7
+ DEFAULT_ERRORS,
8
+ Forbidden,
9
+ GatewayTimeout,
10
+ HTTP_STATUS_MAP,
11
+ InternalServerError,
12
+ Locked,
13
+ NotFound,
14
+ ServiceUnavailable,
15
+ TooManyRequests,
16
+ Unauthorized,
17
+ UnprocessableEntity,
18
+ } from "@distilled.cloud/core/errors";
19
+ import * as Category from "@distilled.cloud/core/category";
20
+ import { API_ERRORS } from "@distilled.cloud/core/errors";
21
+ import type { DefaultErrors as CoreDefaultErrors } from "@distilled.cloud/core/errors";
22
+ import * as Schema from "@distilled.cloud/core/schema-lite-typed";
23
+
24
+ /**
25
+ * A failed response no declared error class matches. `code` is the Connect
26
+ * error code (`unknown`, `data_loss`, ...) and `details` the Connect error
27
+ * details, which carry the request id.
28
+ */
29
+ export class UnknownNamespaceLabsError
30
+ extends /*@__PURE__*/ Schema.TaggedError<UnknownNamespaceLabsError>()(
31
+ "UnknownNamespaceLabsError",
32
+ {
33
+ code: /*@__PURE__*/ Schema.optional(Schema.String),
34
+ message: /*@__PURE__*/ Schema.optional(Schema.String),
35
+ details: /*@__PURE__*/ Schema.optional(Schema.Unknown),
36
+ body: Schema.Unknown,
37
+ },
38
+ ).pipe(Category.withServerError) {}
39
+
40
+ export class NamespaceLabsParseError
41
+ extends /*@__PURE__*/ Schema.TaggedError<NamespaceLabsParseError>()("NamespaceLabsParseError", {
42
+ body: Schema.Unknown,
43
+ cause: Schema.Unknown,
44
+ }).pipe(Category.withParseError) {}
45
+
46
+ /**
47
+ * The token file the credentials read on every request could not be used:
48
+ * it could not be read, is not JSON, or holds no `bearer_token`. It is a
49
+ * failure at run time (Namespace rewrites the file), so it is not a
50
+ * `ConfigError`.
51
+ */
52
+ export class TokenFileUnreadable
53
+ extends /*@__PURE__*/ Schema.TaggedError<TokenFileUnreadable>()("TokenFileUnreadable", {
54
+ message: Schema.String,
55
+ /** The path of the token file. */
56
+ path: Schema.String,
57
+ }).pipe(Category.withAuthError) {}
58
+
59
+ export type ClientErrors = UnknownNamespaceLabsError | NamespaceLabsParseError;
60
+
61
+ export type DefaultErrors = CoreDefaultErrors | ClientErrors;
62
+
63
+ /**
64
+ * The errors declared on the Namespace service: any operation can return
65
+ * them, and every generated operation lists them as its `serviceErrors`.
66
+ * Today that is each of core's status classes (401, 403, 404, 429, the
67
+ * 5xx ...), for a failed response whose status and Connect code match none
68
+ * of the operation's own errors.
69
+ */
70
+ export const NamespaceLabsServiceErrors = API_ERRORS;
71
+ export type NamespaceLabsServiceError = InstanceType<(typeof NamespaceLabsServiceErrors)[number]>;
package/src/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @distilled.cloud/namespacelabs -- Namespace (namespace.so) SDK for Effect.
3
+ *
4
+ * `./services` and `./unstable-services` are generated by
5
+ * `scripts/generate.ts` from the Smithy models that `scripts/convert.ts`
6
+ * converts from Namespace's public protobuf API (`buf.build/namespace/cloud`).
7
+ * Services in `v1beta` and `namespace.experimental.*` packages are under
8
+ * `@distilled.cloud/namespacelabs/unstable/<name>`. Everything else in this
9
+ * folder is hand-written.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { Effect, Layer } from "effect";
14
+ * import * as FetchHttpClient from "effect/http/FetchHttpClient";
15
+ * import * as NamespaceLabs from "@distilled.cloud/namespacelabs";
16
+ * import * as Compute from "@distilled.cloud/namespacelabs/unstable/compute";
17
+ *
18
+ * const program = Effect.gen(function* () {
19
+ * const created = yield* Compute.createInstance({
20
+ * shape: { virtualCpu: 2, memoryMegabytes: 4096, os: "linux", machineArch: "amd64" },
21
+ * deadline: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
22
+ * });
23
+ * const instanceId = created.metadata?.instanceId;
24
+ * if (instanceId === undefined) return undefined;
25
+ * const instance = yield* Compute.describeInstance({ instanceId });
26
+ * yield* Compute.destroyInstance({ instanceId });
27
+ * return instance.metadata?.status;
28
+ * });
29
+ *
30
+ * const Live = Layer.mergeAll(
31
+ * FetchHttpClient.layer,
32
+ * NamespaceLabs.CredentialsFromEnv,
33
+ * );
34
+ *
35
+ * program.pipe(Effect.provide(Live), Effect.runPromise);
36
+ * ```
37
+ */
38
+ export * from "./credentials.ts";
39
+ export * from "./errors.ts";
40
+ export * as T from "./traits.ts";
41
+ export {
42
+ NamespaceLabsProtocol,
43
+ baseUrlFor,
44
+ hostFor,
45
+ type Host,
46
+ type NamespaceLabsOpError,
47
+ type NamespaceLabsOpContext,
48
+ } from "./protocol.ts";
49
+ export { paginateCursor } from "./pagination.ts";
50
+ export * as Retry from "./retry.ts";
@@ -0,0 +1 @@
1
+ export { paginateCursor } from "@distilled.cloud/core/pagination";
@@ -0,0 +1,83 @@
1
+ import type { ErrorOf } from "@distilled.cloud/core/protocol";
2
+ import { restProtocol, type RestErrorEnvelope } from "@distilled.cloud/core/protocol-rest";
3
+ import * as Effect from "effect/Effect";
4
+ import type * as HttpClient from "effect/http/HttpClient";
5
+ import * as Redacted from "effect/Redacted";
6
+ import { Credentials, type Config } from "./credentials.ts";
7
+ import {
8
+ UnknownNamespaceLabsError,
9
+ NamespaceLabsParseError,
10
+ type NamespaceLabsServiceError,
11
+ } from "./errors.ts";
12
+
13
+ /**
14
+ * What every generated Namespace operation fails with besides its own
15
+ * errors: the service's errors, the protocol's, and what resolving the
16
+ * credentials fails with. Generated service files annotate operations with
17
+ * `API.OperationMethod<I, O, NamespaceLabsOpError, NamespaceLabsOpContext>`
18
+ * explicitly.
19
+ */
20
+ export type NamespaceLabsOpError =
21
+ | NamespaceLabsServiceError
22
+ | ErrorOf<typeof NamespaceLabsProtocol>;
23
+
24
+ export type NamespaceLabsOpContext = Credentials | HttpClient.HttpClient;
25
+
26
+ export type Host = "compute" | "storage" | "global" | "privateApi";
27
+
28
+ const HOST_BY_PACKAGE_PREFIX: ReadonlyArray<readonly [prefix: string, host: Host]> = [
29
+ ["namespace.cloud.compute.", "compute"],
30
+ ["namespace.cloud.builder.", "compute"],
31
+ ["namespace.experimental.compute.", "compute"],
32
+ ["namespace.cloud.storage.", "storage"],
33
+ ["namespace.cloud.github.", "privateApi"],
34
+ ["namespace.private.", "privateApi"],
35
+ ];
36
+
37
+ /** The host serving `uri` (`/<package>.<Service>/<Method>`), by proto package. */
38
+ export const hostFor = (uri: string): Host => {
39
+ const service = uri.replace(/^\//, "").split("/")[0] ?? "";
40
+ return HOST_BY_PACKAGE_PREFIX.find(([prefix]) => service.startsWith(prefix))?.[1] ?? "global";
41
+ };
42
+
43
+ export const baseUrlFor = (creds: Config, uri: string): string => {
44
+ switch (hostFor(uri)) {
45
+ case "compute":
46
+ return creds.computeBaseUrl;
47
+ case "storage":
48
+ return creds.storageBaseUrl;
49
+ case "privateApi":
50
+ return creds.privateApiBaseUrl;
51
+ case "global":
52
+ return creds.globalBaseUrl;
53
+ }
54
+ };
55
+
56
+ /** Connect error bodies are `{ code, message, details? }`. */
57
+ const errorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
58
+ if (body === null || typeof body !== "object") return undefined;
59
+ const b = body as Record<string, unknown>;
60
+ return {
61
+ code: typeof b.code === "string" ? b.code : undefined,
62
+ message: typeof b.message === "string" ? b.message : undefined,
63
+ };
64
+ };
65
+
66
+ const errorDetails = (body: unknown): unknown =>
67
+ body !== null && typeof body === "object" ? (body as Record<string, unknown>).details : undefined;
68
+
69
+ export const NamespaceLabsProtocol = /*@__PURE__*/ restProtocol({
70
+ credentials: /*@__PURE__*/ Effect.flatten(Credentials),
71
+ baseUrl: (creds, target) => baseUrlFor(creds, target.uri),
72
+ headers: (creds) => ({ Authorization: `Bearer ${Redacted.value(creds.token)}` }),
73
+ emptyJsonBody: true,
74
+ errorEnvelope,
75
+ unknownError: ({ code, message, body }) =>
76
+ new UnknownNamespaceLabsError({
77
+ code: typeof code === "string" ? code : code !== undefined ? String(code) : undefined,
78
+ message,
79
+ details: errorDetails(body),
80
+ body,
81
+ }),
82
+ parseError: ({ body, cause }) => new NamespaceLabsParseError({ body, cause }),
83
+ });
package/src/retry.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { type Policy, throttlingFactory, transientFactory } from "@distilled.cloud/core/retry";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+
6
+ export {
7
+ type Factory,
8
+ type Options,
9
+ type Policy,
10
+ capped,
11
+ jittered,
12
+ makeDefault,
13
+ throttlingFactory,
14
+ throttlingOptions,
15
+ transientFactory,
16
+ transientOptions,
17
+ } from "@distilled.cloud/core/retry";
18
+
19
+ export class Retry extends Context.Service<Retry, Policy>()("NamespaceLabsRetry") {}
20
+
21
+ export const policy = (optionsOrFactory: Policy) =>
22
+ Effect.provide(Layer.succeed(Retry, optionsOrFactory));
23
+
24
+ export const none = Effect.provide(Layer.succeed(Retry, { while: () => false }));
25
+
26
+ export const throttling = policy(throttlingFactory);
27
+
28
+ export const transient = policy(transientFactory);
@@ -0,0 +1,230 @@
1
+ import * as API from "@distilled.cloud/core/api";
2
+ import * as C from "@distilled.cloud/core/category";
3
+ // AUTO-GENERATED by scripts/generate.ts from .generated-specs (buf.build/namespace/cloud -> smithy). Do not edit.
4
+ import * as S from "@distilled.cloud/core/schema-lite";
5
+ import * as __L from "@distilled.cloud/core/schema-lite";
6
+ import { NamespaceLabsServiceErrors } from "../errors.ts";
7
+ import {
8
+ NamespaceLabsProtocol,
9
+ type NamespaceLabsOpError,
10
+ type NamespaceLabsOpContext,
11
+ } from "../protocol.ts";
12
+ import * as Retry from "../retry.ts";
13
+ import * as T from "../traits.ts";
14
+ // Schema table, filled on first reach (see __S at the end).
15
+ const __s: any[] = [];
16
+
17
+ export type { NamespaceLabsOpError, NamespaceLabsOpContext };
18
+
19
+ /** Span facts shared by every operation (com.distilled.telemetry#service). */
20
+ const TELEMETRY = {
21
+ system: "namespacelabs-api",
22
+ responseHeaders: [
23
+ { header: "x-request-id", name: "http.response.header.x-request-id", transform: "list" },
24
+ { header: "request-id", name: "http.response.header.request-id", transform: "list" },
25
+ ],
26
+ prefix: "Namespacelabs",
27
+ service: "JobsService",
28
+ propagate: "w3c",
29
+ } as const;
30
+
31
+ export class AlreadyExists
32
+ extends /*@__PURE__*/ T.applyErrorMatchers(
33
+ /*@__PURE__*/ S.TaggedError<AlreadyExists>()("AlreadyExists", {
34
+ message: S.String,
35
+ body: S.Unknown,
36
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
37
+ }).pipe(C.withConflictError),
38
+ [{ status: 409, body: { "/code": "already_exists" } }],
39
+ ) {}
40
+
41
+ export class FailedPrecondition
42
+ extends /*@__PURE__*/ T.applyErrorMatchers(
43
+ /*@__PURE__*/ S.TaggedError<FailedPrecondition>()("FailedPrecondition", {
44
+ message: S.String,
45
+ body: S.Unknown,
46
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
47
+ }).pipe(C.withBadRequestError),
48
+ [{ status: 400, body: { "/code": "failed_precondition" } }],
49
+ ) {}
50
+
51
+ export class InvalidArgument
52
+ extends /*@__PURE__*/ T.applyErrorMatchers(
53
+ /*@__PURE__*/ S.TaggedError<InvalidArgument>()("InvalidArgument", {
54
+ message: S.String,
55
+ body: S.Unknown,
56
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
57
+ }).pipe(C.withBadRequestError),
58
+ [{ status: 400, body: { "/code": "invalid_argument" } }],
59
+ ) {}
60
+
61
+ export class NotFound
62
+ extends /*@__PURE__*/ T.applyErrorMatchers(
63
+ /*@__PURE__*/ S.TaggedError<NotFound>()("NotFound", {
64
+ message: S.String,
65
+ body: S.Unknown,
66
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
67
+ }).pipe(C.withBadRequestError),
68
+ [{ status: 404 }],
69
+ ) {}
70
+
71
+ export class PermissionDenied
72
+ extends /*@__PURE__*/ T.applyErrorMatchers(
73
+ /*@__PURE__*/ S.TaggedError<PermissionDenied>()("PermissionDenied", {
74
+ message: S.String,
75
+ body: S.Unknown,
76
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
77
+ }).pipe(C.withAuthError),
78
+ [{ status: 403 }],
79
+ ) {}
80
+
81
+ export class ResourceExhausted
82
+ extends /*@__PURE__*/ T.applyErrorMatchers(
83
+ /*@__PURE__*/ S.TaggedError<ResourceExhausted>()("ResourceExhausted", {
84
+ message: S.String,
85
+ body: S.Unknown,
86
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
87
+ retryAfter: /*@__PURE__*/ S.optional(S.Duration),
88
+ }).pipe(C.withThrottlingError),
89
+ [{ status: 429 }],
90
+ ) {}
91
+
92
+ export class Unauthenticated
93
+ extends /*@__PURE__*/ T.applyErrorMatchers(
94
+ /*@__PURE__*/ S.TaggedError<Unauthenticated>()("Unauthenticated", {
95
+ message: S.String,
96
+ body: S.Unknown,
97
+ headers: /*@__PURE__*/ S.optional(/*@__PURE__*/ S.Record(S.String, S.String)),
98
+ }).pipe(C.withAuthError),
99
+ [{ status: 401 }],
100
+ ) {}
101
+
102
+ export interface DescribeJobRequest {
103
+ /** The Buildkite job ID to describe */
104
+ jobId?: string | undefined;
105
+ }
106
+ export interface RunnerInfo {
107
+ /** Instance ID of the underlying compute instance. */
108
+ instanceId: string;
109
+ }
110
+ /** Job represents a Buildkite command job and its associated build, pipeline, and runner. */
111
+ export interface Job {
112
+ /** Unique Buildkite job ID. */
113
+ jobId: string;
114
+ /** Repository associated with the job. */
115
+ repository: string;
116
+ /** Unique Buildkite build ID. */
117
+ buildId: string;
118
+ /** Build number within the pipeline. */
119
+ buildNumber: string;
120
+ /** Slug of the Buildkite pipeline. */
121
+ pipelineSlug: string;
122
+ /** Label of the Buildkite job. */
123
+ jobName: string;
124
+ /** e.g. "passed", "failed", "canceled", "timed_out", "skipped", "broken" */
125
+ jobState: string;
126
+ /** URL to view the job in Buildkite. */
127
+ jobUrl: string;
128
+ /** When the job was scheduled. */
129
+ scheduledAt?: string | undefined;
130
+ /** When the job started running. */
131
+ startedAt?: string | undefined;
132
+ /** When the job completed. */
133
+ completedAt?: string | undefined;
134
+ /** Runner information, if assigned. */
135
+ runner?: RunnerInfo | undefined;
136
+ /** Branch associated with the build. */
137
+ branch: string;
138
+ /** Commit SHA associated with the build. */
139
+ commitSha: string;
140
+ }
141
+ export interface DescribeJobResponse {
142
+ /** The described Buildkite job. */
143
+ job?: Job | undefined;
144
+ }
145
+ export type DescribeJobError =
146
+ | InvalidArgument
147
+ | FailedPrecondition
148
+ | Unauthenticated
149
+ | PermissionDenied
150
+ | NotFound
151
+ | AlreadyExists
152
+ | ResourceExhausted
153
+ | NamespaceLabsOpError;
154
+ /** Describes a Buildkite job by its job ID. */
155
+ export const describeJob: API.OperationMethod<
156
+ DescribeJobRequest,
157
+ DescribeJobResponse,
158
+ DescribeJobError,
159
+ NamespaceLabsOpContext
160
+ > = /*@__PURE__*/ API.make(() => ({
161
+ input: __S(0, __c0, 0) as any as S.Schema<DescribeJobRequest>,
162
+ output: __S(3, __c0, 3) as any as S.Schema<DescribeJobResponse>,
163
+ errors: [
164
+ InvalidArgument,
165
+ FailedPrecondition,
166
+ Unauthenticated,
167
+ PermissionDenied,
168
+ NotFound,
169
+ AlreadyExists,
170
+ ResourceExhausted,
171
+ ],
172
+ serviceErrors: NamespaceLabsServiceErrors,
173
+ protocol: NamespaceLabsProtocol,
174
+ retry: Retry.Retry,
175
+ telemetry: TELEMETRY,
176
+ span: "DescribeJob",
177
+ }));
178
+
179
+ // Schema builders: each runs one schema initializer, on that schema's first use.
180
+ function __c0(j: number): any {
181
+ switch (j) {
182
+ case 0:
183
+ return S.suspend(() =>
184
+ S.Struct({
185
+ jobId: S.optional(S.String),
186
+ }).pipe(
187
+ T.Http({
188
+ method: "POST",
189
+ uri: "/namespace.cloud.buildkite.JobsService/DescribeJob",
190
+ code: 200,
191
+ }),
192
+ ),
193
+ ).annotate({ identifier: "DescribeJobRequest" });
194
+ case 1:
195
+ return S.suspend(() =>
196
+ S.Struct({
197
+ instanceId: S.String,
198
+ }),
199
+ ).annotate({ identifier: "RunnerInfo" });
200
+ case 2:
201
+ return S.suspend(() =>
202
+ S.Struct({
203
+ jobId: S.String,
204
+ repository: S.String,
205
+ buildId: S.String,
206
+ buildNumber: S.String,
207
+ pipelineSlug: S.String,
208
+ jobName: S.String,
209
+ jobState: S.String,
210
+ jobUrl: S.String,
211
+ scheduledAt: S.optional(S.String),
212
+ startedAt: S.optional(S.String),
213
+ completedAt: S.optional(S.String),
214
+ runner: S.optional(__S(1, __c0, 1)),
215
+ branch: S.String,
216
+ commitSha: S.String,
217
+ }),
218
+ ).annotate({ identifier: "Job" });
219
+ case 3:
220
+ return S.suspend(() =>
221
+ S.Struct({
222
+ job: S.optional(__S(2, __c0, 2)),
223
+ }),
224
+ ).annotate({ identifier: "DescribeJobResponse" });
225
+ }
226
+ }
227
+ // Schema table: entry i is schema j of builder f, made on first reach.
228
+ function __S(i: number, f: (j: number) => unknown, j: number): any {
229
+ return (__s[i] ??= __L.at(f, j));
230
+ }