@reventlessdev/reventless-seed 1.0.0-alpha.16 → 1.0.0-alpha.18

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 (107) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/ReventlessSeed.cmi +0 -0
  4. package/lib/bs/ReventlessSeed.cmt +0 -0
  5. package/lib/bs/ReventlessSeed.mlmap +3 -0
  6. package/lib/bs/compiler-info.json +1 -1
  7. package/lib/bs/src/Seed-ReventlessSeed.cmi +0 -0
  8. package/lib/bs/src/Seed-ReventlessSeed.cmt +0 -0
  9. package/lib/bs/src/Seed.ast +0 -0
  10. package/lib/bs/src/Seed.res +1 -0
  11. package/lib/bs/src/Seed.res.mjs +3 -0
  12. package/lib/bs/src/Seed_Client-ReventlessSeed.cmi +0 -0
  13. package/lib/bs/src/Seed_Client-ReventlessSeed.cmj +0 -0
  14. package/lib/bs/src/Seed_Client-ReventlessSeed.cmt +0 -0
  15. package/lib/bs/src/Seed_Client.ast +0 -0
  16. package/lib/bs/src/Seed_Client.res +67 -11
  17. package/lib/bs/src/Seed_Client.res.mjs +60 -20
  18. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmi +0 -0
  19. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmt +0 -0
  20. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmi +0 -0
  21. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmj +0 -0
  22. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmt +0 -0
  23. package/lib/bs/src/Seed_Prompt.ast +0 -0
  24. package/lib/bs/src/Seed_Prompt.res +82 -15
  25. package/lib/bs/src/Seed_Prompt.res.mjs +59 -7
  26. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmi +0 -0
  27. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmt +0 -0
  28. package/lib/bs/src/Seed_Runner.res.mjs +1 -1
  29. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmi +0 -0
  30. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmt +0 -0
  31. package/lib/bs/src/Seed_Users-ReventlessSeed.cmi +0 -0
  32. package/lib/bs/src/Seed_Users-ReventlessSeed.cmj +0 -0
  33. package/lib/bs/src/Seed_Users-ReventlessSeed.cmt +0 -0
  34. package/lib/bs/src/Seed_Users.ast +0 -0
  35. package/lib/bs/src/Seed_Users.res +80 -0
  36. package/lib/bs/src/Seed_Users.res.mjs +90 -0
  37. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmi +0 -0
  38. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmj +0 -0
  39. package/lib/bs/tests/Seed_ClientTest-ReventlessSeed.cmt +0 -0
  40. package/lib/bs/tests/Seed_ClientTest.ast +0 -0
  41. package/lib/bs/tests/Seed_ClientTest.res +59 -0
  42. package/lib/bs/tests/Seed_ClientTest.res.mjs +64 -0
  43. package/lib/bs/tests/Seed_PromptTest-ReventlessSeed.cmi +0 -0
  44. package/lib/bs/tests/Seed_PromptTest-ReventlessSeed.cmt +0 -0
  45. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  46. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmi +0 -0
  47. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmj +0 -0
  48. package/lib/bs/tests/Seed_UsersTest-ReventlessSeed.cmt +0 -0
  49. package/lib/bs/tests/Seed_UsersTest.ast +0 -0
  50. package/lib/bs/tests/Seed_UsersTest.res +92 -0
  51. package/lib/bs/tests/Seed_UsersTest.res.mjs +95 -0
  52. package/lib/ocaml/.compiler.log +2 -2
  53. package/lib/ocaml/ReventlessSeed.cmi +0 -0
  54. package/lib/ocaml/ReventlessSeed.cmt +0 -0
  55. package/lib/ocaml/ReventlessSeed.mlmap +3 -0
  56. package/lib/ocaml/Seed-ReventlessSeed.cmi +0 -0
  57. package/lib/ocaml/Seed-ReventlessSeed.cmt +0 -0
  58. package/lib/ocaml/Seed.ast +0 -0
  59. package/lib/ocaml/Seed.res +1 -0
  60. package/lib/ocaml/Seed_Client-ReventlessSeed.cmi +0 -0
  61. package/lib/ocaml/Seed_Client-ReventlessSeed.cmj +0 -0
  62. package/lib/ocaml/Seed_Client-ReventlessSeed.cmt +0 -0
  63. package/lib/ocaml/Seed_Client.ast +0 -0
  64. package/lib/ocaml/Seed_Client.res +67 -11
  65. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmi +0 -0
  66. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmj +0 -0
  67. package/lib/ocaml/Seed_ClientTest-ReventlessSeed.cmt +0 -0
  68. package/lib/ocaml/Seed_ClientTest.ast +0 -0
  69. package/lib/ocaml/Seed_ClientTest.res +59 -0
  70. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmi +0 -0
  71. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmt +0 -0
  72. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmi +0 -0
  73. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmj +0 -0
  74. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmt +0 -0
  75. package/lib/ocaml/Seed_Prompt.ast +0 -0
  76. package/lib/ocaml/Seed_Prompt.res +82 -15
  77. package/lib/ocaml/Seed_PromptTest-ReventlessSeed.cmi +0 -0
  78. package/lib/ocaml/Seed_PromptTest-ReventlessSeed.cmt +0 -0
  79. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  80. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmi +0 -0
  81. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmt +0 -0
  82. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmi +0 -0
  83. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmt +0 -0
  84. package/lib/ocaml/Seed_Users-ReventlessSeed.cmi +0 -0
  85. package/lib/ocaml/Seed_Users-ReventlessSeed.cmj +0 -0
  86. package/lib/ocaml/Seed_Users-ReventlessSeed.cmt +0 -0
  87. package/lib/ocaml/Seed_Users.ast +0 -0
  88. package/lib/ocaml/Seed_Users.res +80 -0
  89. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmi +0 -0
  90. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmj +0 -0
  91. package/lib/ocaml/Seed_UsersTest-ReventlessSeed.cmt +0 -0
  92. package/lib/ocaml/Seed_UsersTest.ast +0 -0
  93. package/lib/ocaml/Seed_UsersTest.res +92 -0
  94. package/package.json +2 -1
  95. package/src/Seed.res +1 -0
  96. package/src/Seed.res.mjs +3 -0
  97. package/src/Seed_Client.res +67 -11
  98. package/src/Seed_Client.res.mjs +60 -20
  99. package/src/Seed_Prompt.res +82 -15
  100. package/src/Seed_Prompt.res.mjs +59 -7
  101. package/src/Seed_Runner.res.mjs +1 -1
  102. package/src/Seed_Users.res +80 -0
  103. package/src/Seed_Users.res.mjs +90 -0
  104. package/tests/Seed_ClientTest.res +59 -0
  105. package/tests/Seed_ClientTest.res.mjs +64 -0
  106. package/tests/Seed_UsersTest.res +92 -0
  107. package/tests/Seed_UsersTest.res.mjs +95 -0
