@rojaebl/supa-store 0.0.0-stage → 0.7.2
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 +707 -3
- package/dist/derived.d.ts +9 -0
- package/dist/derived.js +103 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +271 -0
- package/dist/label.d.ts +5 -0
- package/dist/label.js +38 -0
- package/dist/mutation.d.ts +46 -0
- package/dist/mutation.js +131 -0
- package/dist/query.d.ts +184 -0
- package/dist/query.js +301 -0
- package/dist/react.d.ts +29 -0
- package/dist/react.js +36 -0
- package/dist/refetch.d.ts +25 -0
- package/dist/refetch.js +117 -0
- package/dist/resourceHook.d.ts +57 -0
- package/dist/resourceHook.js +292 -0
- package/dist/rpc/client.d.ts +65 -0
- package/dist/rpc/client.js +226 -0
- package/dist/rpc/error.d.ts +7 -0
- package/dist/rpc/error.js +13 -0
- package/dist/rpc/framing.d.ts +4 -0
- package/dist/rpc/framing.js +64 -0
- package/dist/rpc/index.d.ts +4 -0
- package/dist/rpc/index.js +4 -0
- package/dist/rpc/session.d.ts +18 -0
- package/dist/rpc/session.js +120 -0
- package/dist/rpc/transport.d.ts +26 -0
- package/dist/rpc/transport.js +122 -0
- package/dist/server/core.d.ts +72 -0
- package/dist/server/core.js +367 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +2 -0
- package/dist/server/node.d.ts +12 -0
- package/dist/server/node.js +240 -0
- package/dist/server/sse.d.ts +10 -0
- package/dist/server/sse.js +25 -0
- package/dist/server/web.d.ts +8 -0
- package/dist/server/web.js +147 -0
- package/dist/stream/client.d.ts +43 -0
- package/dist/stream/client.js +397 -0
- package/dist/stream/hook.d.ts +9 -0
- package/dist/stream/hook.js +70 -0
- package/dist/stream/index.d.ts +53 -0
- package/dist/stream/index.js +43 -0
- package/dist/stream/protocol.d.ts +105 -0
- package/dist/stream/protocol.js +32 -0
- package/dist/track.d.ts +19 -0
- package/dist/track.js +25 -0
- package/package.json +104 -3
- package/tools/decline-loader.cjs +8 -0
- package/tools/definition.cjs +14 -0
- package/tools/next.d.mts +2 -0
- package/tools/next.mjs +30 -0
- package/tools/vite.d.mts +3 -0
- package/tools/vite.mjs +43 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
// 화면 쪽 연결(스펙 §7 · §8) — 웹소켓 · SSE(fetch 스트림)로 홉에 붙어 값을 따라가고 명령을 보낸다
|
|
2
|
+
// 다시 잇기 · 따라잡기 · 명령의 답을 여기서 맡는다. node · React 의 어느 것도 들이지 않는다(전역 WebSocket · fetch)
|
|
3
|
+
import { CLOSE, DEFAULTS, HEADER, TEXT } from "./protocol.js";
|
|
4
|
+
const failure = (message, requestId) => Object.assign(new Error(message), { requestId });
|
|
5
|
+
/** 요청 id — randomUUID 는 보안 문맥(https · localhost)에만 있으므로 http://LAN-IP 에서는 getRandomValues 로 */
|
|
6
|
+
const newId = () => typeof crypto.randomUUID === "function"
|
|
7
|
+
? crypto.randomUUID()
|
|
8
|
+
: Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
9
|
+
/** 시험 전용 — 다시 잇기의 첫 간격(ms)을 줄인다. 하위 경로로 내보내지 않는다 */
|
|
10
|
+
export const TIMING = Symbol("supa-store.timing");
|
|
11
|
+
/** SSE 본문 읽기 — 조각을 받아 이벤트마다 data 줄을 \n 으로 이어 넘긴다
|
|
12
|
+
* 줄 끝은 \r\n · \r · \n 모두, : 로 시작하는 줄은 주석, data 밖의 칸(id · event · retry)은 버린다 */
|
|
13
|
+
export function sseParser(onData) {
|
|
14
|
+
let buf = "";
|
|
15
|
+
let data = [];
|
|
16
|
+
return (chunk) => {
|
|
17
|
+
buf += chunk;
|
|
18
|
+
for (;;) {
|
|
19
|
+
const at = buf.search(/[\r\n]/);
|
|
20
|
+
if (at < 0)
|
|
21
|
+
return;
|
|
22
|
+
// 끝의 \r 은 다음 조각의 \n 과 한 줄 끝일 수 있으므로 기다린다
|
|
23
|
+
if (buf[at] === "\r" && at === buf.length - 1)
|
|
24
|
+
return;
|
|
25
|
+
const line = buf.slice(0, at);
|
|
26
|
+
buf = buf.slice(at + (buf[at] === "\r" && buf[at + 1] === "\n" ? 2 : 1));
|
|
27
|
+
if (line === "") {
|
|
28
|
+
if (data.length)
|
|
29
|
+
onData(data.join("\n"));
|
|
30
|
+
data = [];
|
|
31
|
+
}
|
|
32
|
+
else if (!line.startsWith(":")) {
|
|
33
|
+
const colon = line.indexOf(":");
|
|
34
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
35
|
+
if (field === "data")
|
|
36
|
+
data.push(colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, ""));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function connect(o) {
|
|
42
|
+
const channel = o.channel ?? "default";
|
|
43
|
+
const firstGap = o[TIMING] ?? DEFAULTS.backoffStartMs;
|
|
44
|
+
const listeners = new Set();
|
|
45
|
+
const pending = new Map();
|
|
46
|
+
let data;
|
|
47
|
+
/** 값을 한 번이라도 받았나 — data 가 undefined 인 값도 있으므로 따로 든다 */
|
|
48
|
+
let has = false;
|
|
49
|
+
/** 가진 버전, 없으면 -1 */
|
|
50
|
+
let version = -1;
|
|
51
|
+
let epoch;
|
|
52
|
+
/** welcome.version — 여기에 이르면 따라잡기가 끝난다 */
|
|
53
|
+
let target = 0;
|
|
54
|
+
/** 끊긴 뒤 아직 따라잡지 못했다 — error 에 재시도 중 */
|
|
55
|
+
let broken = false;
|
|
56
|
+
/** 「다시 오지 마라」의 까닭 — 서면 다시 잇지 않는다 */
|
|
57
|
+
let dead;
|
|
58
|
+
let closed = false;
|
|
59
|
+
let cur;
|
|
60
|
+
let retry;
|
|
61
|
+
let attempt = 0;
|
|
62
|
+
let shown = { data, status: "loading", isFetching: true, error: null };
|
|
63
|
+
const emit = () => {
|
|
64
|
+
const caught = !!cur?.welcomed && version >= target;
|
|
65
|
+
if (caught) {
|
|
66
|
+
// 따라잡아야 이어진 것으로 친다 — 그때 간격을 1초로 되돌린다
|
|
67
|
+
broken = false;
|
|
68
|
+
cur.caught = true;
|
|
69
|
+
attempt = 0;
|
|
70
|
+
}
|
|
71
|
+
const next = dead !== undefined
|
|
72
|
+
? { data, status: "error", isFetching: false, error: dead }
|
|
73
|
+
: { data, status: has ? "ready" : "loading", isFetching: !caught, error: broken ? TEXT.reconnecting : null };
|
|
74
|
+
if (next.data === shown.data &&
|
|
75
|
+
next.status === shown.status &&
|
|
76
|
+
next.isFetching === shown.isFetching &&
|
|
77
|
+
next.error === shown.error)
|
|
78
|
+
return;
|
|
79
|
+
shown = next;
|
|
80
|
+
for (const fn of [...listeners])
|
|
81
|
+
fn();
|
|
82
|
+
};
|
|
83
|
+
// ── 명령 ──
|
|
84
|
+
const fail = (p, message) => {
|
|
85
|
+
clearTimeout(p.timer);
|
|
86
|
+
pending.delete(p.id);
|
|
87
|
+
p.reject(failure(message, p.id));
|
|
88
|
+
};
|
|
89
|
+
const finish = (p) => {
|
|
90
|
+
clearTimeout(p.timer);
|
|
91
|
+
pending.delete(p.id);
|
|
92
|
+
p.resolve(p.wait.result);
|
|
93
|
+
};
|
|
94
|
+
/** 제한 시간을 (다시) 센다 — 끊긴 채 지나면 결과를 확인하지 못한 것 */
|
|
95
|
+
const arm = (p) => {
|
|
96
|
+
clearTimeout(p.timer);
|
|
97
|
+
p.timer = setTimeout(() => fail(p, p.link === cur ? TEXT.timeout : TEXT.unknown), p.timeout);
|
|
98
|
+
};
|
|
99
|
+
const send = (p) => p.link.send({ t: "command", id: p.id, name: p.name, args: p.args });
|
|
100
|
+
/** reply · fate — 명령은 그 명령이 낸 바뀜이 data 에 든 뒤에 끝난다(§7.4) */
|
|
101
|
+
const answered = (m) => {
|
|
102
|
+
const p = pending.get(m.id);
|
|
103
|
+
if (!p || p.wait)
|
|
104
|
+
return;
|
|
105
|
+
if (m.t === "fate" && m.state === "unknown-id")
|
|
106
|
+
return fail(p, TEXT.commandFailed);
|
|
107
|
+
if (m.t === "fate" && m.state === "running") {
|
|
108
|
+
// 같은 id 로 다시 보내면 홉은 돌리지 않고 도는 중인 그 답을 이 연결로 준다
|
|
109
|
+
arm(p);
|
|
110
|
+
return send(p);
|
|
111
|
+
}
|
|
112
|
+
const out = m;
|
|
113
|
+
// ok: false 는 version 0 — data 를 기다리지 않는다(연결의 약속 11)
|
|
114
|
+
if (!out.ok)
|
|
115
|
+
return fail(p, out.error);
|
|
116
|
+
p.wait = { version: out.version, result: out.result };
|
|
117
|
+
if (version >= out.version)
|
|
118
|
+
finish(p);
|
|
119
|
+
};
|
|
120
|
+
/** 서버의 request 를 handlers 로 — 없는 이름 · 던짐은 ok: false */
|
|
121
|
+
const serve = async (link, m) => {
|
|
122
|
+
const fn = o.handlers && Object.hasOwn(o.handlers, m.method) ? o.handlers[m.method] : undefined;
|
|
123
|
+
let out;
|
|
124
|
+
if (!fn)
|
|
125
|
+
out = { ok: false, error: `알 수 없는 요청: ${m.method}` };
|
|
126
|
+
else
|
|
127
|
+
try {
|
|
128
|
+
out = { ok: true, result: await fn(...m.params) };
|
|
129
|
+
}
|
|
130
|
+
catch (e) {
|
|
131
|
+
out = { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
132
|
+
}
|
|
133
|
+
if (cur === link)
|
|
134
|
+
link.send({ t: "answer", id: m.id, ...out });
|
|
135
|
+
};
|
|
136
|
+
// ── 연결 ──
|
|
137
|
+
/** 아무것도 받지 못한 채 60초면 끊긴 것 */
|
|
138
|
+
const watch = (link) => {
|
|
139
|
+
if (cur !== link)
|
|
140
|
+
return;
|
|
141
|
+
clearTimeout(link.idle);
|
|
142
|
+
link.idle = setTimeout(() => lost(link), DEFAULTS.idleMs);
|
|
143
|
+
};
|
|
144
|
+
/** 1초부터 두 배, 30초에서 멈추고 ±20% 를 흔든다 */
|
|
145
|
+
const backoff = () => {
|
|
146
|
+
const ms = Math.min(firstGap * 2 ** attempt++, DEFAULTS.backoffMaxMs);
|
|
147
|
+
return Math.round(ms * (1 + DEFAULTS.jitter * (2 * Math.random() - 1)));
|
|
148
|
+
};
|
|
149
|
+
/** 그 연결이 끊겼다 — 4001 이면 멈추고, 아니면 다시 잇는다 */
|
|
150
|
+
const lost = (link, code, reason = "") => {
|
|
151
|
+
if (cur !== link)
|
|
152
|
+
return;
|
|
153
|
+
cur = undefined;
|
|
154
|
+
clearTimeout(link.idle);
|
|
155
|
+
link.stop();
|
|
156
|
+
if (code === CLOSE.GO_AWAY) {
|
|
157
|
+
dead = reason;
|
|
158
|
+
for (const p of [...pending.values()])
|
|
159
|
+
fail(p, TEXT.unknown);
|
|
160
|
+
return emit();
|
|
161
|
+
}
|
|
162
|
+
broken = true;
|
|
163
|
+
// 「곧 다시 와라」 · 건너뛰기는 곧바로 — 따라잡은 적 없는 연결이면(welcome 뒤 snapshot 이 실패한 4000 등) 늦춘다.
|
|
164
|
+
// welcome 만 보고 곧바로 다시 이으면 늘 실패하는 홉에 쉼 없이 몰린다
|
|
165
|
+
retry = setTimeout(open, code === CLOSE.COME_BACK && link.caught ? 0 : backoff());
|
|
166
|
+
emit();
|
|
167
|
+
};
|
|
168
|
+
const receive = (link, m) => {
|
|
169
|
+
if (cur !== link)
|
|
170
|
+
return; // 앞 연결의 늦은 메시지
|
|
171
|
+
switch (m.t) {
|
|
172
|
+
case "welcome": {
|
|
173
|
+
// 서버가 다시 떴다 — 버전이 0 부터 다시 세므로 가진 버전을 버리고 snapshot 을 기다린다
|
|
174
|
+
const fresh = epoch !== undefined && m.epoch !== epoch;
|
|
175
|
+
epoch = m.epoch;
|
|
176
|
+
target = m.version;
|
|
177
|
+
link.welcomed = true;
|
|
178
|
+
link.connection = m.connection;
|
|
179
|
+
if (fresh)
|
|
180
|
+
version = -1;
|
|
181
|
+
const asked = [];
|
|
182
|
+
for (const p of [...pending.values()]) {
|
|
183
|
+
if (p.link === link)
|
|
184
|
+
continue;
|
|
185
|
+
// 서버가 기록을 잃었으니 확인할 길이 없다. 답을 받아 data 를 기다리던 것은 snapshot 이 끝낸다
|
|
186
|
+
if (fresh && !p.wait) {
|
|
187
|
+
fail(p, TEXT.unknown);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
p.link = link;
|
|
191
|
+
arm(p);
|
|
192
|
+
if (!p.wait)
|
|
193
|
+
asked.push(p.id);
|
|
194
|
+
}
|
|
195
|
+
if (asked.length)
|
|
196
|
+
link.send({ t: "ask", ids: asked });
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
case "snapshot":
|
|
200
|
+
data = m.value;
|
|
201
|
+
has = true;
|
|
202
|
+
version = m.version;
|
|
203
|
+
// 값 전체를 받았으니 기다리던 명령의 바뀜도 들어 있다
|
|
204
|
+
for (const p of [...pending.values()])
|
|
205
|
+
if (p.wait)
|
|
206
|
+
finish(p);
|
|
207
|
+
break;
|
|
208
|
+
case "change":
|
|
209
|
+
if (m.version <= version)
|
|
210
|
+
return;
|
|
211
|
+
// 하나 넘게 건너뛰었다 — 다시 이어 hello 로 따라잡는다
|
|
212
|
+
if (m.version > version + 1)
|
|
213
|
+
return lost(link, CLOSE.COME_BACK);
|
|
214
|
+
data = o.reduce ? o.reduce(data, m.change) : m.change;
|
|
215
|
+
version = m.version;
|
|
216
|
+
for (const p of [...pending.values()])
|
|
217
|
+
if (p.wait && p.wait.version <= version)
|
|
218
|
+
finish(p);
|
|
219
|
+
break;
|
|
220
|
+
case "reply":
|
|
221
|
+
case "fate":
|
|
222
|
+
return answered(m);
|
|
223
|
+
case "request":
|
|
224
|
+
return void serve(link, m);
|
|
225
|
+
case "ping":
|
|
226
|
+
if (o.transport !== "sse")
|
|
227
|
+
link.send({ t: "pong" });
|
|
228
|
+
return;
|
|
229
|
+
case "close":
|
|
230
|
+
return lost(link, m.code, m.reason);
|
|
231
|
+
}
|
|
232
|
+
emit();
|
|
233
|
+
};
|
|
234
|
+
const open = async () => {
|
|
235
|
+
retry = undefined;
|
|
236
|
+
const link = { welcomed: false, send() { }, stop() { } };
|
|
237
|
+
cur = link;
|
|
238
|
+
let token;
|
|
239
|
+
try {
|
|
240
|
+
token = await o.auth?.();
|
|
241
|
+
if (cur !== link)
|
|
242
|
+
return; // 기다리는 동안 닫혔다
|
|
243
|
+
(o.transport === "sse" ? sse : ws)(link, token);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
return lost(link);
|
|
247
|
+
}
|
|
248
|
+
watch(link);
|
|
249
|
+
};
|
|
250
|
+
const ws = (link, token) => {
|
|
251
|
+
const sock = new WebSocket(o.url);
|
|
252
|
+
sock.onopen = () => sock.send(JSON.stringify({ t: "hello", channel, auth: token, ...(version >= 0 ? { version, epoch } : {}) }));
|
|
253
|
+
sock.onmessage = (e) => {
|
|
254
|
+
watch(link);
|
|
255
|
+
let m;
|
|
256
|
+
try {
|
|
257
|
+
m = JSON.parse(String(e.data));
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
receive(link, m);
|
|
263
|
+
};
|
|
264
|
+
sock.onclose = (e) => lost(link, e.code, e.reason);
|
|
265
|
+
link.send = (m) => void (sock.readyState === WebSocket.OPEN && sock.send(JSON.stringify(m)));
|
|
266
|
+
link.stop = () => {
|
|
267
|
+
sock.onopen = sock.onmessage = sock.onclose = null;
|
|
268
|
+
sock.close();
|
|
269
|
+
};
|
|
270
|
+
};
|
|
271
|
+
/** SSE — GET 의 헤더가 hello 다. 받기는 fetch 본문을 빈 줄로 나눠 읽고, 보내기는 POST 다 */
|
|
272
|
+
const sse = (link, token) => {
|
|
273
|
+
// POST 도 같은 신호로 — 연결을 버리면 날아가는 POST 도 함께 끊는다
|
|
274
|
+
const abort = new AbortController();
|
|
275
|
+
link.stop = () => abort.abort();
|
|
276
|
+
link.send = (m) => void post(link, m, abort.signal, { [HEADER.channel]: channel, [HEADER.connection]: link.connection ?? "" });
|
|
277
|
+
const headers = { [HEADER.channel]: channel, accept: "text/event-stream" };
|
|
278
|
+
if (token)
|
|
279
|
+
headers[HEADER.authorization] = `Bearer ${token}`;
|
|
280
|
+
if (version >= 0) {
|
|
281
|
+
headers[HEADER.epoch] = epoch;
|
|
282
|
+
headers[HEADER.lastEventId] = String(version);
|
|
283
|
+
}
|
|
284
|
+
void (async () => {
|
|
285
|
+
const res = await fetch(o.url, { headers, signal: abort.signal });
|
|
286
|
+
// 연결 때 401 · 403 은 「다시 오지 마라」와 같다
|
|
287
|
+
if (res.status === 401 || res.status === 403)
|
|
288
|
+
return lost(link, CLOSE.GO_AWAY, await res.text());
|
|
289
|
+
if (!res.ok || !res.body)
|
|
290
|
+
return lost(link);
|
|
291
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
292
|
+
// 망가진 프레임은 버린다 — 웹소켓과 같게 연결은 살린다
|
|
293
|
+
const feed = sseParser((data) => {
|
|
294
|
+
let m;
|
|
295
|
+
try {
|
|
296
|
+
m = JSON.parse(data);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
receive(link, m);
|
|
302
|
+
});
|
|
303
|
+
for (;;) {
|
|
304
|
+
const { value, done } = await reader.read();
|
|
305
|
+
if (done)
|
|
306
|
+
break;
|
|
307
|
+
// 스트림에서 받은 것만 idle 을 다시 센다 — POST 의 응답은 GET 이 살아 있다는 뜻이 아니다
|
|
308
|
+
watch(link);
|
|
309
|
+
feed(value);
|
|
310
|
+
}
|
|
311
|
+
lost(link);
|
|
312
|
+
})().catch(() => lost(link));
|
|
313
|
+
};
|
|
314
|
+
/** command 의 응답은 reply, ask 는 fate 의 배열 — 받은 길과 같게 receive 로 넘긴다 */
|
|
315
|
+
const post = async (link, m, signal, headers) => {
|
|
316
|
+
let res;
|
|
317
|
+
let body;
|
|
318
|
+
// POST 마다 auth() 를 다시 부른다 — 짧게 사는 토큰이 갱신되면 연 때의 것이 아니라 새 것을 싣는다
|
|
319
|
+
// auth() 가 던지면 토큰 없이 보낸다 — 홉이 거절하면 아래의 막힌 길로 간다
|
|
320
|
+
const token = await Promise.resolve()
|
|
321
|
+
.then(() => o.auth?.())
|
|
322
|
+
.catch(() => undefined);
|
|
323
|
+
if (token)
|
|
324
|
+
headers = { ...headers, [HEADER.authorization]: `Bearer ${token}` };
|
|
325
|
+
try {
|
|
326
|
+
res = await fetch(o.url, {
|
|
327
|
+
method: "POST",
|
|
328
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
329
|
+
body: JSON.stringify(m),
|
|
330
|
+
signal,
|
|
331
|
+
});
|
|
332
|
+
body = await res.text();
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return; // 닿았는지 모른다 — 스트림이 끊기면 다시 이어 ask 로 묻는다
|
|
336
|
+
}
|
|
337
|
+
if (res.status === 200) {
|
|
338
|
+
let out;
|
|
339
|
+
try {
|
|
340
|
+
out = JSON.parse(body);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
for (const x of [out].flat())
|
|
346
|
+
receive(link, x);
|
|
347
|
+
}
|
|
348
|
+
else if (m.t === "command")
|
|
349
|
+
// 400 · 401 · 403 · 404 · 500 — 홉이 명령을 돌리기 전에 막았다
|
|
350
|
+
receive(link, { t: "reply", id: m.id, ok: false, error: TEXT.commandFailed, version: 0 });
|
|
351
|
+
else if (m.t === "ask" && cur === link)
|
|
352
|
+
// 물을 길이 막혔다 — 제한 시간까지 「응답 지연」으로 기다리게 두지 않는다
|
|
353
|
+
for (const id of m.ids) {
|
|
354
|
+
const p = pending.get(id);
|
|
355
|
+
if (p && !p.wait)
|
|
356
|
+
fail(p, TEXT.unknown);
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
void open();
|
|
360
|
+
return {
|
|
361
|
+
view: () => shown,
|
|
362
|
+
subscribe(fn) {
|
|
363
|
+
listeners.add(fn);
|
|
364
|
+
return () => void listeners.delete(fn);
|
|
365
|
+
},
|
|
366
|
+
command(name, args, id = newId()) {
|
|
367
|
+
const had = pending.get(id);
|
|
368
|
+
if (had)
|
|
369
|
+
return had.promise;
|
|
370
|
+
const link = cur;
|
|
371
|
+
// 끊긴 동안 · welcome 전에는 보내지 않는다 — 쥐었다 다시 보내지 않는다
|
|
372
|
+
if (!link?.welcomed)
|
|
373
|
+
return Promise.reject(failure(TEXT.commandFailed, id));
|
|
374
|
+
const p = { id, name, args, link, timeout: o.commands?.[name]?.timeout ?? o.timeout ?? DEFAULTS.timeoutMs };
|
|
375
|
+
p.promise = new Promise((resolve, reject) => Object.assign(p, { resolve, reject }));
|
|
376
|
+
pending.set(id, p);
|
|
377
|
+
arm(p);
|
|
378
|
+
send(p);
|
|
379
|
+
return p.promise;
|
|
380
|
+
},
|
|
381
|
+
close() {
|
|
382
|
+
if (closed)
|
|
383
|
+
return;
|
|
384
|
+
closed = true;
|
|
385
|
+
clearTimeout(retry);
|
|
386
|
+
const link = cur;
|
|
387
|
+
cur = undefined;
|
|
388
|
+
if (link) {
|
|
389
|
+
clearTimeout(link.idle);
|
|
390
|
+
link.stop();
|
|
391
|
+
}
|
|
392
|
+
for (const p of [...pending.values()])
|
|
393
|
+
fail(p, TEXT.unknown);
|
|
394
|
+
listeners.clear();
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { StreamClient } from "./client.js";
|
|
2
|
+
type Options = {
|
|
3
|
+
pick?: readonly string[];
|
|
4
|
+
omit?: readonly string[];
|
|
5
|
+
};
|
|
6
|
+
export declare const STREAM_FIELDS: string[];
|
|
7
|
+
export declare const NO_FAILURE = "\uB2E4\uC2DC \uBCF4\uB0BC \uC2E4\uD328\uD55C \uBA85\uB839\uC774 \uC5C6\uB2E4";
|
|
8
|
+
export declare function makeStreamHook(client: StreamClient<unknown>, names: string[]): (options?: Options) => unknown;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// 연결의 화면 훅 — 정의 파일과 함께 서버 쪽에서도 평가되므로 "use client" 를 두지 않고 React 를 이름공간으로 가져온다
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
import { same, subscribeNone, useMutation } from "../resourceHook.js";
|
|
4
|
+
export const STREAM_FIELDS = ["data", "status", "isFetching", "error"];
|
|
5
|
+
export const NO_FAILURE = "다시 보낼 실패한 명령이 없다";
|
|
6
|
+
export function makeStreamHook(client, names) {
|
|
7
|
+
return function useStream(options) {
|
|
8
|
+
const shown = options?.pick ?? [...STREAM_FIELDS, ...names].filter((n) => !options?.omit?.includes(n));
|
|
9
|
+
const fields = shown.filter((n) => STREAM_FIELDS.includes(n));
|
|
10
|
+
// 고른 칸이 겉 한 겹으로 그대로면 앞 결과를 준다 — isFetching 만 바뀌어도 data 만 고른 화면은 다시 그리지 않는다
|
|
11
|
+
const last = React.useRef(null);
|
|
12
|
+
const snapshot = () => {
|
|
13
|
+
const v = client.view();
|
|
14
|
+
const prev = last.current;
|
|
15
|
+
if (prev && Object.keys(prev).length === fields.length && fields.every((f) => f in prev && same(prev[f], v[f])))
|
|
16
|
+
return prev;
|
|
17
|
+
const out = {};
|
|
18
|
+
for (const f of fields)
|
|
19
|
+
out[f] = v[f];
|
|
20
|
+
return (last.current = out);
|
|
21
|
+
};
|
|
22
|
+
const item = React.useSyncExternalStore(fields.length ? client.subscribe : subscribeNone, snapshot, snapshot);
|
|
23
|
+
// 명령마다 훅을 정해진 차례로 부른다 — 고르기와 상관없이 훅 순서가 같다
|
|
24
|
+
const views = {};
|
|
25
|
+
for (const name of names)
|
|
26
|
+
views[name] = useCommand(client, name);
|
|
27
|
+
if (!shown.some((n) => names.includes(n)))
|
|
28
|
+
return item;
|
|
29
|
+
const out = {};
|
|
30
|
+
for (const name of shown)
|
|
31
|
+
out[name] = name in item ? item[name] : views[name];
|
|
32
|
+
return out;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** 0.2 의 MutationView 에 retry 를 더한다 — 이 화면의 이 명령 칸에서 마지막 실패의 요청 id · 인자만 쥔다(스펙 §14 의 21) */
|
|
36
|
+
function useCommand(client, name) {
|
|
37
|
+
const failed = React.useRef(null);
|
|
38
|
+
/** 보낸 차례와 쥔 실패를 마지막으로 정한 차례 — 늦게 온 앞 부르기가 뒤 부르기의 결과를 덮지 않게 */
|
|
39
|
+
const order = React.useRef({ sent: 0, settled: 0 });
|
|
40
|
+
const send = (args, id) => {
|
|
41
|
+
const mine = ++order.current.sent;
|
|
42
|
+
const latest = () => mine > order.current.settled && ((order.current.settled = mine), true);
|
|
43
|
+
return client.command(name, args, id).then((data) => {
|
|
44
|
+
// 이 칸의 성공(mutate · mutateAsync · retry)이면 다시 보낼 실패가 없다
|
|
45
|
+
if (latest())
|
|
46
|
+
failed.current = null;
|
|
47
|
+
return data;
|
|
48
|
+
}, (e) => {
|
|
49
|
+
if (latest())
|
|
50
|
+
failed.current = { id: e.requestId, args };
|
|
51
|
+
throw e;
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
const view = useMutation((...args) => send(args), (run) => ({
|
|
55
|
+
// 같은 id 면 홉은 다시 돌리지 않고 쥔 답을 준다. 앱의 ok: false 는 같은 실패가 돌아온다 — 새로 부르려면 mutate
|
|
56
|
+
retry() {
|
|
57
|
+
const f = failed.current;
|
|
58
|
+
return f ? run(() => send(f.args, f.id)) : Promise.reject(new Error(NO_FAILURE));
|
|
59
|
+
},
|
|
60
|
+
}));
|
|
61
|
+
return {
|
|
62
|
+
...view,
|
|
63
|
+
// reset 은 쥔 실패도 지운다 — 도는 중이던 것의 결과도 다시 쥐지 않는다
|
|
64
|
+
reset() {
|
|
65
|
+
failed.current = null;
|
|
66
|
+
order.current.settled = order.current.sent;
|
|
67
|
+
view.reset();
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { DISPOSE, USE } from "../index.js";
|
|
2
|
+
import type { MutationView } from "../query.js";
|
|
3
|
+
import { type ClientOptions, type ClientView, type CommandError } from "./client.js";
|
|
4
|
+
export type { ClientView, CommandError };
|
|
5
|
+
type Fn = (...args: any[]) => any;
|
|
6
|
+
export interface StreamCommandView<F extends Fn> extends MutationView<F> {
|
|
7
|
+
/** 마지막으로 실패한 명령을 같은 요청 id · 인자로 다시 보낸다. 실패한 명령이 없으면 거절한다 */
|
|
8
|
+
retry(): Promise<Awaited<ReturnType<F>>>;
|
|
9
|
+
}
|
|
10
|
+
/** 화면이 꺼내는 칸 — 연결의 값(§8.3)과 명령마다의 칸 */
|
|
11
|
+
export type StreamView<V, Cmd> = ClientView<V> & {
|
|
12
|
+
[K in keyof Cmd]: StreamCommandView<Extract<Cmd[K], Fn>>;
|
|
13
|
+
};
|
|
14
|
+
type Name<V, Cmd> = keyof StreamView<V, Cmd> & string;
|
|
15
|
+
export type StreamUseOptions<V, Cmd> = {
|
|
16
|
+
pick: readonly Name<V, Cmd>[];
|
|
17
|
+
omit?: never;
|
|
18
|
+
} | {
|
|
19
|
+
omit: readonly Name<V, Cmd>[];
|
|
20
|
+
pick?: never;
|
|
21
|
+
} | undefined;
|
|
22
|
+
export type StreamUseResult<V, Cmd, O> = [O] extends [{
|
|
23
|
+
pick: readonly (infer N)[];
|
|
24
|
+
}] ? Pick<StreamView<V, Cmd>, N & keyof StreamView<V, Cmd>> : [O] extends [{
|
|
25
|
+
omit: readonly (infer N)[];
|
|
26
|
+
}] ? Omit<StreamView<V, Cmd>, N & keyof StreamView<V, Cmd>> : StreamView<V, Cmd>;
|
|
27
|
+
export interface StreamUse<V, Cmd> {
|
|
28
|
+
<O extends StreamUseOptions<V, Cmd>>(options?: O): StreamUseResult<V, Cmd, O>;
|
|
29
|
+
}
|
|
30
|
+
/** store 상태 — 화면은 useStore 로, store 끼리는 명령 함수로 부른다(실패하면 던진다) */
|
|
31
|
+
export type Stream<V, Cmd> = {
|
|
32
|
+
[USE]: StreamUse<V, Cmd>;
|
|
33
|
+
[DISPOSE](): void;
|
|
34
|
+
} & {
|
|
35
|
+
[K in keyof Cmd]: (...args: Parameters<Extract<Cmd[K], Fn>>) => Promise<Awaited<ReturnType<Extract<Cmd[K], Fn>>>>;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* 명령의 타입은 셋째 타입 인자로 적고, 이름과 제한 시간은 commands 에 적는다 — 타입은 런타임에 남지 않으므로
|
|
39
|
+
* 명령마다 commands 에 한 칸이 있어야 한다(없으면 타입 오류)
|
|
40
|
+
*/
|
|
41
|
+
export type StreamOptions<V, C, Cmd> = Omit<ClientOptions<V, C>, "commands"> & {
|
|
42
|
+
/** 기본 "browser" — window 가 없으면(서버에서 그릴 때) 열지 않는다. "always" 면 Node 에서도 연다 */
|
|
43
|
+
open?: "browser" | "always";
|
|
44
|
+
} & (keyof Cmd extends never ? {
|
|
45
|
+
commands?: {};
|
|
46
|
+
} : {
|
|
47
|
+
commands: {
|
|
48
|
+
[K in keyof Cmd]: {
|
|
49
|
+
timeout?: number;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
export declare function createStream<V, C = V, Cmd extends Record<keyof Cmd, Fn> = {}>(o: StreamOptions<V, C, Cmd>): Stream<V, Cmd>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// supa-store/stream — 서버와 이어진 연결을 store 상태로 꺼낸다(스펙 §6 · §8)
|
|
2
|
+
// 정의 파일은 서버에서도 평가되므로 "use client" 를 두지 않는다. 시험 전용(TIMING · sseParser)은 내보내지 않는다
|
|
3
|
+
import { DISPOSE, USE } from "../index.js";
|
|
4
|
+
import { connect } from "./client.js";
|
|
5
|
+
import { makeStreamHook } from "./hook.js";
|
|
6
|
+
import { TEXT } from "./protocol.js";
|
|
7
|
+
/** 상대 주소는 location 으로 푼다 — 웹소켓이면 http → ws, https → wss */
|
|
8
|
+
function absolute(url, transport) {
|
|
9
|
+
// URL.canParse 는 쓰지 않는다 — 그것이 없는 옛 브라우저에서도 돌게
|
|
10
|
+
try {
|
|
11
|
+
new URL(url);
|
|
12
|
+
return url;
|
|
13
|
+
}
|
|
14
|
+
catch { }
|
|
15
|
+
if (typeof location === "undefined" || !location)
|
|
16
|
+
throw new Error(`상대 주소를 풀 location 이 없다: ${url} — ws(s):// 또는 http(s):// 로 적는다`);
|
|
17
|
+
const u = new URL(url, location.href);
|
|
18
|
+
if (transport !== "sse")
|
|
19
|
+
u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
|
|
20
|
+
return u.href;
|
|
21
|
+
}
|
|
22
|
+
/** 서버에서 그릴 때의 연결 — 열지 않으므로 loading 그대로이고 명령은 실패한다 */
|
|
23
|
+
const IDLE_VIEW = { data: undefined, status: "loading", isFetching: true, error: null };
|
|
24
|
+
const idle = {
|
|
25
|
+
view: () => IDLE_VIEW,
|
|
26
|
+
subscribe: () => () => { },
|
|
27
|
+
command: (_name, _args, id = "") => Promise.reject(Object.assign(new Error(TEXT.commandFailed), { requestId: id })),
|
|
28
|
+
close() { },
|
|
29
|
+
};
|
|
30
|
+
export function createStream(o) {
|
|
31
|
+
const names = Object.keys(o.commands ?? {});
|
|
32
|
+
const client = typeof window === "undefined" && o.open !== "always"
|
|
33
|
+
? idle
|
|
34
|
+
: connect({ ...o, url: absolute(o.url, o.transport) });
|
|
35
|
+
const state = {
|
|
36
|
+
[USE]: makeStreamHook(client, names),
|
|
37
|
+
// 다시 짓기 직전 · Store.dispose 에서 — 앞 연결의 늦은 메시지는 닫힌 클라이언트가 버린다
|
|
38
|
+
[DISPOSE]: () => client.close(),
|
|
39
|
+
};
|
|
40
|
+
for (const name of names)
|
|
41
|
+
state[name] = (...args) => client.command(name, args);
|
|
42
|
+
return state;
|
|
43
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** 명령 · 요청의 결과 — 성공이면 result, 실패면 앱의 문구 */
|
|
2
|
+
export type Outcome = {
|
|
3
|
+
ok: true;
|
|
4
|
+
result: unknown;
|
|
5
|
+
} | {
|
|
6
|
+
ok: false;
|
|
7
|
+
error: string;
|
|
8
|
+
};
|
|
9
|
+
export type ServerMessage = {
|
|
10
|
+
t: "welcome";
|
|
11
|
+
epoch: string;
|
|
12
|
+
version: number;
|
|
13
|
+
connection: string;
|
|
14
|
+
} | {
|
|
15
|
+
t: "snapshot";
|
|
16
|
+
version: number;
|
|
17
|
+
value: unknown;
|
|
18
|
+
} | {
|
|
19
|
+
t: "change";
|
|
20
|
+
version: number;
|
|
21
|
+
change: unknown;
|
|
22
|
+
}
|
|
23
|
+
/** version 은 답할 때의 채널 버전 */
|
|
24
|
+
| ({
|
|
25
|
+
t: "reply";
|
|
26
|
+
id: string;
|
|
27
|
+
version: number;
|
|
28
|
+
} & Outcome) | ({
|
|
29
|
+
t: "fate";
|
|
30
|
+
id: string;
|
|
31
|
+
state: "done";
|
|
32
|
+
version: number;
|
|
33
|
+
} & Outcome) | {
|
|
34
|
+
t: "fate";
|
|
35
|
+
id: string;
|
|
36
|
+
state: "unknown-id" | "running";
|
|
37
|
+
} | {
|
|
38
|
+
t: "request";
|
|
39
|
+
id: string;
|
|
40
|
+
method: string;
|
|
41
|
+
params: unknown[];
|
|
42
|
+
} | {
|
|
43
|
+
t: "ping";
|
|
44
|
+
}
|
|
45
|
+
/** SSE 에서 서버가 일부러 닫을 때 — 웹소켓은 닫기 코드로 */
|
|
46
|
+
| {
|
|
47
|
+
t: "close";
|
|
48
|
+
code: number;
|
|
49
|
+
reason: string;
|
|
50
|
+
};
|
|
51
|
+
export type ClientMessage =
|
|
52
|
+
/** epoch · version 은 가진 것이 있을 때, auth 는 웹소켓일 때 */
|
|
53
|
+
{
|
|
54
|
+
t: "hello";
|
|
55
|
+
version?: number;
|
|
56
|
+
epoch?: string;
|
|
57
|
+
channel?: string;
|
|
58
|
+
auth?: string;
|
|
59
|
+
} | {
|
|
60
|
+
t: "command";
|
|
61
|
+
id: string;
|
|
62
|
+
name: string;
|
|
63
|
+
args: unknown[];
|
|
64
|
+
} | {
|
|
65
|
+
t: "ask";
|
|
66
|
+
ids: string[];
|
|
67
|
+
} | ({
|
|
68
|
+
t: "answer";
|
|
69
|
+
id: string;
|
|
70
|
+
} & Outcome) | {
|
|
71
|
+
t: "pong";
|
|
72
|
+
};
|
|
73
|
+
/** 4001 은 「다시 오지 마라」, 4000 은 「곧 다시 와라」 */
|
|
74
|
+
export declare const CLOSE: {
|
|
75
|
+
readonly GO_AWAY: 4001;
|
|
76
|
+
readonly COME_BACK: 4000;
|
|
77
|
+
};
|
|
78
|
+
export declare const TEXT: {
|
|
79
|
+
readonly reconnecting: "연결 끊김. 재시도 중..";
|
|
80
|
+
readonly commandFailed: "연결 끊김. 명령 실패";
|
|
81
|
+
readonly unknown: "연결 끊김. 알 수 없음";
|
|
82
|
+
readonly timeout: "응답 지연";
|
|
83
|
+
};
|
|
84
|
+
export declare const DEFAULTS: {
|
|
85
|
+
readonly historyCount: 1000;
|
|
86
|
+
readonly historyMs: 300000;
|
|
87
|
+
readonly pingMs: 25000;
|
|
88
|
+
readonly idleMs: 60000;
|
|
89
|
+
readonly helloMs: 10000;
|
|
90
|
+
readonly timeoutMs: 30000;
|
|
91
|
+
readonly backoffStartMs: 1000;
|
|
92
|
+
readonly backoffMaxMs: 30000;
|
|
93
|
+
readonly jitter: 0.2;
|
|
94
|
+
};
|
|
95
|
+
/** SSE 와 POST 가 싣는 헤더 — 이름은 소문자로 읽는다. 토큰은 Authorization 에만 싣는다(주소에 싣지 않는다) */
|
|
96
|
+
export declare const HEADER: {
|
|
97
|
+
/** POST 가 어느 스트림 연결의 것인지 — welcome.connection */
|
|
98
|
+
readonly connection: "x-supa-connection";
|
|
99
|
+
/** SSE 의 hello.channel */
|
|
100
|
+
readonly channel: "x-supa-channel";
|
|
101
|
+
/** SSE 의 hello.epoch — 버전은 Last-Event-ID 가 싣는다 */
|
|
102
|
+
readonly epoch: "x-supa-epoch";
|
|
103
|
+
readonly lastEventId: "last-event-id";
|
|
104
|
+
readonly authorization: "authorization";
|
|
105
|
+
};
|