@midsummer-ai/sdk 0.1.0-staging.3778 → 0.1.0-staging.3781

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.
package/auth/contract.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-DBp5FHvK.mjs";
1
+ import { c as LIMITS, l as LIMIT_WINDOW_MS, r as AuthError, u as SETTINGS_TTL_MS } from "../auth-DUEJfZvB.mjs";
2
2
  import { IMPERSONATION_TOKEN_MS, startImpersonation } from "./impersonate.mjs";
3
3
  //#region src/auth/contract.ts
4
4
  /**
package/auth/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-DBp5FHvK.mjs";
1
+ import { a as SESSION_CACHE_S, d as databaseStore, i as IMPERSONATION_S, n as AUTH_ROUTES, o as auth, r as AuthError, s as createAuth, t as AUTH_PATH } from "../auth-DUEJfZvB.mjs";
2
2
  import { checkSignInMail, signInWords } from "./mail.mjs";
3
3
  import { n as authFiles } from "../files-DhPeWwcT.mjs";
4
4
  export { AUTH_PATH, AUTH_ROUTES, AuthError, IMPERSONATION_S, SESSION_CACHE_S, auth, authFiles, checkSignInMail, createAuth, databaseStore, signInWords };
package/auth/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CIuYlRWZ.mjs";
1
+ import { t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
2
2
  import { DatabaseProvider } from "../database/react.mjs";
3
3
  import { a as WORDS, c as deviceOf, i as CAPTCHA_WIDGETS, l as setupKeyOf, o as ago, r as AUTH_CSS, t as qrPath } from "../qr-Br1sOBmT.mjs";
4
4
  import { AuthClientError, authClient } from "./client.mjs";
@@ -1,5 +1,5 @@
1
1
  import { i as processEnv, r as platformApi, t as here } from "./here-BKjizr_N.mjs";
2
- import { d as userToken, o as connect, s as databaseUrl } from "./client-CIuYlRWZ.mjs";
2
+ import { d as userToken, o as connect, s as databaseUrl } from "./client-CrJkXd5h.mjs";
3
3
  import { sendSignInMail } from "./auth/mail.mjs";
4
4
  import "./files-DhPeWwcT.mjs";
5
5
  import { standIn } from "./auth/stand-in.mjs";
@@ -225,6 +225,10 @@ var DoorSocket = class {
225
225
  ready(authorization, bytes) {
226
226
  return this.state === "open" && authorization === this.authorization && bytes <= this.#maxCall && this.#calls.size < this.#inFlight;
227
227
  }
228
+ /** Whether a call of `bytes` as `authorization` may be sent on it now, behind a hello not answered yet: not ended, its hello's token, within its bounds. */
229
+ takes(authorization, bytes) {
230
+ return this.state !== "closed" && authorization === this.authorization && bytes <= this.#maxCall && this.#calls.size < this.#inFlight;
231
+ }
228
232
  /** One call (a `POST <door>/call` body): its answer, or `SocketClosed` once the socket ends first. */
