@eloxiv/client 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +6 -2
- package/dist/Account.d.ts +131 -0
- package/dist/Account.d.ts.map +1 -0
- package/dist/Account.js +169 -0
- package/dist/Account.js.map +1 -0
- package/dist/Agent.d.ts +496 -0
- package/dist/Agent.d.ts.map +1 -0
- package/dist/Agent.js +228 -0
- package/dist/Agent.js.map +1 -0
- package/dist/AgentSync.d.ts +990 -0
- package/dist/AgentSync.d.ts.map +1 -0
- package/dist/AgentSync.js +46 -0
- package/dist/AgentSync.js.map +1 -0
- package/dist/AppState.d.ts +127 -0
- package/dist/AppState.d.ts.map +1 -0
- package/dist/AppState.js +145 -0
- package/dist/AppState.js.map +1 -0
- package/dist/AppStateSync.d.ts +193 -0
- package/dist/AppStateSync.d.ts.map +1 -0
- package/dist/AppStateSync.js +23 -0
- package/dist/AppStateSync.js.map +1 -0
- package/dist/Auth.d.ts +95 -0
- package/dist/Auth.d.ts.map +1 -0
- package/dist/Auth.js +139 -0
- package/dist/Auth.js.map +1 -0
- package/dist/Avatars.d.ts +53 -0
- package/dist/Avatars.d.ts.map +1 -0
- package/dist/Avatars.js +121 -0
- package/dist/Avatars.js.map +1 -0
- package/dist/BrowserAnalytics.d.ts +56 -0
- package/dist/BrowserAnalytics.d.ts.map +1 -0
- package/dist/BrowserAnalytics.js +94 -0
- package/dist/BrowserAnalytics.js.map +1 -0
- package/dist/Chat.d.ts +712 -0
- package/dist/Chat.d.ts.map +1 -0
- package/dist/Chat.js +883 -0
- package/dist/Chat.js.map +1 -0
- package/dist/ChatIntegrity.d.ts +63 -0
- package/dist/ChatIntegrity.d.ts.map +1 -0
- package/dist/ChatIntegrity.js +89 -0
- package/dist/ChatIntegrity.js.map +1 -0
- package/dist/ChatSends.d.ts +103 -0
- package/dist/ChatSends.d.ts.map +1 -0
- package/dist/ChatSends.js +157 -0
- package/dist/ChatSends.js.map +1 -0
- package/dist/Client.d.ts +113 -0
- package/dist/Client.d.ts.map +1 -0
- package/dist/Client.js +189 -0
- package/dist/Client.js.map +1 -0
- package/dist/Collab.d.ts +138 -0
- package/dist/Collab.d.ts.map +1 -0
- package/dist/Collab.js +454 -0
- package/dist/Collab.js.map +1 -0
- package/dist/CollabTools.d.ts +129 -0
- package/dist/CollabTools.d.ts.map +1 -0
- package/dist/CollabTools.js +277 -0
- package/dist/CollabTools.js.map +1 -0
- package/dist/Connections.d.ts +288 -0
- package/dist/Connections.d.ts.map +1 -0
- package/dist/Connections.js +316 -0
- package/dist/Connections.js.map +1 -0
- package/dist/Consent.d.ts +338 -0
- package/dist/Consent.d.ts.map +1 -0
- package/dist/Consent.js +142 -0
- package/dist/Consent.js.map +1 -0
- package/dist/Desktop.d.ts +61 -0
- package/dist/Desktop.d.ts.map +1 -0
- package/dist/Desktop.js +101 -0
- package/dist/Desktop.js.map +1 -0
- package/dist/Directory.d.ts +36 -0
- package/dist/Directory.d.ts.map +1 -0
- package/dist/Directory.js +42 -0
- package/dist/Directory.js.map +1 -0
- package/dist/ErrorReporter.d.ts +48 -0
- package/dist/ErrorReporter.d.ts.map +1 -0
- package/dist/ErrorReporter.js +70 -0
- package/dist/ErrorReporter.js.map +1 -0
- package/dist/ExpoSqlite.d.ts +7 -0
- package/dist/ExpoSqlite.d.ts.map +1 -0
- package/dist/ExpoSqlite.js +7 -0
- package/dist/ExpoSqlite.js.map +1 -0
- package/dist/FileSync.d.ts +265 -0
- package/dist/FileSync.d.ts.map +1 -0
- package/dist/FileSync.js +29 -0
- package/dist/FileSync.js.map +1 -0
- package/dist/FileTables.gen.d.ts +109 -0
- package/dist/FileTables.gen.d.ts.map +1 -0
- package/dist/FileTables.gen.js +23 -0
- package/dist/FileTables.gen.js.map +1 -0
- package/dist/Foldkit.d.ts +487 -0
- package/dist/Foldkit.d.ts.map +1 -0
- package/dist/Foldkit.js +617 -0
- package/dist/Foldkit.js.map +1 -0
- package/dist/History.d.ts +133 -0
- package/dist/History.d.ts.map +1 -0
- package/dist/History.js +210 -0
- package/dist/History.js.map +1 -0
- package/dist/InboxSync.d.ts +428 -0
- package/dist/InboxSync.d.ts.map +1 -0
- package/dist/InboxSync.js +37 -0
- package/dist/InboxSync.js.map +1 -0
- package/dist/KernelTables.gen.d.ts +1522 -0
- package/dist/KernelTables.gen.d.ts.map +1 -0
- package/dist/KernelTables.gen.js +307 -0
- package/dist/KernelTables.gen.js.map +1 -0
- package/dist/Make.d.ts +75 -0
- package/dist/Make.d.ts.map +1 -0
- package/dist/Make.js +70 -0
- package/dist/Make.js.map +1 -0
- package/dist/Models.d.ts +88 -0
- package/dist/Models.d.ts.map +1 -0
- package/dist/Models.js +80 -0
- package/dist/Models.js.map +1 -0
- package/dist/Optimistic.d.ts +120 -0
- package/dist/Optimistic.d.ts.map +1 -0
- package/dist/Optimistic.js +231 -0
- package/dist/Optimistic.js.map +1 -0
- package/dist/PlatformSync.d.ts +273 -0
- package/dist/PlatformSync.d.ts.map +1 -0
- package/dist/PlatformSync.js +92 -0
- package/dist/PlatformSync.js.map +1 -0
- package/dist/Poll.d.ts +113 -0
- package/dist/Poll.d.ts.map +1 -0
- package/dist/Poll.js +179 -0
- package/dist/Poll.js.map +1 -0
- package/dist/Preferences.d.ts +18 -0
- package/dist/Preferences.d.ts.map +1 -0
- package/dist/Preferences.js +22 -0
- package/dist/Preferences.js.map +1 -0
- package/dist/Proposals.d.ts +29 -0
- package/dist/Proposals.d.ts.map +1 -0
- package/dist/Proposals.js +41 -0
- package/dist/Proposals.js.map +1 -0
- package/dist/React.d.ts +17 -0
- package/dist/React.d.ts.map +1 -0
- package/dist/React.js +17 -0
- package/dist/React.js.map +1 -0
- package/dist/Reader.d.ts +35 -0
- package/dist/Reader.d.ts.map +1 -0
- package/dist/Reader.js +136 -0
- package/dist/Reader.js.map +1 -0
- package/dist/Resources.d.ts +98 -0
- package/dist/Resources.d.ts.map +1 -0
- package/dist/Resources.js +161 -0
- package/dist/Resources.js.map +1 -0
- package/dist/Rows.d.ts +4 -0
- package/dist/Rows.d.ts.map +1 -0
- package/dist/Rows.js +16 -0
- package/dist/Rows.js.map +1 -0
- package/dist/Runtime.d.ts +254 -0
- package/dist/Runtime.d.ts.map +1 -0
- package/dist/Runtime.js +1283 -0
- package/dist/Runtime.js.map +1 -0
- package/dist/RuntimeRuns.d.ts +74 -0
- package/dist/RuntimeRuns.d.ts.map +1 -0
- package/dist/RuntimeRuns.js +118 -0
- package/dist/RuntimeRuns.js.map +1 -0
- package/dist/ServicesSync.d.ts +286 -0
- package/dist/ServicesSync.d.ts.map +1 -0
- package/dist/ServicesSync.js +40 -0
- package/dist/ServicesSync.js.map +1 -0
- package/dist/Session.d.ts +228 -0
- package/dist/Session.d.ts.map +1 -0
- package/dist/Session.js +792 -0
- package/dist/Session.js.map +1 -0
- package/dist/ShareGrant.d.ts +47 -0
- package/dist/ShareGrant.d.ts.map +1 -0
- package/dist/ShareGrant.js +20 -0
- package/dist/ShareGrant.js.map +1 -0
- package/dist/Sharing.d.ts +203 -0
- package/dist/Sharing.d.ts.map +1 -0
- package/dist/Sharing.js +520 -0
- package/dist/Sharing.js.map +1 -0
- package/dist/Skew.d.ts +52 -0
- package/dist/Skew.d.ts.map +1 -0
- package/dist/Skew.js +77 -0
- package/dist/Skew.js.map +1 -0
- package/dist/SpacesSync.d.ts +247 -0
- package/dist/SpacesSync.d.ts.map +1 -0
- package/dist/SpacesSync.js +30 -0
- package/dist/SpacesSync.js.map +1 -0
- package/dist/Storage.d.ts +51 -0
- package/dist/Storage.d.ts.map +1 -0
- package/dist/Storage.js +107 -0
- package/dist/Storage.js.map +1 -0
- package/dist/Sync.d.ts +48 -0
- package/dist/Sync.d.ts.map +1 -0
- package/dist/Sync.js +48 -0
- package/dist/Sync.js.map +1 -0
- package/dist/SyncTables.d.ts +13 -0
- package/dist/SyncTables.d.ts.map +1 -0
- package/dist/SyncTables.js +13 -0
- package/dist/SyncTables.js.map +1 -0
- package/dist/Tab.d.ts +36 -0
- package/dist/Tab.d.ts.map +1 -0
- package/dist/Tab.js +44 -0
- package/dist/Tab.js.map +1 -0
- package/dist/Transport.d.ts +139 -0
- package/dist/Transport.d.ts.map +1 -0
- package/dist/Transport.js +232 -0
- package/dist/Transport.js.map +1 -0
- package/dist/Upload.d.ts +41 -0
- package/dist/Upload.d.ts.map +1 -0
- package/dist/Upload.js +93 -0
- package/dist/Upload.js.map +1 -0
- package/dist/WebMcp.d.ts +78 -0
- package/dist/WebMcp.d.ts.map +1 -0
- package/dist/WebMcp.js +204 -0
- package/dist/WebMcp.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/package.json +97 -3
- package/src/Account.ts +249 -0
- package/src/Agent.ts +387 -0
- package/src/AgentSync.ts +59 -0
- package/src/AppState.ts +222 -0
- package/src/AppStateSync.ts +26 -0
- package/src/Auth.ts +225 -0
- package/src/Avatars.ts +144 -0
- package/src/BrowserAnalytics.ts +133 -0
- package/src/Chat.ts +1150 -0
- package/src/ChatIntegrity.ts +130 -0
- package/src/ChatSends.ts +209 -0
- package/src/Client.ts +319 -0
- package/src/Collab.ts +524 -0
- package/src/CollabTools.ts +381 -0
- package/src/Connections.ts +517 -0
- package/src/Consent.ts +176 -0
- package/src/Desktop.ts +139 -0
- package/src/Directory.ts +71 -0
- package/src/ErrorReporter.ts +112 -0
- package/src/ExpoSqlite.ts +6 -0
- package/src/FileSync.ts +34 -0
- package/src/FileTables.gen.ts +23 -0
- package/src/Foldkit.ts +960 -0
- package/src/History.ts +337 -0
- package/src/InboxSync.ts +47 -0
- package/src/KernelTables.gen.ts +329 -0
- package/src/Make.ts +120 -0
- package/src/Models.ts +134 -0
- package/src/Optimistic.ts +364 -0
- package/src/PlatformSync.ts +156 -0
- package/src/Poll.ts +227 -0
- package/src/Preferences.ts +42 -0
- package/src/Proposals.ts +57 -0
- package/src/React.ts +26 -0
- package/src/Reader.ts +180 -0
- package/src/Resources.ts +257 -0
- package/src/Rows.ts +16 -0
- package/src/Runtime.ts +1442 -0
- package/src/RuntimeRuns.ts +180 -0
- package/src/ServicesSync.ts +58 -0
- package/src/Session.ts +844 -0
- package/src/ShareGrant.ts +20 -0
- package/src/Sharing.ts +696 -0
- package/src/Skew.ts +97 -0
- package/src/SpacesSync.ts +61 -0
- package/src/Storage.ts +167 -0
- package/src/Sync.ts +125 -0
- package/src/SyncTables.ts +12 -0
- package/src/Tab.ts +59 -0
- package/src/Transport.ts +321 -0
- package/src/Upload.ts +125 -0
- package/src/WebMcp.ts +279 -0
- package/src/index.ts +26 -0
- package/src/web-globals.d.ts +103 -0
package/src/Transport.ts
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client's transport rules, shared by every request the SDK makes over HTTP: whether there is a backend at
|
|
3
|
+
* all (`BackendStatus`), how a failure is classed (`failureClass`: retried, counted, or final), a failure circuit
|
|
4
|
+
* that stops repeated failures from becoming a request storm (`makeCircuit`), and one action call over plain
|
|
5
|
+
* `fetch` with a timeout, an abort signal, `keepalive` and explicit retries (`httpAction`), which the read batch
|
|
6
|
+
* (`makeReader`) and the app-state client build on.
|
|
7
|
+
*
|
|
8
|
+
* Web-standard only: `fetch`, `AbortController` and timers, so it runs wherever the SDK runs (Hermes included).
|
|
9
|
+
*/
|
|
10
|
+
import { CLIENT_VERSION_HEADER, HTTP_ACTIONS_PREFIX, IDEMPOTENCY_HEADER } from "@eloxiv/contracts"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Whether the client has a backend to talk to:
|
|
14
|
+
* - `available`: requests go out;
|
|
15
|
+
* - `disabled`: the host supplies no backend on purpose (a standalone or static build, a preview, a host that
|
|
16
|
+
* proxies none), with the reason; every request is refused before it is made;
|
|
17
|
+
* - `unavailable`: the backend is there but failing; the circuit is open until `retryAt` (ms since the epoch).
|
|
18
|
+
*/
|
|
19
|
+
export type BackendStatus =
|
|
20
|
+
| { readonly state: "available" }
|
|
21
|
+
| { readonly state: "disabled"; readonly reason: string }
|
|
22
|
+
| { readonly state: "unavailable"; readonly reason: string; readonly retryAt: number; readonly failures: number }
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A request refused or failed by the transport or the kernel: `error` is the kernel's (`_tag`, `message` and its
|
|
26
|
+
* fields) or the transport's own (`BackendDisabled`, `BackendUnavailable`, `Timeout`, `Aborted`, `NetworkError`),
|
|
27
|
+
* `status` the HTTP status, or 0 when nothing answered.
|
|
28
|
+
*/
|
|
29
|
+
export class RequestError extends Error {
|
|
30
|
+
override readonly name = "RequestError"
|
|
31
|
+
readonly status: number
|
|
32
|
+
readonly error: { readonly _tag: string; readonly message?: string; readonly [field: string]: unknown }
|
|
33
|
+
constructor(status: number, error: { readonly _tag: string; readonly [field: string]: unknown }) {
|
|
34
|
+
super(`${error._tag}${typeof error["message"] === "string" ? `: ${error["message"]}` : ""}`)
|
|
35
|
+
this.status = status
|
|
36
|
+
this.error = error
|
|
37
|
+
}
|
|
38
|
+
get _tag(): string {
|
|
39
|
+
return this.error._tag
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* How a failure counts:
|
|
45
|
+
* - `retry`: nothing definitive came back (no answer, a timeout, 408, 429, a gateway's 502, 503 or 504): worth
|
|
46
|
+
* trying again later, and counted by the circuit;
|
|
47
|
+
* - `server`: the server failed (another 5xx): counted by the circuit, not retried;
|
|
48
|
+
* - `auth`: the credential was refused (401): final, and the reader stops using that credential;
|
|
49
|
+
* - `final`: the kernel answered with a refusal (any other 4xx): final, never retried, not counted. Asking again
|
|
50
|
+
* gets the same answer, so a not-found or forbidden read never turns into a storm.
|
|
51
|
+
*/
|
|
52
|
+
export type FailureClass = "retry" | "server" | "auth" | "final"
|
|
53
|
+
|
|
54
|
+
export const failureClass = (status: number): FailureClass =>
|
|
55
|
+
status === 0 || status === 408 || status === 429 || status === 502 || status === 503 || status === 504
|
|
56
|
+
? "retry"
|
|
57
|
+
: status >= 500
|
|
58
|
+
? "server"
|
|
59
|
+
: status === 401
|
|
60
|
+
? "auth"
|
|
61
|
+
: "final"
|
|
62
|
+
|
|
63
|
+
/** A transport refusal of the client's own (nothing was sent). */
|
|
64
|
+
const refusal = (status: BackendStatus): RequestError =>
|
|
65
|
+
status.state === "disabled"
|
|
66
|
+
? new RequestError(0, { _tag: "BackendDisabled", message: status.reason })
|
|
67
|
+
: new RequestError(0, {
|
|
68
|
+
_tag: "BackendUnavailable",
|
|
69
|
+
message: status.state === "unavailable" ? status.reason : "unavailable",
|
|
70
|
+
retryAt: status.state === "unavailable" ? status.retryAt : 0,
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
export interface CircuitOptions {
|
|
74
|
+
/** Consecutive counted failures that open the circuit (default 5). */
|
|
75
|
+
readonly threshold?: number | undefined
|
|
76
|
+
/** How long it stays open before one request may try again (ms, default 15 000). */
|
|
77
|
+
readonly cooldownMs?: number | undefined
|
|
78
|
+
/** The clock (ms since the epoch); for tests. */
|
|
79
|
+
readonly now?: (() => number) | undefined
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A failure circuit for one backend. Closed, requests go out; `threshold` counted failures in a row (`retry` and
|
|
84
|
+
* `server` classes) open it, and while open every request is refused at once (`BackendUnavailable`, with
|
|
85
|
+
* `retryAt`), without being sent. Once the cooldown has passed one request goes out (half-open): its success
|
|
86
|
+
* closes the circuit, its failure opens it for another cooldown. Any success resets the count.
|
|
87
|
+
*/
|
|
88
|
+
export const makeCircuit = (options: CircuitOptions = {}) => {
|
|
89
|
+
const threshold = options.threshold ?? 5
|
|
90
|
+
const cooldownMs = options.cooldownMs ?? 15_000
|
|
91
|
+
const now = options.now ?? Date.now
|
|
92
|
+
let failures = 0
|
|
93
|
+
let openUntil = 0
|
|
94
|
+
let probing = false
|
|
95
|
+
const listeners = new Set<(status: BackendStatus) => void>()
|
|
96
|
+
const status = (): BackendStatus =>
|
|
97
|
+
failures >= threshold
|
|
98
|
+
? { state: "unavailable", reason: `${failures} requests failed in a row`, retryAt: openUntil, failures }
|
|
99
|
+
: { state: "available" }
|
|
100
|
+
const changed = (before: BackendStatus) => {
|
|
101
|
+
const after = status()
|
|
102
|
+
if (after.state !== before.state) for (const listener of listeners) listener(after)
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
status,
|
|
106
|
+
/** Is the circuit open now (refusing every request until its cooldown has passed)? */
|
|
107
|
+
isOpen: (): boolean => failures >= threshold && now() < openUntil,
|
|
108
|
+
/** May a request go out now? Half-open after the cooldown: one request at a time is let through. */
|
|
109
|
+
admit: (): boolean => {
|
|
110
|
+
if (failures < threshold) return true
|
|
111
|
+
if (now() < openUntil || probing) return false
|
|
112
|
+
probing = true
|
|
113
|
+
return true
|
|
114
|
+
},
|
|
115
|
+
succeeded: () => {
|
|
116
|
+
const before = status()
|
|
117
|
+
failures = 0
|
|
118
|
+
probing = false
|
|
119
|
+
changed(before)
|
|
120
|
+
},
|
|
121
|
+
/** A finished request's failure, counted only when its class is `retry` or `server`. */
|
|
122
|
+
failed: (kind: FailureClass) => {
|
|
123
|
+
if (kind !== "retry" && kind !== "server") {
|
|
124
|
+
probing = false
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
const before = status()
|
|
128
|
+
failures += 1
|
|
129
|
+
probing = false
|
|
130
|
+
if (failures >= threshold) openUntil = now() + cooldownMs
|
|
131
|
+
changed(before)
|
|
132
|
+
},
|
|
133
|
+
/** Told of every change between available and unavailable; returns the unsubscribe. */
|
|
134
|
+
subscribe: (listener: (status: BackendStatus) => void) => {
|
|
135
|
+
listeners.add(listener)
|
|
136
|
+
return () => {
|
|
137
|
+
listeners.delete(listener)
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
export type Circuit = ReturnType<typeof makeCircuit>
|
|
143
|
+
|
|
144
|
+
/** The parts of an abort signal used here (pass an `AbortController`'s `signal`). */
|
|
145
|
+
export interface SignalLike {
|
|
146
|
+
readonly aborted: boolean
|
|
147
|
+
readonly addEventListener: (type: "abort", listener: () => void, options?: { readonly once?: boolean }) => void
|
|
148
|
+
readonly removeEventListener: (type: "abort", listener: () => void) => void
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A signal as `fetch` takes it, whatever the platform's types call a signal (the SDK's own, the DOM's, React
|
|
153
|
+
* Native's): every runtime's fetch takes an `AbortController`'s signal, which `SignalLike` describes.
|
|
154
|
+
*/
|
|
155
|
+
export const fetchSignal = (signal: SignalLike): never => signal as never
|
|
156
|
+
|
|
157
|
+
/** Who a request acts as, and where; each read when the request is made. */
|
|
158
|
+
export interface TransportOptions {
|
|
159
|
+
/** Kernel base URL, e.g. `http://localhost:4100`. */
|
|
160
|
+
readonly baseUrl: string
|
|
161
|
+
readonly token?: (() => string | undefined) | undefined
|
|
162
|
+
readonly orgId?: string | (() => string | undefined) | undefined
|
|
163
|
+
readonly clientVersion?: string | undefined
|
|
164
|
+
/** A host that supplies no backend says so, with why: every request is refused before it is made. */
|
|
165
|
+
readonly backend?: { readonly disabled: string } | undefined
|
|
166
|
+
/** The backend's failure circuit, shared by every client of the same backend (default: one of its own). */
|
|
167
|
+
readonly circuit?: Circuit | undefined
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface RequestOptions {
|
|
171
|
+
/** Abort the request (it rejects with `Aborted`). */
|
|
172
|
+
readonly signal?: SignalLike | undefined
|
|
173
|
+
/** Give up after this long (ms); it rejects with `Timeout` (status 0: the outcome is unknown). */
|
|
174
|
+
readonly timeoutMs?: number | undefined
|
|
175
|
+
/**
|
|
176
|
+
* Let the request outlive the page (`fetch`'s `keepalive`), for state published while navigating away. Browsers
|
|
177
|
+
* limit a keepalive body to 64 KiB.
|
|
178
|
+
*/
|
|
179
|
+
readonly keepalive?: boolean | undefined
|
|
180
|
+
/**
|
|
181
|
+
* Tries after the first, only for failures of class `retry`, backing off from `retryBaseMs` (default 250 ms).
|
|
182
|
+
* Retrying a write is only safe with an idempotency key: `httpAction` refuses retries for a call without one.
|
|
183
|
+
*/
|
|
184
|
+
readonly retries?: number | undefined
|
|
185
|
+
readonly retryBaseMs?: number | undefined
|
|
186
|
+
readonly idempotencyKey?: string | undefined
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const resolveOrg = (orgId: TransportOptions["orgId"]) => (typeof orgId === "function" ? orgId() : orgId)
|
|
190
|
+
|
|
191
|
+
/** The headers a request acting as `options` sends. */
|
|
192
|
+
export const requestHeaders = (
|
|
193
|
+
options: TransportOptions,
|
|
194
|
+
extra: Record<string, string> = {},
|
|
195
|
+
): Record<string, string> => {
|
|
196
|
+
const result: Record<string, string> = { ...extra }
|
|
197
|
+
const token = options.token?.()
|
|
198
|
+
if (token !== undefined) result["authorization"] = `Bearer ${token}`
|
|
199
|
+
const orgId = resolveOrg(options.orgId)
|
|
200
|
+
if (orgId !== undefined) result["x-eloxiv-org"] = orgId
|
|
201
|
+
if (options.clientVersion !== undefined) result[CLIENT_VERSION_HEADER] = options.clientVersion
|
|
202
|
+
return result
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The transport's backend status: disabled by the host, else the circuit's. */
|
|
206
|
+
export const backendStatus = (options: TransportOptions, circuit: Circuit): BackendStatus =>
|
|
207
|
+
options.backend !== undefined ? { state: "disabled", reason: options.backend.disabled } : circuit.status()
|
|
208
|
+
|
|
209
|
+
/** Read through a function so a check after an `await` is not narrowed by one before it. */
|
|
210
|
+
const isAborted = (signal: SignalLike | undefined) => signal?.aborted === true
|
|
211
|
+
|
|
212
|
+
const sleep = (ms: number, signal: SignalLike | undefined) =>
|
|
213
|
+
new Promise<void>((resolve) => {
|
|
214
|
+
const timer = setTimeout(done, ms)
|
|
215
|
+
function done() {
|
|
216
|
+
clearTimeout(timer)
|
|
217
|
+
signal?.removeEventListener("abort", done)
|
|
218
|
+
resolve()
|
|
219
|
+
}
|
|
220
|
+
signal?.addEventListener("abort", done, { once: true })
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One JSON request through the transport's rules: refused at once while the backend is disabled or its circuit
|
|
225
|
+
* open; aborted by `signal` or after `timeoutMs`; retried on failures of class `retry` up to `retries` times; every
|
|
226
|
+
* outcome told to the circuit. Resolves with the parsed body of a 2xx answer; rejects with `RequestError`.
|
|
227
|
+
*/
|
|
228
|
+
export const sendJson = async (
|
|
229
|
+
options: TransportOptions,
|
|
230
|
+
circuit: Circuit,
|
|
231
|
+
path: string,
|
|
232
|
+
body: unknown,
|
|
233
|
+
request: RequestOptions = {},
|
|
234
|
+
): Promise<unknown> => {
|
|
235
|
+
const retries = Math.max(0, request.retries ?? 0)
|
|
236
|
+
// Who the request acts as, and where, read once: a retry is the same request, so a switch of organisation (or a
|
|
237
|
+
// new token) meanwhile never sends it again somewhere else under the same idempotency key.
|
|
238
|
+
const headers = requestHeaders(options, {
|
|
239
|
+
"content-type": "application/json",
|
|
240
|
+
...(request.idempotencyKey === undefined ? {} : { [IDEMPOTENCY_HEADER]: request.idempotencyKey }),
|
|
241
|
+
})
|
|
242
|
+
for (let attempt = 0; ; attempt++) {
|
|
243
|
+
const status = backendStatus(options, circuit)
|
|
244
|
+
if (status.state === "disabled") throw refusal(status)
|
|
245
|
+
if (request.signal?.aborted === true) throw new RequestError(0, { _tag: "Aborted", message: "aborted" })
|
|
246
|
+
if (!circuit.admit()) throw refusal(circuit.status())
|
|
247
|
+
const controller = new AbortController()
|
|
248
|
+
const abort = () => controller.abort()
|
|
249
|
+
request.signal?.addEventListener("abort", abort, { once: true })
|
|
250
|
+
let timedOut = false
|
|
251
|
+
const timer =
|
|
252
|
+
request.timeoutMs === undefined
|
|
253
|
+
? undefined
|
|
254
|
+
: setTimeout(() => {
|
|
255
|
+
timedOut = true
|
|
256
|
+
controller.abort()
|
|
257
|
+
}, request.timeoutMs)
|
|
258
|
+
let failure: RequestError
|
|
259
|
+
try {
|
|
260
|
+
const response = await fetch(`${options.baseUrl}${path}`, {
|
|
261
|
+
method: "POST",
|
|
262
|
+
headers,
|
|
263
|
+
body: JSON.stringify(body),
|
|
264
|
+
signal: controller.signal,
|
|
265
|
+
...(request.keepalive === true ? { keepalive: true } : {}),
|
|
266
|
+
})
|
|
267
|
+
if (response.ok) {
|
|
268
|
+
// A success whose body did not arrive is a lost answer (it may have run), not an empty one: it throws, and
|
|
269
|
+
// is retried like any answer that did not come back.
|
|
270
|
+
const answer: unknown = await response.json()
|
|
271
|
+
circuit.succeeded()
|
|
272
|
+
return answer
|
|
273
|
+
}
|
|
274
|
+
const parsed = (await response.json().catch(() => ({}))) as Record<string, unknown>
|
|
275
|
+
failure = new RequestError(response.status, {
|
|
276
|
+
...parsed,
|
|
277
|
+
_tag: typeof parsed["_tag"] === "string" ? parsed["_tag"] : `HTTP ${response.status}`,
|
|
278
|
+
})
|
|
279
|
+
} catch (error) {
|
|
280
|
+
failure =
|
|
281
|
+
error instanceof RequestError
|
|
282
|
+
? error
|
|
283
|
+
: timedOut
|
|
284
|
+
? new RequestError(0, { _tag: "Timeout", message: `No answer within ${request.timeoutMs} ms` })
|
|
285
|
+
: isAborted(request.signal)
|
|
286
|
+
? new RequestError(0, { _tag: "Aborted", message: "aborted" })
|
|
287
|
+
: new RequestError(0, { _tag: "NetworkError", message: String(error) })
|
|
288
|
+
} finally {
|
|
289
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
290
|
+
request.signal?.removeEventListener("abort", abort)
|
|
291
|
+
}
|
|
292
|
+
const kind = failureClass(failure.status)
|
|
293
|
+
// An abort is the caller's, not the backend's: the circuit is not told.
|
|
294
|
+
if (failure._tag === "Aborted") circuit.failed("final")
|
|
295
|
+
else circuit.failed(kind)
|
|
296
|
+
if (failure._tag === "Aborted" || kind !== "retry" || attempt >= retries) throw failure
|
|
297
|
+
await sleep((request.retryBaseMs ?? 250) * 2 ** attempt, request.signal)
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* One action called over HTTP (`POST /api/actions/<action>`), the same invocation path as the typed client's
|
|
303
|
+
* `call`, with the transport's rules (`sendJson`): for what the RPC client does not give, a timeout per call, an
|
|
304
|
+
* abort signal, `keepalive` and explicit retries. Resolves with the result envelope (`{ kind: "output", output }`
|
|
305
|
+
* or a replay); rejects with `RequestError`. Retries need an idempotency key (a write retried without one could
|
|
306
|
+
* run twice): asking for them without one is refused before anything is sent.
|
|
307
|
+
*/
|
|
308
|
+
export const httpAction = (
|
|
309
|
+
options: TransportOptions,
|
|
310
|
+
circuit: Circuit,
|
|
311
|
+
action: string,
|
|
312
|
+
input: unknown,
|
|
313
|
+
request: RequestOptions = {},
|
|
314
|
+
): Promise<unknown> => {
|
|
315
|
+
if ((request.retries ?? 0) > 0 && request.idempotencyKey === undefined) {
|
|
316
|
+
return Promise.reject(
|
|
317
|
+
new RequestError(0, { _tag: "InvalidInput", message: "Retrying a call needs an idempotency key" }),
|
|
318
|
+
)
|
|
319
|
+
}
|
|
320
|
+
return sendJson(options, circuit, `${HTTP_ACTIONS_PREFIX}/${action}`, input, request)
|
|
321
|
+
}
|
package/src/Upload.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uploading a file (the Files contract's resumable multipart upload) as one call with its status: begin (the
|
|
3
|
+
* kernel checks the size, the type, the record's `attach` policy and the quota before anything is stored), each part
|
|
4
|
+
* sent to its single-use URL with the bytes sent so far reported, an interrupted part resumed with fresh URLs
|
|
5
|
+
* (`files.resumeUpload`: the parts received are not sent again), then complete. What comes back is the file's id, a
|
|
6
|
+
* durable reference to attach or send to the agent; never the bytes inline. The file is `processing` until the
|
|
7
|
+
* kernel's inspection makes it `available` (the replica's file row says when).
|
|
8
|
+
*/
|
|
9
|
+
import { FILES_ACTIONS, type PartUrl, type UploadPlan } from "@eloxiv/contracts"
|
|
10
|
+
import {
|
|
11
|
+
type Circuit,
|
|
12
|
+
fetchSignal,
|
|
13
|
+
httpAction,
|
|
14
|
+
makeCircuit,
|
|
15
|
+
RequestError,
|
|
16
|
+
type SignalLike,
|
|
17
|
+
type TransportOptions,
|
|
18
|
+
} from "./Transport.ts"
|
|
19
|
+
|
|
20
|
+
export type UploadStatus =
|
|
21
|
+
| { readonly phase: "starting" }
|
|
22
|
+
| { readonly phase: "uploading"; readonly fileId: string; readonly sent: number; readonly total: number }
|
|
23
|
+
| { readonly phase: "completing"; readonly fileId: string }
|
|
24
|
+
| { readonly phase: "processing"; readonly fileId: string }
|
|
25
|
+
| { readonly phase: "failed"; readonly fileId: string | null; readonly error: RequestError }
|
|
26
|
+
|
|
27
|
+
export interface UploadRequest {
|
|
28
|
+
readonly name: string
|
|
29
|
+
readonly contentType: string
|
|
30
|
+
readonly bytes: Uint8Array
|
|
31
|
+
/** Attach it to this record once complete (the entity's `attach` policy). */
|
|
32
|
+
readonly attachTo?: { readonly entity: string; readonly id: string } | undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface UploadOptions {
|
|
36
|
+
readonly onStatus?: ((status: UploadStatus) => void) | undefined
|
|
37
|
+
/** Aborting stops sending and abandons the upload (`files.abortUpload`: its quota is released). */
|
|
38
|
+
readonly signal?: SignalLike | undefined
|
|
39
|
+
/** Resumes after a part failed without a definitive answer (default 3). */
|
|
40
|
+
readonly resumes?: number | undefined
|
|
41
|
+
readonly circuit?: Circuit | undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const outputOf = (envelope: unknown): unknown => (envelope as { output: unknown }).output
|
|
45
|
+
/** Read through a function so a check after an `await` is not narrowed by one before it. */
|
|
46
|
+
const isAborted = (signal: SignalLike | undefined) => signal?.aborted === true
|
|
47
|
+
|
|
48
|
+
export const uploadFile = async (
|
|
49
|
+
transport: TransportOptions,
|
|
50
|
+
file: UploadRequest,
|
|
51
|
+
options: UploadOptions = {},
|
|
52
|
+
): Promise<{ readonly fileId: string }> => {
|
|
53
|
+
const circuit = options.circuit ?? transport.circuit ?? makeCircuit()
|
|
54
|
+
const status = (next: UploadStatus) => options.onStatus?.(next)
|
|
55
|
+
const action = async <A>(name: string, input: unknown) =>
|
|
56
|
+
outputOf(await httpAction(transport, circuit, name, input, { signal: options.signal })) as A
|
|
57
|
+
status({ phase: "starting" })
|
|
58
|
+
let fileId: string | null = null
|
|
59
|
+
try {
|
|
60
|
+
let plan = await action<UploadPlan>(FILES_ACTIONS.beginUpload, {
|
|
61
|
+
name: file.name,
|
|
62
|
+
contentType: file.contentType,
|
|
63
|
+
size: file.bytes.length,
|
|
64
|
+
...(file.attachTo === undefined ? {} : { attachTo: file.attachTo }),
|
|
65
|
+
})
|
|
66
|
+
fileId = plan.fileId
|
|
67
|
+
const total = file.bytes.length
|
|
68
|
+
const partBytes = (part: PartUrl) => {
|
|
69
|
+
const start = (part.partNumber - 1) * plan.partSize
|
|
70
|
+
return file.bytes.slice(start, start + part.size)
|
|
71
|
+
}
|
|
72
|
+
let received = new Set(plan.received)
|
|
73
|
+
const sentSoFar = () =>
|
|
74
|
+
[...received].reduce((sum, n) => sum + Math.min(plan.partSize, total - (n - 1) * plan.partSize), 0)
|
|
75
|
+
let resumes = options.resumes ?? 3
|
|
76
|
+
status({ phase: "uploading", fileId, sent: sentSoFar(), total })
|
|
77
|
+
for (;;) {
|
|
78
|
+
let failed: RequestError | undefined
|
|
79
|
+
for (const part of plan.parts) {
|
|
80
|
+
if (received.has(part.partNumber)) continue
|
|
81
|
+
if (isAborted(options.signal)) throw new RequestError(0, { _tag: "Aborted", message: "aborted" })
|
|
82
|
+
let response: { readonly ok: boolean; readonly status: number }
|
|
83
|
+
try {
|
|
84
|
+
response = await fetch(part.url, {
|
|
85
|
+
method: "PUT",
|
|
86
|
+
headers: part.headers,
|
|
87
|
+
body: partBytes(part),
|
|
88
|
+
...(options.signal === undefined ? {} : { signal: fetchSignal(options.signal) }),
|
|
89
|
+
})
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (isAborted(options.signal)) throw new RequestError(0, { _tag: "Aborted", message: "aborted" })
|
|
92
|
+
failed = new RequestError(0, { _tag: "NetworkError", message: String(error) })
|
|
93
|
+
break
|
|
94
|
+
}
|
|
95
|
+
if (!response.ok) {
|
|
96
|
+
// 409: the URL was used (an answer lost); 5xx or none: try again. A 4xx refusal is final.
|
|
97
|
+
failed = new RequestError(response.status, {
|
|
98
|
+
_tag: `HTTP ${response.status}`,
|
|
99
|
+
message: "The part was refused",
|
|
100
|
+
})
|
|
101
|
+
if (response.status !== 409 && response.status < 500) throw failed
|
|
102
|
+
break
|
|
103
|
+
}
|
|
104
|
+
received.add(part.partNumber)
|
|
105
|
+
status({ phase: "uploading", fileId, sent: sentSoFar(), total })
|
|
106
|
+
}
|
|
107
|
+
if (failed === undefined) break
|
|
108
|
+
if (resumes-- <= 0) throw failed
|
|
109
|
+
plan = await action<UploadPlan>(FILES_ACTIONS.resumeUpload, { fileId })
|
|
110
|
+
received = new Set(plan.received)
|
|
111
|
+
}
|
|
112
|
+
status({ phase: "completing", fileId })
|
|
113
|
+
await action(FILES_ACTIONS.completeUpload, { fileId })
|
|
114
|
+
status({ phase: "processing", fileId })
|
|
115
|
+
return { fileId }
|
|
116
|
+
} catch (error) {
|
|
117
|
+
const failure =
|
|
118
|
+
error instanceof RequestError ? error : new RequestError(0, { _tag: "NetworkError", message: String(error) })
|
|
119
|
+
if (fileId !== null && failure._tag === "Aborted") {
|
|
120
|
+
await httpAction(transport, circuit, FILES_ACTIONS.abortUpload, { fileId }).catch(() => undefined)
|
|
121
|
+
}
|
|
122
|
+
status({ phase: "failed", fileId, error: failure })
|
|
123
|
+
throw failure
|
|
124
|
+
}
|
|
125
|
+
}
|