@@ -1,5 +1,6 @@
1
1
  // Generated by ReScript, PLEASE EDIT WITH CARE
2
2
 
3
+ import * as Stdlib_JSON from "@rescript/runtime/lib/es6/Stdlib_JSON.js";
3
4
  import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
4
5
  import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
6
  import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
@@ -98,6 +99,32 @@ async function login(t) {
98
99
  t.token = Stdlib_Option.flatMap(field(json, "token"), asString);
99
100
  }
100
101
 
102
+ let transientErrorTypes = [
103
+ "InternalFailure",
104
+ "ServiceUnavailable",
105
+ "ServiceUnavailableError",
106
+ "Throttling",
107
+ "ThrottlingException",
108
+ "TooManyRequestsException",
109
+ "RequestTimeout"
110
+ ];
111
+
112
+ function isTransient(errors) {
113
+ let entries = Stdlib_JSON.Decode.array(errors);
114
+ if (entries !== undefined && entries.length !== 0) {
115
+ return entries.every(e => {
116
+ let errorType = nodeString(e, "errorType");
117
+ if (errorType !== undefined) {
118
+ return transientErrorTypes.includes(errorType);
119
+ } else {
120
+ return false;
121
+ }
122
+ });
123
+ } else {
124
+ return false;
125
+ }
126
+ }
127
+
101
128
  async function gql(t, query, label) {
102
129
  let headers = Object.fromEntries([[
103
130
  "content-type",
@@ -111,30 +138,38 @@ async function gql(t, query, label) {
111
138
  "query",
112
139
  query
113
140
  ]]));
114
- let res;
115
- try {
116
- res = await fetch(t.config.endpoint, {
117
- method: "POST",
118
- headers: headers,
119
- body: body
120
- });
121
- } catch (exn) {
122
- throw {
123
- RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
124
- _1: label + `: cannot reach ` + t.config.endpoint + ` — is the platform running?`,
125
- Error: new Error()
126
- };
127
- }
128
- let json = await res.json();
129
- let errors = field(json, "errors");
130
- if (errors !== undefined) {
141
+ let attempt = async n => {
142
+ let res;
143
+ try {
144
+ res = await fetch(t.config.endpoint, {
145
+ method: "POST",
146
+ headers: headers,
147
+ body: body
148
+ });
149
+ } catch (exn) {
150
+ throw {
151
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
152
+ _1: label + `: cannot reach ` + t.config.endpoint + ` — is the platform running?`,
153
+ Error: new Error()
154
+ };
155
+ }
156
+ let json = await res.json();
157
+ let errors = field(json, "errors");
158
+ if (errors === undefined) {
159
+ return Stdlib_Option.getOr(field(json, "data"), null);
160
+ }
161
+ if (isTransient(errors) && n < 4) {
162
+ await sleep((250 * (1 << (n - 1 | 0)) | 0) + (Math.random() * 250 | 0) | 0);
163
+ return await attempt(n + 1 | 0);
164
+ }
165
+ let tried = n > 1 ? `\n gave up after ` + n.toString() + ` attempts` : "";
131
166
  throw {
132
167
  RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
133
- _1: label + ` failed\n query: ` + query + `\n response: ` + JSON.stringify(errors),
168
+ _1: label + ` failed\n query: ` + query + `\n response: ` + JSON.stringify(errors) + tried,
134
169
  Error: new Error()
135
170
  };
136
- }
137
- return Stdlib_Option.getOr(field(json, "data"), null);
171
+ };
172
+ return await attempt(1);
138
173
  }