229
233
  call(body) {
230
234
  if (this.state === "closed") return Promise.reject(new SocketClosed());
@@ -878,19 +882,21 @@ function warmUp(lane, door) {
878
882
  const encoder = new TextEncoder();
879
883
  /** A `Server-Timing` entry's number of milliseconds. */
880
884
  const ms = (value) => value.toFixed(1);
885
+ const legOf = (leg) => !leg ? "none" : leg.ms === void 0 ? leg.ended ?? "unanswered" : `${ms(leg.ms)} (${leg.status})${leg.ended ? ` ${leg.ended}` : ""}`;
881
886
  /**
882
887
  * The `db-first` entry of a request's first call to its door, which says where its time went: `token` (having the
883
- * token: none when the request handed one), `call` (the call itself, `by fetch` or `by socket`), `warm` (the door's
884
- * connection started at connect, ended before the call or still going beside it; `none` where none was started) and
885
- * `socket` (open, and how long its hello took, or still opening, or none). A slow call beside a quick warm-up was the
888
+ * token: none when the request handed one), which path's answer `won`, each path's time (`socket` and `fetch`: its
889
+ * answer's, or how it ended without one, as dropped once the other won), `warm` (the door's connection started at
890
+ * connect, ended before the call or still going beside it; `none` where none was started) and the socket's hello
891
+ * (`hello`: how long until it was answered, or still opening, or none). A slow call beside a quick warm-up was the
886
892
  * Database (waking, or the engine); a slow warm-up the connection.
887
893
  */
888
- function firstEntry(lane, tokenMs, callMs, started, status, bySocket) {
894
+ function firstEntry(lane, tokenMs, started, won, legs) {
889
895
  const warm = lane.warm;
890
896
  const warmed = !warm ? "none" : warm.ended === void 0 ? `${ms(started - warm.at)} so far, beside the call` : `${ms(warm.ended - warm.at)} ${warm.ended <= started ? "before" : "beside"} the call (${warm.status})`;
891
897
  const socket = lane.socket;
892
- const opened = !socket ? "none" : socket.state === "open" ? `open in ${ms(socket.openMs ?? 0)}` : socket.state === "opening" ? "opening" : `closed (${socket.why})`;
893
- return `db-first;dur=${ms(tokenMs + callMs)};desc="token ${ms(tokenMs)}, call ${ms(callMs)} by ${bySocket ? "socket" : "fetch"} (${status}), warm ${warmed}, socket ${opened}"`;
898
+ const hello = !socket ? "none" : socket.openMs !== void 0 ? `answered in ${ms(socket.openMs)}` : socket.state === "opening" ? "opening" : `closed (${socket.why})`;
899
+ return `db-first;dur=${ms(tokenMs + (legs[won]?.ms ?? 0))};desc="token ${ms(tokenMs)}, won by ${won}, socket ${legOf(legs.socket)}, fetch ${legOf(legs.fetch)}, warm ${warmed}, hello ${hello}"`;
894
900
  }
895
901
  /** A WebSocket to `url` once it opens, as a `Connection`'s `dial` gives one. */
896
902
  function openedAt(url) {
@@ -911,11 +917,14 @@ function openedAt(url) {
911
917
  * make it again (`remake`), once, and sends the calls once more.
912
918
  *
913
919
  * How a call goes, in each request (`Lane`): connecting starts the door's connection (`warmUp`). The request's first
914
- * call goes by fetch (`POST <door>/call`), and beside it the request opens a socket to the door's socket address
915
- * (`DoorSocket`), where the door has one and the runtime can open one; later calls of the request go on the socket once
916
- * its hello is answered, by fetch until then. A watch goes on the socket too. Nothing waits on the socket: one that
917
- * fails or closes leaves every call it held, and every later one of that request, to fetch, with no error; a watch
918
- * opens a WebSocket to the door instead. A renewed token goes by fetch: a socket's token is its hello's.
920
+ * call opens a socket to the door's socket address (`DoorSocket`), where the door has one and the runtime can open one,
921
+ * the call right behind its hello. Until the hello is answered, calls that may go twice (reads, and mutations under
922
+ * their exactly-once tag) also go by fetch (`POST <door>/call`) at once, and the first answer stands: a fetch the socket
923
+ * beat is aborted, a socket's late answer ignored and the socket kept. An action goes on the socket alone. Once the
924
+ * hello is answered every call goes on the socket alone. A watch goes on the socket too. A socket that fails or closes
925
+ * leaves every call it held, and every later one of that request, to fetch, with no error; a watch opens a WebSocket to
926
+ * the door instead. A door with no socket address is fetch alone. A renewed token goes by fetch: a socket's token is
927
+ * its hello's. Every path is bounded by `DOOR_CALL_MS`.
919
928
  */
920
929
  function doorCalls(handle, binding, first) {
921
930
  let door = first;
@@ -951,8 +960,11 @@ function doorCalls(handle, binding, first) {
951
960
  lane.socket = new DoorSocket(asker.socket(door.socket), database, `Bearer ${token}`);
952
961
  } catch {}
953
962
  };
954
- /** One call of `ops` to the door, and how to find each one's answer by its `i`. */
955
- const post = async (ops) => {
963
+ /**
964
+ * One call of `ops` to the door, and how to find each one's answer by its `i`. `races`: every op may go on both paths
965
+ * at once (a read, or a write under its exactly-once tag); an action may not, and goes on one.
966
+ */
967
+ const post = async (ops, races) => {
956
968
  const body = JSON.stringify(ops), bytes = encoder.encode(body), since = Date.now();
957
969
  const asker = now(), lane = laneOf(asker, door.url);
958
970
  let remade = false;
@@ -970,11 +982,58 @@ function doorCalls(handle, binding, first) {
970
982
  }
971
983
  const tokenMs = performance.now() - asked;
972
984
  begin(lane, asker, token);
973
- const socket = lane.socket?.ready(`Bearer ${token}`, bytes.length) ? lane.socket : void 0;
985
+ const authorization = `Bearer ${token}`;
986
+ const socket = lane.socket?.takes(authorization, bytes.length) ? lane.socket : void 0;
987
+ const how = !socket ? "fetch" : socket.state === "open" || !races ? "socket" : "race";
974
988
  const started = performance.now();
975
- let status, text;
976
- if (socket) try {
977
- ({status, text} = await answeredWithin(socket, socket.call(bytes)));
989
+ const first = !lane.timed;
990
+ lane.timed = true;
991
+ const legs = {};
992
+ const paths = [];
993
+ const bySocket = () => {
994
+ const leg = {};
995
+ legs.socket = leg;
996
+ return answeredWithin(socket, socket.call(bytes)).then((answer) => {
997
+ leg.ms = performance.now() - started;
998
+ leg.status = answer.status;
999
+ return {
1000
+ ...answer,
1001
+ via: "socket"
1002
+ };
1003
+ }, (error) => {
1004
+ leg.ended = error instanceof SocketClosed ? `failed (${socket.why ?? "closed"})` : "failed";
1005
+ throw error;
1006
+ });
1007
+ };
1008
+ const byFetch = (signal) => {
1009
+ const leg = {};
1010
+ legs.fetch = leg;
1011
+ return (async () => {
1012
+ const response = await fetchAt(`${door.url}/call`, {
1013
+ method: "POST",
1014
+ headers: {
1015
+ authorization,
1016
+ "content-type": "application/json"
1017
+ },
1018
+ body,
1019
+ signal
1020
+ });
1021
+ const text = await response.text();
1022
+ leg.ms = performance.now() - started;
1023
+ leg.status = response.status;
1024
+ return {
1025
+ status: response.status,
1026
+ text,
1027
+ via: "fetch"
1028
+ };
1029
+ })().catch((error) => {
1030
+ leg.ended ??= "failed";
1031
+ throw error;
1032
+ });
1033
+ };
1034
+ let answer;
1035
+ if (how === "socket") try {
1036
+ answer = await bySocket();
978
1037
  } catch (error) {
979
1038
  if (error instanceof SocketClosed) {
980
1039
  tries -= 1;
@@ -982,34 +1041,45 @@ function doorCalls(handle, binding, first) {
982
1041
  }
983
1042
  throw error;
984
1043
  }
1044
+ else if (how === "fetch") try {
1045
+ answer = await byFetch(AbortSignal.timeout(DOOR_CALL_MS));
1046
+ } catch (error) {
1047
+ if (tries < 2) continue;
1048
+ return all({
1049
+ ok: false,
1050
+ why: "unavailable",
1051
+ error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
1052
+ });
1053
+ }
985
1054
  else {
986
- let response;
1055
+ const dropped = new AbortController();
1056
+ const viaSocket = bySocket(), viaFetch = byFetch(AbortSignal.any([dropped.signal, AbortSignal.timeout(DOOR_CALL_MS)]));
1057
+ paths.push(viaSocket, viaFetch);
987
1058
  try {
988
- response = await fetchAt(`${door.url}/call`, {
989
- method: "POST",
990
- headers: {
991
- authorization: `Bearer ${token}`,
992
- "content-type": "application/json"
993
- },
994
- body,
995
- signal: AbortSignal.timeout(DOOR_CALL_MS)
996
- });
997
- text = await response.text();
998
- } catch (error) {
1059
+ answer = await Promise.any([viaSocket, viaFetch]);
1060
+ } catch (failed) {
999
1061
  if (tries < 2) continue;
1062
+ const error = failed.errors?.[1];
1000
1063
  return all({
1001
1064
  ok: false,
1002
1065
  why: "unavailable",
1003
1066
  error: `couldn't reach the database bound as ${binding} (${error instanceof Error ? error.message : String(error)})`
1004
1067
  });
1005
1068
  }
1006
- status = response.status;
1069
+ if (answer.via === "socket") {
1070
+ legs.fetch.ended = "dropped";
1071
+ dropped.abort();
1072
+ } else legs.socket.ended = "ignored";
1073
+ viaSocket.catch(() => {});
1074
+ viaFetch.catch(() => {});
1007
1075
  }
1076
+ const { status, text } = answer;
1008
1077
  const callMs = performance.now() - started;
1009
- asker.note?.(`db-call;dur=${ms(callMs)};desc="${status}, ${ops.length} call${ops.length === 1 ? "" : "s"}${socket ? ", socket" : ""}"`);
1010
- if (!lane.timed) {
1011
- lane.timed = true;
1012
- asker.note?.(firstEntry(lane, tokenMs, callMs, started, status, !!socket));
1078
+ asker.note?.(`db-call;dur=${ms(callMs)};desc="${status}, ${ops.length} call${ops.length === 1 ? "" : "s"}${answer.via === "socket" ? ", socket" : ""}${how === "race" ? `, raced` : ""}"`);
1079
+ if (first) {
1080
+ const note = () => asker.note?.(firstEntry(lane, tokenMs, started, answer.via, legs));
1081
+ if (how === "race") Promise.allSettled(paths).then(note);
1082
+ else note();
1013
1083
  }
1014
1084
  if (status === 401 && tries === 0) {
1015
1085
  try {
@@ -1072,7 +1142,7 @@ function doorCalls(handle, binding, first) {
1072
1142
  post(part.map((each, n) => ({
1073
1143
  i: n + 1,
1074
1144
  ...each.op
1075
- }))).then((answerOf) => {
1145
+ })), part.every((each) => each.races)).then((answerOf) => {
1076
1146
  part.forEach((each, n) => each.done(answerOf(n + 1)));
1077
1147
  }, (error) => {
1078
1148
  part.forEach((each, n) => each.done({
@@ -1084,10 +1154,11 @@ function doorCalls(handle, binding, first) {
1084
1154
  });
1085
1155
  }
1086
1156
  };
1087
- const call = (op) => new Promise((done) => {
1157
+ const call = (op, races = true) => new Promise((done) => {
1088
1158
  if (queued.length === 0) queueMicrotask(flush);
1089
1159
  queued.push({
1090
1160
  op,
1161
+ races,
1091
1162
  done
1092
1163
  });
1093
1164
  });
@@ -1126,7 +1197,7 @@ function doorCalls(handle, binding, first) {
1126
1197
  f: fn.name,
1127
1198
  a: args,
1128
1199
  t: tag ?? `${client}:${tags += 1}`
1129
- });
1200
+ }, fn.kind !== "action");
1130
1201
  },
1131
1202
  watchQuery(fn, args, options, onValue) {
1132
1203
  let stopped = false, stop = () => {};
@@ -1,3 +1,3 @@
1
1
  import { DatabaseError } from "./errors.mjs";
2
- import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CIuYlRWZ.mjs";
2
+ import { a as clerk, c as oidc, d as userToken, i as auth0, l as profileClaims, n as DatabaseClient, o as connect, r as PROFILE_MOST, s as databaseUrl, t as DATABASE_TOKEN_PATH, u as signedInDatabase } from "../client-CrJkXd5h.mjs";
3
3
  export { DATABASE_TOKEN_PATH, DatabaseClient, DatabaseError, PROFILE_MOST, auth0, clerk, connect, databaseUrl, oidc, profileClaims, signedInDatabase, userToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midsummer-ai/sdk",
3
- "version": "0.1.0-staging.3778",
3
+ "version": "0.1.0-staging.3781",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Midsummer's handles for an app's code: its Database, Storage, Queues, Vector DB, AI, Email and Agents, with stand-ins for tests.",