139
174
 
140
175
  let commandResultSelection = `__typename
@@ -269,6 +304,8 @@ async function waitForIds(t, fieldName, ids, timeoutMsOpt) {
269
304
  return Stdlib_Option.getOr(result, 0);
270
305
  }
271
306
 
307
+ let attempts = 4;
308
+
272
309
  export {
273
310
  sleep,
274
311
  make,
@@ -279,6 +316,9 @@ export {
279
316
  asString,
280
317
  nodeString,
281
318
  login,
319
+ transientErrorTypes,
320
+ isTransient,
321
+ attempts,
282
322
  gql,
283
323
  commandResultSelection,
284
324
  send,
@@ -121,11 +121,15 @@ let isAffirmative = (answer: string): bool =>
121
121
  * Auto-returns when there is a single option, so a lone data set or stack needs
122
122
  * no keypress. `env` (e.g. `SEED_SET`) preselects by matching label or 1-based
123
123
  * index, so CI runs without a TTY. Otherwise it prints a numbered menu.
124
+ *
125
+ * `defaultIndex` makes Enter a valid answer, selecting that 0-based option;
126
+ * without one every reply must name a choice.
124
127
  */
125
128
  let select = async (
126
129
  ~title: string,
127
130
  ~options: array<(string, 'a)>,
128
131
  ~env=?,
132
+ ~defaultIndex=?,
129
133
  ): 'a =>
130
134
  switch options {
131
135
  | [(_, only)] => only
@@ -153,29 +157,38 @@ let select = async (
153
157
  options->Array.forEachWithIndex(((label, _), i) =>
154
158
  Console.log(` ${(i + 1)->Int.toString}) ${label}`)
155
159
  )
160
+ let fallback = defaultIndex->Option.flatMap(i => options->Array.get(i))
161
+ let hint = switch (defaultIndex, fallback) {
162
+ | (Some(i), Some(_)) => ` (default ${(i + 1)->Int.toString})`
163
+ | _ => ""
164
+ }
156
165
  let rec pick = async (): 'a => {
157
- let answer = await ask(`\nSelect [1-${(options->Array.length)->Int.toString}]: `)
158
- switch Int.fromString(answer) {
159
- | Some(n) if n >= 1 && n <= options->Array.length =>
160
- let (_, value) = options->Array.getUnsafe(n - 1)
161
- value
166
+ let answer = await ask(
167
+ `\nSelect [1-${(options->Array.length)->Int.toString}]${hint}: `,
168
+ )
169
+ switch (answer, fallback) {
170
+ | ("", Some((_, value))) => value
162
171
  | _ =>
163
- Console.log(" Not a valid choice.")
164
- await pick()
172
+ switch Int.fromString(answer) {
173
+ | Some(n) if n >= 1 && n <= options->Array.length =>
174
+ let (_, value) = options->Array.getUnsafe(n - 1)
175
+ value
176
+ | _ =>
177
+ Console.log(" Not a valid choice.")
178
+ await pick()
179
+ }
165
180
  }
166
181
  }
167
182
  await pick()
168
183
  }
169
184
  }
170
185
 
171
- /**
172
- * Prompts for a username (visible) and password (echo muted).
173
- *
174
- * `REVENTLESS_DEMO_USER` / `REVENTLESS_DEMO_PASSWORD` skip the prompts. With
175
- * `localDefaults`, empty input falls back to `admin`/`admin` — the dev login.
176
- */
177
- let credentials = async (~localDefaults: bool=false): (string, string) => {
178
- let username = switch envValue("REVENTLESS_DEMO_USER") {
186
+ // Typing both halves is the fallback, not the first offer: it is what happens
187
+ // when the platform keeps no accounts file. `envUser` is threaded in so a
188
+ // `REVENTLESS_DEMO_USER` that named nobody in the file still skips the username
189
+ // prompt rather than asking for a name that was already given.
190
+ let askCredentials = async (~localDefaults: bool, ~envUser: option<string>): (string, string) => {
191
+ let username = switch envUser {
179
192
  | Some(u) => u
180
193
  | None =>
181
194
  requireTty()
@@ -189,6 +202,60 @@ let credentials = async (~localDefaults: bool=false): (string, string) => {
189
202
  let entered = await askHidden(localDefaults ? "Password [admin]: " : "Password: ")
190
203
  entered == "" && localDefaults ? "admin" : entered
191
204
  }
205
+ (username, password)
206
+ }
207
+
208
+ // The accounts file the platform already keeps (`.reventless/users.yaml`, or
209
+ // `SEED_USERS_FILE`). It records the password beside the username, so choosing
210
+ // an account is the whole credential step — nothing is typed.
211
+ //
212
+ // A named `REVENTLESS_DEMO_USER` picks its entry directly; otherwise the file's
213
+ // accounts are offered in the order it defines them, first as the default.
214
+ // `None` means the file has nothing to offer and the caller should ask.
215
+ let fromUsersFile = async (~envUser: option<string>): option<(string, string)> =>
216
+ switch Seed_Users.load(~path=?envValue("SEED_USERS_FILE")) {
217
+ | None => None
218
+ | Some((path, users)) =>
219
+ let chosen = switch envUser {
220
+ | Some(name) => users->Array.find(u => u.username == name)
221
+ | None =>
222
+ Some(
223
+ await select(
224
+ ~title=`User (${path}):`,
225
+ ~options=users->Array.map(u => (Seed_Users.label(u), u)),
226
+ ~env="SEED_USER",
227
+ ~defaultIndex=0,
228
+ ),
229
+ )
230
+ }
231
+ // Logged for every arm, including the single-account file that selects
232
+ // itself without a keypress: which identity seeded the data is the thing an
233
+ // operator checks when owner-scoped rows turn up under the wrong account.
234
+ chosen->Option.map(u => {
235
+ Console.log(`Logging in as ${u.username} (from ${path})`)
236
+ (u.username, u.password)
237
+ })
238
+ }
239
+
240
+ /**
241
+ * Resolves the credentials a seed run logs in with.
242
+ *
243
+ * `REVENTLESS_DEMO_USER` + `REVENTLESS_DEMO_PASSWORD` together are the
244
+ * non-interactive path and skip everything below. Otherwise the platform's
245
+ * `.reventless/users.yaml` supplies the accounts to choose from, and only a
246
+ * platform without one falls back to typing both halves — where, with
247
+ * `localDefaults`, empty input means `admin`/`admin`.
248
+ */
249
+ let credentials = async (~localDefaults: bool=false): (string, string) => {
250
+ let envUser = envValue("REVENTLESS_DEMO_USER")
251
+ let (username, password) = switch (envUser, envValue("REVENTLESS_DEMO_PASSWORD")) {
252
+ | (Some(u), Some(p)) => (u, p)
253
+ | _ =>
254
+ switch await fromUsersFile(~envUser) {
255
+ | Some(pair) => pair
256
+ | None => await askCredentials(~localDefaults, ~envUser)
257
+ }
258
+ }
192
259
  if username == "" || password == "" {
193
260
  throw(Failed("username and password are required."))
194
261
  }
@@ -5,6 +5,7 @@ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
5
  import * as Nodereadline from "node:readline";
6
6
  import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
7
7
  import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
8
+ import * as Seed_Users$ReventlessSeed from "./Seed_Users.res.mjs";
8
9
 
9
10
  let rlRef = {
10
11
  contents: undefined
@@ -94,7 +95,7 @@ function isAffirmative(answer) {
94
95
  }
95
96
  }
96
97
 
97
- async function select(title, options, env) {
98
+ async function select(title, options, env, defaultIndex) {
98
99
  if (options.length === 1) {
99
100
  return options[0][1];
100
101
  }
@@ -118,8 +119,13 @@ async function select(title, options, env) {
118
119
  options.forEach((param, i) => {
119
120
  console.log(` ` + (i + 1 | 0).toString() + `) ` + param[0]);
120
121
  });
122
+ let fallback = Stdlib_Option.flatMap(defaultIndex, i => options[i]);
123
+ let hint = defaultIndex !== undefined && fallback !== undefined ? ` (default ` + (defaultIndex + 1 | 0).toString() + `)` : "";
121
124
  let pick = async () => {
122
- let answer = await ask(`\nSelect [1-` + options.length.toString() + `]: `);
125
+ let answer = await ask(`\nSelect [1-` + options.length.toString() + `]` + hint + `: `);
126
+ if (answer === "" && fallback !== undefined) {
127
+ return fallback[1];
128
+ }
123
129
  let n = Stdlib_Int.fromString(answer, undefined);
124
130
  if (n !== undefined) {
125
131
  if (n >= 1 && n <= options.length) {
@@ -136,12 +142,10 @@ async function select(title, options, env) {
136
142
  return await pick();
137
143
  }
138
144
 
139
- async function credentials(localDefaultsOpt) {
140
- let localDefaults = localDefaultsOpt !== undefined ? localDefaultsOpt : false;
141
- let u = envValue("REVENTLESS_DEMO_USER");
145
+ async function askCredentials(localDefaults, envUser) {
142
146
  let username;
143
- if (u !== undefined) {
144
- username = u;
147
+ if (envUser !== undefined) {
148
+ username = envUser;
145
149
  } else {
146
150
  requireTty();
147
151
  let entered = await ask(localDefaults ? "Username [admin]: " : "Username: ");
@@ -156,6 +160,52 @@ async function credentials(localDefaultsOpt) {
156
160
  let entered$1 = await askHidden(localDefaults ? "Password [admin]: " : "Password: ");
157
161
  password = entered$1 === "" && localDefaults ? "admin" : entered$1;
158
162
  }
163
+ return [
164
+ username,
165
+ password
166
+ ];
167
+ }
168
+
169
+ async function fromUsersFile(envUser) {
170
+ let match = Seed_Users$ReventlessSeed.load(envValue("SEED_USERS_FILE"));
171
+ if (match === undefined) {
172
+ return;
173
+ }
174
+ let users = match[1];
175
+ let path = match[0];
176
+ let chosen = envUser !== undefined ? users.find(u => u.username === envUser) : await select(`User (` + path + `):`, users.map(u => [
177
+ Seed_Users$ReventlessSeed.label(u),
178
+ u
179
+ ]), "SEED_USER", 0);
180
+ return Stdlib_Option.map(chosen, u => {
181
+ console.log(`Logging in as ` + u.username + ` (from ` + path + `)`);
182
+ return [
183
+ u.username,
184
+ u.password
185
+ ];
186
+ });
187
+ }
188
+
189
+ async function credentials(localDefaultsOpt) {
190
+ let localDefaults = localDefaultsOpt !== undefined ? localDefaultsOpt : false;
191
+ let envUser = envValue("REVENTLESS_DEMO_USER");
192
+ let match = envValue("REVENTLESS_DEMO_PASSWORD");
193
+ let match$1;
194
+ let exit = 0;
195
+ if (envUser !== undefined && match !== undefined) {
196
+ match$1 = [
197
+ envUser,
198
+ match
199
+ ];
200
+ } else {
201
+ exit = 1;
202
+ }
203
+ if (exit === 1) {
204
+ let pair = await fromUsersFile(envUser);
205
+ match$1 = pair !== undefined ? pair : await askCredentials(localDefaults, envUser);
206
+ }
207
+ let password = match$1[1];
208
+ let username = match$1[0];
159
209
  if (username === "" || password === "") {
160
210
  throw {
161
211
  RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
@@ -180,6 +230,8 @@ export {
180
230
  askHidden,
181
231
  isAffirmative,
182
232
  select,
233
+ askCredentials,
234
+ fromUsersFile,
183
235
  credentials,
184
236
  }
185
237
  /* node:readline Not a pure module */
@@ -155,7 +155,7 @@ function seed(sets, connect) {
155
155
  chosen = await Seed_Prompt$ReventlessSeed.select("Data set:", sets.map(s => [
156
156
  s.label,
157
157
  s
158
- ]), undefined);
158
+ ]), undefined, undefined);
159
159
  }
160
160
  } else {
161
161
  chosen = sets[0];
@@ -0,0 +1,80 @@
1
+ // The dev accounts a seed run can log in as, read from `.reventless/users.yaml`.
2
+ //
3
+ // Both platforms keep that file beside the package the seed runs from: locally
4
+ // the in-memory auth adapter loads it at startup, and on AWS it is the record of
5
+ // what was created in the Cognito pool. Either way it already holds the
6
+ // credentials an operator would otherwise retype, so the credential prompt
7
+ // offers its entries instead of asking for a password nobody remembers.
8
+ //
9
+ // Absence is normal and silent — the caller falls back to asking. Nothing here
10
+ // throws: a missing, unreadable or malformed file yields no accounts.
11
+
12
+ @module("yaml") external parseYaml: string => JSON.t = "parse"
13
+
14
+ /** One account: what to log in as, and what to send with it. */
15
+ type user = {username: string, password: string, groups: array<string>}
16
+
17
+ let asString = (json: JSON.t): option<string> =>
18
+ switch json {
19
+ | String(s) => Some(s)
20
+ | _ => None
21
+ }
22
+
23
+ let userOf = (json: JSON.t): option<user> =>
24
+ switch json {
25
+ | Object(obj) =>
26
+ switch (
27
+ obj->Dict.get("username")->Option.flatMap(asString),
28
+ obj->Dict.get("password")->Option.flatMap(asString),
29
+ ) {
30
+ | (Some(username), Some(password)) =>
31
+ let groups = switch obj->Dict.get("groups") {
32
+ | Some(JSON.Array(items)) => items->Array.filterMap(asString)
33
+ | _ => []
34
+ }
35
+ Some({username, password, groups})
36
+ | _ => None
37
+ }
38
+ | _ => None
39
+ }
40
+
41
+ /**
42
+ * The accounts a users.yaml document defines, in the order it defines them —
43
+ * the order is what makes "the first one" a stable default.
44
+ *
45
+ * An entry without both a username and a password is skipped rather than
46
+ * rejected: the file is hand-maintained, and one incomplete entry should not
47
+ * cost the operator the rest of the list.
48
+ */
49
+ let parseString = (yamlText: string): array<user> => {
50
+ let doc = try parseYaml(yamlText) catch {
51
+ | _ => JSON.Null
52
+ }
53
+ switch doc {
54
+ | Array(items) => items->Array.filterMap(userOf)
55
+ | _ => []
56
+ }
57
+ }
58
+
59
+ /** Where the file lives for the platform being seeded — the seed runs from that
60
+ package's directory, which is the same cwd the local auth adapter reads. */
61
+ let defaultPath = (): string => NodePath.join([NodeProcess.cwd(), ".reventless", "users.yaml"])
62
+
63
+ /**
64
+ * The accounts on disk, with the path they came from. `None` when there is no
65
+ * readable file with at least one usable account, which the caller reads as
66
+ * "ask for credentials instead".
67
+ */
68
+ let load = (~path: option<string>=?): option<(string, array<user>)> => {
69
+ let file = path->Option.getOr(defaultPath())
70
+ let users = try {
71
+ NodeFs.existsSync(file) ? parseString(NodeFs.readFileSync(file)) : []
72
+ } catch {
73
+ | _ => []
74
+ }
75
+ users->Array.length == 0 ? None : Some((file, users))
76
+ }
77
+
78
+ /** Menu label: the username, plus whatever groups the file records for it. */
79
+ let label = (u: user): string =>
80
+ u.groups->Array.length == 0 ? u.username : `${u.username} [${u.groups->Array.join(", ")}]`
@@ -0,0 +1,90 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Yaml from "yaml";
4
+ import * as Nodefs from "node:fs";
5
+ import * as Nodepath from "node:path";
6
+ import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.js";
7
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
8
+
9
+ function asString(json) {
10
+ if (typeof json === "string") {
11
+ return json;
12
+ }
13
+ }
14
+
15
+ function userOf(json) {
16
+ if (typeof json !== "object" || json === null || Array.isArray(json)) {
17
+ return;
18
+ }
19
+ let match = Stdlib_Option.flatMap(json["username"], asString);
20
+ let match$1 = Stdlib_Option.flatMap(json["password"], asString);
21
+ if (match === undefined) {
22
+ return;
23
+ }
24
+ if (match$1 === undefined) {
25
+ return;
26
+ }
27
+ let match$2 = json["groups"];
28
+ let groups = match$2 !== undefined ? (
29
+ Array.isArray(match$2) ? Stdlib_Array.filterMap(match$2, asString) : []
30
+ ) : [];
31
+ return {
32
+ username: match,
33
+ password: match$1,
34
+ groups: groups
35
+ };
36
+ }
37
+
38
+ function parseString(yamlText) {
39
+ let doc;
40
+ try {
41
+ doc = Yaml.parse(yamlText);
42
+ } catch (exn) {
43
+ doc = null;
44
+ }
45
+ if (Array.isArray(doc)) {
46
+ return Stdlib_Array.filterMap(doc, userOf);
47
+ } else {
48
+ return [];
49
+ }
50
+ }
51
+
52
+ function defaultPath() {
53
+ return Nodepath.join(process.cwd(), ".reventless", "users.yaml");
54
+ }
55
+
56
+ function load(path) {
57
+ let file = Stdlib_Option.getOr(path, defaultPath());
58
+ let users;
59
+ try {
60
+ users = Nodefs.existsSync(file) ? parseString(Nodefs.readFileSync(file, "utf8")) : [];
61
+ } catch (exn) {
62
+ users = [];
63
+ }
64
+ if (users.length === 0) {
65
+ return;
66
+ } else {
67
+ return [
68
+ file,
69
+ users
70
+ ];
71
+ }
72
+ }
73
+
74
+ function label(u) {
75
+ if (u.groups.length === 0) {
76
+ return u.username;
77
+ } else {
78
+ return u.username + ` [` + u.groups.join(", ") + `]`;
79
+ }
80
+ }
81
+
82
+ export {
83
+ asString,
84
+ userOf,
85
+ parseString,
86
+ defaultPath,
87
+ load,
88
+ label,
89
+ }
90
+ /* yaml Not a pure module */
@@ -0,0 +1,59 @@
1
+ open JestGlobals
2
+
3
+ // A seed issues hundreds of commands against runtimes a preceding reset left
4
+ // cold, so the endpoint faulting on one of them is a normal event rather than an
5
+ // exceptional one. Before the retry, a single `InternalFailure` in that batch
6
+ // aborted the run and left a half-seeded store that could only be recovered by a
7
+ // full wipe and a re-run — for a request that would have succeeded on being
8
+ // asked again.
9
+ //
10
+ // What makes the retry safe is the classifier, so that is what these pin. A
11
+ // fault on the endpoint's side carries no information about the document and is
12
+ // worth resending; anything that is an *answer* — a validation error, an unknown
13
+ // field, a refused token — comes back identical however many times it is asked,
14
+ // and resending it only delays the failure the operator needs to see.
15
+
16
+ let errors = entries => JSON.Encode.array(entries->Array.map(JSON.Encode.object))
17
+
18
+ let errorOfType = errorType =>
19
+ Dict.fromArray([("errorType", JSON.Encode.string(errorType))])
20
+
21
+ describe("Seed_Client.isTransient:", () => {
22
+ testSync("resends a fault on the endpoint's own side", () =>
23
+ ["InternalFailure", "ServiceUnavailable", "Throttling", "TooManyRequestsException"]
24
+ ->Array.forEach(t =>
25
+ expect(Seed_Client.isTransient(errors([errorOfType(t)])))->toBe(true)
26
+ )
27
+ )
28
+
29
+ // The exact payload the seed aborted on.
30
+ testSync("resends the shape AppSync actually returned", () => {
31
+ let payload = JSON.parseOrThrow(`[{"errorType":"InternalFailure","message":"An internal failure occurred."}]`)
32
+ expect(Seed_Client.isTransient(payload))->toBe(true)
33
+ })
34
+
35
+ testSync("fails fast on an error that is an answer", () =>
36
+ ["ValidationException", "Unauthorized", "FieldUndefined"]->Array.forEach(t =>
37
+ expect(Seed_Client.isTransient(errors([errorOfType(t)])))->toBe(false)
38
+ )
39
+ )
40
+
41
+ // A real error sitting alongside a transient one still means the request was
42
+ // wrong, and resending it cannot make it right.
43
+ testSync("refuses to resend a batch that mixes a real error in", () =>
44
+ expect(
45
+ Seed_Client.isTransient(
46
+ errors([errorOfType("InternalFailure"), errorOfType("ValidationException")]),
47
+ ),
48
+ )->toBe(false)
49
+ )
50
+
51
+ // `Array.every` is vacuously true on an empty array, which would turn "the
52
+ // endpoint said errors but named none" into an endless resend.
53
+ testSync("treats an empty or untyped error list as final", () => {
54
+ expect(Seed_Client.isTransient(errors([])))->toBe(false)
55
+ expect(Seed_Client.isTransient(errors([Dict.fromArray([("message", JSON.Encode.string("boom"))])])))
56
+ ->toBe(false)
57
+ expect(Seed_Client.isTransient(JSON.Encode.null))->toBe(false)
58
+ })
59
+ })
@@ -0,0 +1,64 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Seed_Client$ReventlessSeed from "../src/Seed_Client.res.mjs";
4
+
5
+ function errors(entries) {
6
+ return entries.map(prim => prim);
7
+ }
8
+
9
+ function errorOfType(errorType) {
10
+ return Object.fromEntries([[
11
+ "errorType",
12
+ errorType
13
+ ]]);
14
+ }
15
+
16
+ globalThis.describe("Seed_Client.isTransient:", () => {
17
+ globalThis.test("resends a fault on the endpoint's own side", () => {
18
+ [
19
+ "InternalFailure",
20
+ "ServiceUnavailable",
21
+ "Throttling",
22
+ "TooManyRequestsException"
23
+ ].forEach(t => {
24
+ let entries = [errorOfType(t)];
25
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(entries.map(prim => prim))).toBe(true);
26
+ });
27
+ });
28
+ globalThis.test("resends the shape AppSync actually returned", () => {
29
+ let payload = JSON.parse(`[{"errorType":"InternalFailure","message":"An internal failure occurred."}]`);
30
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(payload)).toBe(true);
31
+ });
32
+ globalThis.test("fails fast on an error that is an answer", () => {
33
+ [
34
+ "ValidationException",
35
+ "Unauthorized",
36
+ "FieldUndefined"
37
+ ].forEach(t => {
38
+ let entries = [errorOfType(t)];
39
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(entries.map(prim => prim))).toBe(false);
40
+ });
41
+ });
42
+ globalThis.test("refuses to resend a batch that mixes a real error in", () => {
43
+ let entries = [
44
+ errorOfType("InternalFailure"),
45
+ errorOfType("ValidationException")
46
+ ];
47
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(entries.map(prim => prim))).toBe(false);
48
+ });
49
+ globalThis.test("treats an empty or untyped error list as final", () => {
50
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient([].map(prim => prim))).toBe(false);
51
+ let entries = [Object.fromEntries([[
52
+ "message",
53
+ "boom"
54
+ ]])];
55
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(entries.map(prim => prim))).toBe(false);
56
+ globalThis.expect(Seed_Client$ReventlessSeed.isTransient(null)).toBe(false);
57
+ });
58
+ });
59
+
60
+ export {
61
+ errors,
62
+ errorOfType,
63
+ }
64
+ /* Not a pure module */