@gjermundgaraba/clankermux 0.6.0 → 0.7.0

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.
@@ -30,10 +30,11 @@ export declare class Attachment {
30
30
  private cursor;
31
31
  private incarnation;
32
32
  private continuation;
33
- private pendingServer;
34
33
  session: Session | undefined;
35
34
  constructor(engine: Engine);
36
- openOn(welcome: Welcome): void;
35
+ /** Readies an `OPEN` on the connection `welcome` began: the cursor to
36
+ * resume from, when there is one to keep. */
37
+ open(welcome: Welcome): Resume | undefined;
37
38
  resume(): Resume | undefined;
38
39
  ended(): boolean;
39
40
  closed(): boolean;
@@ -10,21 +10,22 @@ function mustHoldUntilSnapshotEnd(held, type) {
10
10
  export class Attachment {
11
11
  engine;
12
12
  state = { kind: "opening" };
13
- cursor = { offset: 0, marker: 0 };
13
+ cursor = { incarnation: "", offset: 0, marker: 0 };
14
14
  incarnation = "";
15
15
  continuation = 0;
16
- pendingServer;
17
16
  session;
18
17
  constructor(engine) {
19
18
  this.engine = engine;
20
19
  }
21
- openOn(welcome) {
22
- this.pendingServer = { incarnation: welcome.incarnation, continuation: welcome.limits.continuation };
20
+ /** Readies an `OPEN` on the connection `welcome` began: the cursor to
21
+ * resume from, when there is one to keep. */
22
+ open(welcome) {
23
+ this.incarnation = welcome.incarnation;
24
+ this.continuation = welcome.limits.continuation;
25
+ return this.resume();
23
26
  }
24
27
  resume() {
25
- return this.state.kind === "streaming"
26
- ? { incarnation: this.incarnation, offset: this.cursor.offset, marker: this.cursor.marker }
27
- : undefined;
28
+ return this.state.kind === "streaming" ? { ...this.cursor } : undefined;
28
29
  }
29
30
  ended() {
30
31
  return this.state.kind === "ended";
@@ -68,16 +69,9 @@ export class Attachment {
68
69
  switch (type) {
69
70
  case FrameType.Attached: {
70
71
  const attached = this.json(frame);
71
- if (this.pendingServer) {
72
- this.incarnation = this.pendingServer.incarnation;
73
- this.continuation = this.pendingServer.continuation;
74
- this.pendingServer = undefined;
75
- }
76
- this.cursor = { offset: attached.offset, marker: attached.marker };
72
+ this.cursor = { incarnation: this.incarnation, offset: attached.offset, marker: attached.marker };
77
73
  this.session = attached.session;
78
- if (attached.mode === "snapshot") {
79
- if (attached.snapshot_bytes === undefined)
80
- throw ClientError.protocol("ATTACHED without snapshot_bytes");
74
+ if (attached.snapshot_bytes !== undefined) {
81
75
  this.discard();
82
76
  const decoder = new Decoder(this.engine, attached.snapshot_bytes);
83
77
  try {
@@ -1,6 +1,6 @@
1
1
  import { type Catalog, type Description, type ErrorCode, type ErrorMessage, type Event, type Frame, FrameType, type Hello, type Peer, type Welcome } from "../proto/index.ts";
2
2
  export interface Transport {
3
- send(bytes: Uint8Array): void;
3
+ send(bytes: Uint8Array<ArrayBuffer>): void;
4
4
  close(): void;
5
5
  onMessage: ((bytes: Uint8Array) => void) | undefined;
6
6
  onClose: (() => void) | undefined;
@@ -0,0 +1,143 @@
1
+ import { type FSM, type FSMSnapshot } from "xstate/fsm";
2
+ import type { ClosedReason, ErrorCode, ErrorMessage, Exit, Session } from "../proto/index.ts";
3
+ import type { Attachment } from "./attachment.ts";
4
+ import { type Connection } from "./connection.ts";
5
+ /** Why the link to the session ended. `closed`: the connection closed
6
+ * (not a `CLOSED` frame, which the worker does not wait for when it
7
+ * detaches); `removed`, `stopping` and `detached` (another client's
8
+ * `detach`): the server's `CLOSED`; `exited`:
9
+ * the session's program exited; `no_such_session` and `engine_mismatch`:
10
+ * an `OPEN` refused; `error`: any other error, the server's or the
11
+ * client's own. */
12
+ export type LinkEnd = "closed" | "removed" | "stopping" | "detached" | "exited" | "no_such_session" | "engine_mismatch" | "error";
13
+ /** A terminal's link to its session, through the client's connection and
14
+ * the terminal's attachment. */
15
+ export type Link =
16
+ /** Opening a connection; `attempt` counts from 1 and starts again once
17
+ * a server answers. */
18
+ {
19
+ state: "connecting";
20
+ attempt: number;
21
+ }
22
+ /** Connected, and showing `session` as `ATTACHED` described it (its
23
+ * `status` may be `restored` or `exited`), or attached to none. */
24
+ | {
25
+ state: "connected";
26
+ session: Session | undefined;
27
+ }
28
+ /** The link ended. `code` and `message` are the error's, when there is
29
+ * one, and `message` the reason a `detach` gave; `exit` is the
30
+ * program's, for `exited`. `retry`: the worker
31
+ * reconnects or attaches again by itself, so `connecting` or
32
+ * `connected` follows; otherwise nothing does until the page attaches. */
33
+ | {
34
+ state: "ended";
35
+ reason: LinkEnd;
36
+ code?: ErrorCode;
37
+ message?: string;
38
+ exit?: Exit;
39
+ retry: boolean;
40
+ };
41
+ export declare function endedWith(err: unknown, retry: boolean): Link;
42
+ export interface Open {
43
+ conn: Connection;
44
+ channel: number;
45
+ fresh: Attachment;
46
+ }
47
+ export interface Line {
48
+ session: string;
49
+ attachment: Attachment;
50
+ channel: number;
51
+ conn: Connection;
52
+ }
53
+ declare const CLEARED: {
54
+ gaveUp: undefined;
55
+ live: undefined;
56
+ session: undefined;
57
+ attachment: undefined;
58
+ channel: undefined;
59
+ conn: undefined;
60
+ described: undefined;
61
+ exit: undefined;
62
+ reason: undefined;
63
+ message: undefined;
64
+ ended: undefined;
65
+ };
66
+ type Only<T> = T & {
67
+ [K in Exclude<keyof typeof CLEARED, keyof T>]?: undefined;
68
+ };
69
+ interface Contexts {
70
+ none: Only<{
71
+ gaveUp: Link | undefined;
72
+ live: boolean;
73
+ }>;
74
+ waiting: Only<{
75
+ session: string;
76
+ attachment: Attachment | undefined;
77
+ }>;
78
+ opening: Only<Line>;
79
+ attached: Only<Line & {
80
+ described: Session | undefined;
81
+ }>;
82
+ exited: Only<Line & {
83
+ exit: Exit | undefined;
84
+ }>;
85
+ closed: Only<Line & {
86
+ reason: "stopping" | "closed";
87
+ message: string | undefined;
88
+ }>;
89
+ backoff: Only<{
90
+ session: string;
91
+ ended: Link;
92
+ }>;
93
+ disposed: Only<{}>;
94
+ }
95
+ interface Events {
96
+ "hub.live": {
97
+ open: Open;
98
+ };
99
+ "hub.down": {};
100
+ "page.attach": {
101
+ session: string;
102
+ open: Open | undefined;
103
+ };
104
+ "page.detach": {
105
+ live: boolean;
106
+ };
107
+ "page.unmount": {};
108
+ "frame.screen": {
109
+ session: Session | undefined;
110
+ };
111
+ "frame.resumed": {
112
+ session: Session | undefined;
113
+ };
114
+ "frame.exited": {
115
+ exit: Exit | undefined;
116
+ };
117
+ "frame.closed": {
118
+ reason: ClosedReason;
119
+ message: string | undefined;
120
+ };
121
+ "frame.error": {
122
+ error: ErrorMessage;
123
+ endsAttachment: boolean;
124
+ };
125
+ "attachment.threw": {
126
+ error: unknown;
127
+ };
128
+ "reopen.due": {
129
+ open: Open | undefined;
130
+ };
131
+ }
132
+ export type MountSnapshot = {
133
+ [K in keyof Contexts]: FSMSnapshot<Contexts[K], K>;
134
+ }[keyof Contexts];
135
+ export type MountEvent = {
136
+ [K in keyof Events]: {
137
+ type: K;
138
+ } & Events[K];
139
+ }[keyof Events];
140
+ export declare const mountMachine: FSM<{}, MountEvent, keyof Contexts, MountSnapshot, unknown>;
141
+ export declare function lineOf(snapshot: MountSnapshot): Line | undefined;
142
+ export declare function linkOf(snapshot: MountSnapshot): Link | undefined;
143
+ export {};
@@ -0,0 +1,205 @@
1
+ import { setup, types } from "xstate/fsm";
2
+ import { ClientError } from "./connection.js";
3
+ const UNRETRYABLE_OPEN_ERRORS = new Set(["no_such_session", "engine_mismatch", "invalid_request"]);
4
+ function linkEnd(code) {
5
+ return code === "no_such_session" || code === "engine_mismatch" ? code : "error";
6
+ }
7
+ export function endedWith(err, retry) {
8
+ const server = err instanceof ClientError ? err.server : undefined;
9
+ return server
10
+ ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
11
+ : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry };
12
+ }
13
+ function closedWith(reason, message) {
14
+ return { state: "ended", reason, ...(message !== undefined && { message }), retry: reason === "stopping" };
15
+ }
16
+ const CLEARED = {
17
+ gaveUp: undefined,
18
+ live: undefined,
19
+ session: undefined,
20
+ attachment: undefined,
21
+ channel: undefined,
22
+ conn: undefined,
23
+ described: undefined,
24
+ exit: undefined,
25
+ reason: undefined,
26
+ message: undefined,
27
+ ended: undefined,
28
+ };
29
+ const none = (gaveUp, live) => ({ ...CLEARED, gaveUp, live });
30
+ const waiting = (session, attachment) => ({ ...CLEARED, session, attachment });
31
+ const line = ({ session, attachment, channel, conn }) => ({ ...CLEARED, session, attachment, channel, conn });
32
+ const opening = (session, attachment, { conn, channel }) => line({ session, attachment, channel, conn });
33
+ const backoff = (session, ended) => ({ ...CLEARED, session, ended });
34
+ const attach = ({ event: { session, open } }) => open
35
+ ? { target: "opening", context: opening(session, open.fresh, open) }
36
+ : { target: "waiting", context: waiting(session, undefined) };
37
+ const detach = ({ event }) => ({ target: "none", context: none(undefined, event.live) });
38
+ const unmount = { target: "disposed", context: CLEARED };
39
+ const lost = ({ context }) => ({ target: "waiting", context: waiting(context.session, context.attachment) });
40
+ const screen = ({ context, event }) => ({
41
+ target: "attached",
42
+ context: { ...line(context), described: event.session },
43
+ });
44
+ const closed = ({ context, event: { reason, message } }) => reason === "removed" || reason === "detached"
45
+ ? { target: "none", context: none(closedWith(reason, message), true) }
46
+ : { target: "closed", context: { ...line(context), reason, message } };
47
+ const refused = ({ context, event }) => {
48
+ if (!event.endsAttachment)
49
+ return undefined;
50
+ const { code, message } = event.error;
51
+ const retry = !UNRETRYABLE_OPEN_ERRORS.has(code);
52
+ const ended = { state: "ended", reason: linkEnd(code), code, message, retry };
53
+ return retry
54
+ ? { target: "backoff", context: backoff(context.session, ended) }
55
+ : { target: "none", context: none(ended, true) };
56
+ };
57
+ const threw = ({ context, event }) => {
58
+ const desync = event.error instanceof ClientError && event.error.kind === "desync";
59
+ const ended = endedWith(event.error, desync);
60
+ return desync
61
+ ? { target: "backoff", context: backoff(context.session, ended) }
62
+ : { target: "none", context: none(ended, true) };
63
+ };
64
+ export const mountMachine = setup({
65
+ schemas: {
66
+ events: {
67
+ "hub.live": types(),
68
+ "hub.down": types(),
69
+ "page.attach": types(),
70
+ "page.detach": types(),
71
+ "page.unmount": types(),
72
+ "frame.screen": types(),
73
+ "frame.resumed": types(),
74
+ "frame.exited": types(),
75
+ "frame.closed": types(),
76
+ "frame.error": types(),
77
+ "attachment.threw": types(),
78
+ "reopen.due": types(),
79
+ },
80
+ },
81
+ states: {
82
+ none: { schemas: { context: types() } },
83
+ waiting: { schemas: { context: types() } },
84
+ opening: { schemas: { context: types() } },
85
+ attached: { schemas: { context: types() } },
86
+ exited: { schemas: { context: types() } },
87
+ closed: { schemas: { context: types() } },
88
+ backoff: { schemas: { context: types() } },
89
+ disposed: { schemas: { context: types() } },
90
+ },
91
+ }).createFSM({
92
+ initial: "none",
93
+ context: none(undefined, false),
94
+ states: {
95
+ none: {
96
+ on: {
97
+ "hub.live": { target: "none", context: none(undefined, true) },
98
+ "hub.down": { target: "none", context: none(undefined, false) },
99
+ "page.attach": attach,
100
+ "page.unmount": unmount,
101
+ },
102
+ },
103
+ waiting: {
104
+ on: {
105
+ "hub.live": ({ context, event: { open } }) => ({
106
+ target: "opening",
107
+ context: opening(context.session, context.attachment ?? open.fresh, open),
108
+ }),
109
+ "page.attach": attach,
110
+ "page.detach": detach,
111
+ "page.unmount": unmount,
112
+ },
113
+ },
114
+ opening: {
115
+ on: {
116
+ "frame.screen": screen,
117
+ "frame.resumed": screen,
118
+ "frame.closed": closed,
119
+ "frame.error": refused,
120
+ "attachment.threw": threw,
121
+ "hub.down": lost,
122
+ "page.attach": attach,
123
+ "page.detach": detach,
124
+ "page.unmount": unmount,
125
+ },
126
+ },
127
+ attached: {
128
+ on: {
129
+ "frame.screen": screen,
130
+ "frame.exited": ({ context, event: { exit } }) => ({ target: "exited", context: { ...line(context), exit } }),
131
+ "frame.closed": closed,
132
+ "frame.error": refused,
133
+ "attachment.threw": threw,
134
+ "hub.down": lost,
135
+ "page.attach": attach,
136
+ "page.detach": detach,
137
+ "page.unmount": unmount,
138
+ },
139
+ },
140
+ exited: {
141
+ on: {
142
+ "frame.screen": screen,
143
+ "frame.closed": closed,
144
+ "frame.error": refused,
145
+ "attachment.threw": threw,
146
+ "hub.down": lost,
147
+ "page.attach": attach,
148
+ "page.detach": detach,
149
+ "page.unmount": unmount,
150
+ },
151
+ },
152
+ closed: {
153
+ on: {
154
+ "hub.down": lost,
155
+ "page.attach": attach,
156
+ "page.detach": detach,
157
+ "page.unmount": unmount,
158
+ },
159
+ },
160
+ backoff: {
161
+ on: {
162
+ "reopen.due": ({ context, event: { open } }) => open
163
+ ? { target: "opening", context: opening(context.session, open.fresh, open) }
164
+ : { target: "waiting", context: waiting(context.session, undefined) },
165
+ "hub.live": ({ context, event: { open } }) => ({
166
+ target: "opening",
167
+ context: opening(context.session, open.fresh, open),
168
+ }),
169
+ "page.attach": attach,
170
+ "page.detach": detach,
171
+ "page.unmount": unmount,
172
+ },
173
+ },
174
+ disposed: {},
175
+ },
176
+ });
177
+ export function lineOf(snapshot) {
178
+ switch (snapshot.value) {
179
+ case "opening":
180
+ case "attached":
181
+ case "exited":
182
+ case "closed":
183
+ return snapshot.context;
184
+ default:
185
+ return undefined;
186
+ }
187
+ }
188
+ export function linkOf(snapshot) {
189
+ switch (snapshot.value) {
190
+ case "none":
191
+ return snapshot.context.gaveUp ?? (snapshot.context.live ? { state: "connected", session: undefined } : undefined);
192
+ case "attached":
193
+ return { state: "connected", session: snapshot.context.described };
194
+ case "exited": {
195
+ const { exit } = snapshot.context;
196
+ return { state: "ended", reason: "exited", ...(exit && { exit }), retry: false };
197
+ }
198
+ case "closed":
199
+ return closedWith(snapshot.context.reason, snapshot.context.message);
200
+ case "backoff":
201
+ return snapshot.context.ended;
202
+ default:
203
+ return undefined;
204
+ }
205
+ }
@@ -1,42 +1,8 @@
1
1
  import { type CellPoint, type PackedFrame, type KeyInput } from "../engine/index.ts";
2
- import { type ErrorCode, type ErrorMessage, type Event, type Exit, type Peer, type Profile, type Session, type Size } from "../proto/index.ts";
2
+ import { type ErrorMessage, type Event, type Peer, type Profile, type Session, type Size } from "../proto/index.ts";
3
3
  import { type ErrorKind } from "./connection.ts";
4
- /** Why the link to the session ended. `closed`: the connection closed
5
- * (not a `CLOSED` frame, which the worker does not wait for when it
6
- * detaches); `removed`, `stopping` and `detached` (another client's
7
- * `detach`): the server's `CLOSED`; `exited`:
8
- * the session's program exited; `no_such_session` and `engine_mismatch`:
9
- * an `OPEN` refused; `error`: any other error, the server's or the
10
- * client's own. */
11
- export type LinkEnd = "closed" | "removed" | "stopping" | "detached" | "exited" | "no_such_session" | "engine_mismatch" | "error";
12
- /** A terminal's link to its session, through the client's connection and
13
- * the terminal's attachment. */
14
- export type Link =
15
- /** Opening a connection; `attempt` counts from 1 and starts again once
16
- * a server answers. */
17
- {
18
- state: "connecting";
19
- attempt: number;
20
- }
21
- /** Connected, and showing `session` as `ATTACHED` described it (its
22
- * `status` may be `restored` or `exited`), or attached to none. */
23
- | {
24
- state: "connected";
25
- session: Session | undefined;
26
- }
27
- /** The link ended. `code` and `message` are the error's, when there is
28
- * one, and `message` the reason a `detach` gave; `exit` is the
29
- * program's, for `exited`. `retry`: the worker
30
- * reconnects or attaches again by itself, so `connecting` or
31
- * `connected` follows; otherwise nothing does until the page attaches. */
32
- | {
33
- state: "ended";
34
- reason: LinkEnd;
35
- code?: ErrorCode;
36
- message?: string;
37
- exit?: Exit;
38
- retry: boolean;
39
- };
4
+ import { type Link } from "./link.ts";
5
+ export type { Link, LinkEnd } from "./link.ts";
40
6
  /** A failed request, as it crosses to the page. */
41
7
  export interface Failure {
42
8
  kind: ErrorKind;
@@ -2,6 +2,7 @@ import { ENGINE, Engine, KeyEncoder, RenderState, SelectionGesture, } from "../e
2
2
  import { FrameType, } from "../proto/index.js";
3
3
  import { Attachment } from "./attachment.js";
4
4
  import { ClientError, Connection, hello } from "./connection.js";
5
+ import { endedWith, lineOf, linkOf, mountMachine, } from "./link.js";
5
6
  import { Osc52Scanner } from "./osc52.js";
6
7
  const SCROLL_KEYS = {
7
8
  PageUp: -1,
@@ -12,7 +13,6 @@ const SCROLL_KEYS = {
12
13
  const PAINT_COALESCE_MS = 16;
13
14
  const BACKOFF_MIN_MS = 250;
14
15
  const BACKOFF_MAX_MS = 5000;
15
- const UNRETRYABLE_OPEN_ERRORS = new Set(["no_such_session", "engine_mismatch", "invalid_request"]);
16
16
  const ACKABLE_ATTENTION_STATES = new Set(["done", "error"]);
17
17
  const ALTERNATE_SCROLL_MODE = 1007;
18
18
  const SEND_REQUEST_OVERHEAD_BYTES = 1024;
@@ -76,12 +76,6 @@ function failureOf(err) {
76
76
  ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
77
77
  : { kind: "protocol", message: err instanceof Error ? err.message : String(err) };
78
78
  }
79
- function endedWith(err, retry) {
80
- const server = err instanceof ClientError ? err.server : undefined;
81
- return server
82
- ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
83
- : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry };
84
- }
85
79
  class Hub {
86
80
  post;
87
81
  constructor(post) {
@@ -158,6 +152,8 @@ class Hub {
158
152
  if (this.conn !== conn)
159
153
  return;
160
154
  this.conn = undefined;
155
+ for (const mount of this.mounts.values())
156
+ mount.disconnected();
161
157
  if (err.kind === "server") {
162
158
  this.refuse(err);
163
159
  }
@@ -182,7 +178,7 @@ class Hub {
182
178
  this.statusText = "connected";
183
179
  this.post({ type: "connection", link: this.connectionLink });
184
180
  for (const mount of this.mounts.values())
185
- mount.connected();
181
+ mount.connected(conn);
186
182
  }
187
183
  async subscribe(conn) {
188
184
  const incarnation = conn.welcome.incarnation;
@@ -278,35 +274,30 @@ class Hub {
278
274
  const mount = new Mount(this, id, init);
279
275
  this.mounts.set(id, mount);
280
276
  mount.status(this.statusText);
281
- if (this.connectionLink.state === "ended")
282
- this.reattach(mount);
283
- else if (this.live())
284
- mount.connected();
285
- else
277
+ const conn = this.live();
278
+ if (conn)
279
+ mount.connected(conn);
280
+ else if (this.connectionLink.state !== "ended")
286
281
  mount.link(this.connectionLink);
282
+ this.reconnectIfEnded();
287
283
  }
288
284
  unmount(id) {
289
285
  this.mounts.get(id)?.dispose();
290
286
  this.mounts.delete(id);
291
287
  }
292
- reattach(mount) {
293
- if (this.connectionLink.state === "ended") {
294
- this.attempt = 0;
295
- void this.connect();
296
- }
297
- else {
298
- mount.open();
299
- }
288
+ reconnectIfEnded() {
289
+ if (this.connectionLink.state !== "ended")
290
+ return;
291
+ this.attempt = 0;
292
+ void this.connect();
300
293
  }
301
294
  }
302
295
  class Mount {
303
296
  hub;
304
297
  id;
305
- attachment;
306
- channel = 0;
307
- openOn;
298
+ snapshot = mountMachine.initialState;
299
+ reopenTimer;
308
300
  acking = false;
309
- session;
310
301
  viewport;
311
302
  profile;
312
303
  active;
@@ -325,12 +316,9 @@ class Mount {
325
316
  frameInFlight = false;
326
317
  fullNext = false;
327
318
  backoff = new Backoff();
328
- reopenTimer;
329
- disposed = false;
330
319
  constructor(hub, id, init) {
331
320
  this.hub = hub;
332
321
  this.id = id;
333
- this.session = init.session;
334
322
  this.viewport = init.viewport;
335
323
  this.profile = init.profile;
336
324
  this.active = init.active;
@@ -339,9 +327,17 @@ class Mount {
339
327
  this.ackOnFocus = init.ackOnFocus;
340
328
  this.render = new RenderState(hub.engine);
341
329
  this.gesture = new SelectionGesture(hub.engine);
330
+ if (init.session !== undefined)
331
+ this.step({ type: "page.attach", session: init.session, open: undefined });
332
+ }
333
+ get attachment() {
334
+ return this.snapshot.context.attachment;
335
+ }
336
+ get session() {
337
+ return this.snapshot.context.session;
342
338
  }
343
339
  post(message, options) {
344
- if (!this.disposed)
340
+ if (this.snapshot.value !== "disposed")
345
341
  this.hub.post(message, options);
346
342
  }
347
343
  link(link) {
@@ -350,33 +346,52 @@ class Mount {
350
346
  status(text) {
351
347
  this.post({ type: "status", mount: this.id, text });
352
348
  }
353
- connected() {
354
- if (this.session !== undefined) {
355
- this.open();
356
- }
357
- else {
358
- this.status("no session");
359
- this.link({ state: "connected", session: undefined });
360
- }
349
+ connected(conn) {
350
+ this.step({ type: "hub.live", open: this.offer(conn) });
351
+ }
352
+ disconnected() {
353
+ this.step({ type: "hub.down" });
354
+ }
355
+ offer(conn) {
356
+ return { conn, channel: this.hub.nextChannel(), fresh: new Attachment(this.hub.engine) };
361
357
  }
362
- open() {
358
+ offerIfLive() {
363
359
  const conn = this.hub.live();
364
- if (!conn || this.session === undefined || this.disposed || this.openOn === conn)
365
- return;
366
- if (!this.attachment)
367
- this.attachment = new Attachment(this.hub.engine);
368
- const attachment = this.attachment;
369
- attachment.openOn(conn.welcome);
370
- const channel = this.hub.nextChannel();
371
- this.channel = channel;
372
- this.openOn = conn;
373
- const resume = attachment.resume();
360
+ return conn && this.offer(conn);
361
+ }
362
+ step(event) {
363
+ const prev = this.snapshot;
364
+ const [next] = mountMachine.transition(prev, event);
365
+ if (next === prev)
366
+ return;
367
+ const { attachment } = prev.context;
368
+ if (attachment && attachment !== next.context.attachment)
369
+ this.close(attachment, lineOf(prev));
370
+ if (prev.value === "backoff")
371
+ clearTimeout(this.reopenTimer);
372
+ this.snapshot = next;
373
+ if (next.value === "opening")
374
+ this.open(next.context);
375
+ if (next.value === "backoff") {
376
+ this.reopenTimer = setTimeout(() => this.step({ type: "reopen.due", open: this.offerIfLive() }), this.backoff.next());
377
+ }
378
+ const link = linkOf(next);
379
+ if (!link)
380
+ return;
381
+ if (link.state === "connected" && link.session === undefined)
382
+ this.status("no session");
383
+ this.link(link);
384
+ }
385
+ open({ session, attachment, channel, conn }) {
386
+ const resume = attachment.open(conn.welcome);
374
387
  const open = {
375
- session: this.session,
388
+ session,
376
389
  ...(this.readOnly && { read_only: true }),
377
390
  ...(this.active && { viewport: this.viewport, profile: this.profile }),
378
391
  ...(resume && { resume }),
379
392
  };
393
+ if (this.active)
394
+ this.sizeTakenByOtherClient = false;
380
395
  conn.open(channel, open, (frame) => {
381
396
  if (this.attachment !== attachment)
382
397
  return;
@@ -386,35 +401,21 @@ class Mount {
386
401
  }
387
402
  catch (err) {
388
403
  this.status(String(err));
389
- const desync = err instanceof ClientError && err.kind === "desync";
390
- this.link(endedWith(err, desync));
391
- if (desync)
392
- this.reopen();
393
- else
394
- this.giveUp();
404
+ this.step({ type: "attachment.threw", error: err });
395
405
  return;
396
406
  }
397
407
  for (const action of actions)
398
408
  this.apply(action);
399
409
  });
400
410
  }
401
- attached(session) {
402
- this.link({ state: "connected", session });
403
- if (session?.status === "exited") {
404
- this.link({ state: "ended", reason: "exited", ...(session.exit && { exit: session.exit }), retry: false });
411
+ close(attachment, line) {
412
+ this.forgetSelection(attachment.term());
413
+ if (line) {
414
+ line.conn.release(line.channel);
415
+ if (!attachment.closed())
416
+ line.conn.send(FrameType.Close, line.channel, new Uint8Array());
405
417
  }
406
- }
407
- giveUp() {
408
- this.close();
409
- this.session = undefined;
410
- }
411
- reopen() {
412
- this.close();
413
- this.reopenTimer ??= setTimeout(() => {
414
- this.reopenTimer = undefined;
415
- if (this.session !== undefined && !this.attachment)
416
- this.open();
417
- }, this.backoff.next());
418
+ attachment.free();
418
419
  }
419
420
  apply(action) {
420
421
  switch (action.type) {
@@ -431,14 +432,16 @@ class Mount {
431
432
  ? `exited: ${describe(session.exit)}`
432
433
  : "attached";
433
434
  this.status(text);
434
- this.attached(session);
435
+ this.step({ type: "frame.screen", session });
436
+ if (session?.status === "exited")
437
+ this.step({ type: "frame.exited", exit: session.exit });
435
438
  if (session)
436
439
  this.changed(session);
437
440
  break;
438
441
  }
439
442
  case "resumed":
440
443
  this.status("resumed");
441
- this.link({ state: "connected", session: this.attachment?.session });
444
+ this.step({ type: "frame.resumed", session: this.attachment?.session });
442
445
  break;
443
446
  case "output":
444
447
  if (this.selected && !this.attachment?.term()?.selected)
@@ -460,7 +463,7 @@ class Mount {
460
463
  case "exited":
461
464
  this.paint();
462
465
  this.status(`exited: ${describe(action.exit)}`);
463
- this.link({ state: "ended", reason: "exited", exit: action.exit, retry: false });
466
+ this.step({ type: "frame.exited", exit: action.exit });
464
467
  break;
465
468
  case "gap":
466
469
  this.clipboard.reset();
@@ -469,28 +472,12 @@ class Mount {
469
472
  break;
470
473
  case "closed":
471
474
  this.status(`closed: ${action.reason}`);
472
- this.link({
473
- state: "ended",
474
- reason: action.reason,
475
- ...(action.message !== undefined && { message: action.message }),
476
- retry: action.reason === "stopping",
477
- });
478
- if (action.reason === "removed" || action.reason === "detached")
479
- this.giveUp();
475
+ this.step({ type: "frame.closed", reason: action.reason, message: action.message });
480
476
  break;
481
- case "error": {
477
+ case "error":
482
478
  this.status(`${action.error.code}: ${action.error.message}`);
483
- if (!this.attachment?.closed())
484
- break;
485
- const { code, message } = action.error;
486
- const retry = !UNRETRYABLE_OPEN_ERRORS.has(code);
487
- this.link({ state: "ended", reason: linkEnd(code), code, message, retry });
488
- if (retry)
489
- this.reopen();
490
- else
491
- this.giveUp();
479
+ this.step({ type: "frame.error", error: action.error, endsAttachment: this.attachment?.closed() === true });
492
480
  break;
493
- }
494
481
  }
495
482
  }
496
483
  applyProfile(term) {
@@ -534,7 +521,7 @@ class Mount {
534
521
  }
535
522
  this.paintPending = true;
536
523
  const term = this.attachment?.term();
537
- if (!term || this.disposed || !this.visible || this.frameInFlight)
524
+ if (!term || !this.visible || this.frameInFlight)
538
525
  return;
539
526
  if (this.fullNext) {
540
527
  this.render.free();
@@ -598,72 +585,57 @@ class Mount {
598
585
  if (this.selected)
599
586
  this.unselected();
600
587
  }
601
- close() {
602
- if (!this.attachment)
603
- return;
604
- this.forgetSelection(this.attachment.term());
605
- const conn = this.hub.conn;
606
- if (conn) {
607
- conn.release(this.channel);
608
- if (!this.attachment.closed())
609
- conn.send(FrameType.Close, this.channel, new Uint8Array());
610
- }
611
- this.attachment.free();
612
- this.attachment = undefined;
613
- this.openOn = undefined;
614
- }
615
588
  attach(session) {
616
- this.close();
589
+ this.step({ type: "page.attach", session, open: this.offerIfLive() });
617
590
  this.inputQueue.stopWaitingOnSendsUnderWay();
618
- this.session = session;
619
- this.hub.reattach(this);
591
+ this.hub.reconnectIfEnded();
620
592
  }
621
593
  detach() {
622
- const had = this.session !== undefined;
623
- this.giveUp();
594
+ this.step({ type: "page.detach", live: this.hub.live() !== undefined });
624
595
  this.inputQueue.stopWaitingOnSendsUnderWay();
625
- if (had && this.hub.conn) {
626
- this.status("no session");
627
- this.link({ state: "connected", session: undefined });
628
- }
629
596
  }
630
597
  dispose() {
631
- this.close();
632
- this.disposed = true;
598
+ this.step({ type: "page.unmount" });
633
599
  if (this.paintTimer !== undefined)
634
600
  clearTimeout(this.paintTimer);
635
- if (this.reopenTimer !== undefined)
636
- clearTimeout(this.reopenTimer);
637
601
  this.render.free();
638
602
  this.gesture.forget(undefined);
639
603
  }
640
604
  sendInput(bytes) {
641
- this.queueInput(bytes, async ({ conn, channel }) => {
642
- conn.send(FrameType.Input, channel, bytes);
643
- });
605
+ if (!this.typed(bytes))
606
+ return;
607
+ const line = lineOf(this.snapshot);
608
+ if (line)
609
+ this.deliver(line.conn, async () => line.conn.send(FrameType.Input, line.channel, bytes));
644
610
  }
645
611
  sendPaste(bytes) {
646
- this.queueInput(bytes, async ({ conn, session }) => {
612
+ if (!this.typed(bytes))
613
+ return;
614
+ const { conn } = this.hub;
615
+ const { session } = this;
616
+ if (!conn || session === undefined)
617
+ return;
618
+ this.deliver(conn, async () => {
647
619
  const chunk = pasteChunkSize(conn.welcome.limits);
648
620
  for (let at = 0; at < bytes.length; at += chunk) {
649
621
  await conn.call("send", { session, data: base64(bytes.subarray(at, at + chunk)) });
650
622
  }
651
623
  });
652
624
  }
653
- queueInput(bytes, deliver) {
654
- const conn = this.hub.conn;
655
- const attachment = this.attachment;
656
- const session = this.session;
657
- const channel = this.channel;
658
- if (bytes.length === 0 || this.readOnly || !conn || !attachment || attachment.ended() || session === undefined) {
659
- return;
660
- }
625
+ typed(bytes) {
626
+ const { attachment } = this;
627
+ if (bytes.length === 0 || this.readOnly || !attachment || attachment.ended())
628
+ return false;
661
629
  this.claim();
662
630
  this.backToLive();
663
631
  this.unselect();
632
+ return true;
633
+ }
634
+ deliver(conn, send) {
635
+ const { attachment } = this;
664
636
  this.inputQueue.enqueueUnlessDetached(() => this.attachment === attachment, async () => {
665
637
  try {
666
- await deliver({ conn, session, channel });
638
+ await send();
667
639
  }
668
640
  catch (err) {
669
641
  if (conn === this.hub.conn)
@@ -740,8 +712,8 @@ class Mount {
740
712
  this.viewport = size;
741
713
  this.profile = profile;
742
714
  this.active = active;
743
- const attachment = this.attachment;
744
- if (!this.hub.conn || !attachment || attachment.ended())
715
+ const { attachment } = this;
716
+ if (!attachment || attachment.ended())
745
717
  return;
746
718
  this.applyProfile(attachment.term());
747
719
  this.paint();
@@ -749,11 +721,15 @@ class Mount {
749
721
  this.report();
750
722
  }
751
723
  report() {
724
+ const line = lineOf(this.snapshot);
725
+ if (!line)
726
+ return;
752
727
  this.sizeTakenByOtherClient = false;
753
- this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
728
+ line.conn.sendJson(FrameType.Viewport, line.channel, { ...this.viewport, profile: this.profile });
754
729
  }
755
730
  claim() {
756
- if (this.sizeTakenByOtherClient && this.active && this.attachment && !this.attachment.ended())
731
+ const { attachment } = this;
732
+ if (this.sizeTakenByOtherClient && this.active && attachment && !attachment.ended())
757
733
  this.report();
758
734
  }
759
735
  focus(focused) {
@@ -780,9 +756,6 @@ class Mount {
780
756
  }, () => (this.acking = false));
781
757
  }
782
758
  }
783
- function linkEnd(code) {
784
- return code === "no_such_session" || code === "engine_mismatch" ? code : "error";
785
- }
786
759
  function describe(exit) {
787
760
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
788
761
  }
@@ -1,26 +1,5 @@
1
+ import { FrameType } from "./messages.ts";
1
2
  export declare const HEADER_LEN = 10;
2
- export declare const FrameType: {
3
- readonly Hello: 1;
4
- readonly Request: 2;
5
- readonly Open: 16;
6
- readonly Input: 17;
7
- readonly Viewport: 18;
8
- readonly Close: 19;
9
- readonly Welcome: 129;
10
- readonly Reply: 130;
11
- readonly Event: 131;
12
- readonly Error: 143;
13
- readonly Attached: 144;
14
- readonly Snapshot: 145;
15
- readonly SnapshotReady: 146;
16
- readonly SnapshotEnd: 147;
17
- readonly Output: 148;
18
- readonly Resized: 149;
19
- readonly Exited: 150;
20
- readonly Gap: 151;
21
- readonly Closed: 153;
22
- };
23
- export type FrameType = (typeof FrameType)[keyof typeof FrameType];
24
3
  export interface Header {
25
4
  type: FrameType;
26
5
  channel: number;
@@ -33,7 +12,7 @@ export declare class FrameError extends Error {
33
12
  }
34
13
  /** Parses a header, ignoring `flags`. */
35
14
  export declare function parseHeader(bytes: Uint8Array, maxFrame: number): Header;
36
- export declare function encodeFrame(type: FrameType, channel: number, payload: Uint8Array): Uint8Array;
15
+ export declare function encodeFrame(type: FrameType, channel: number, payload: Uint8Array): Uint8Array<ArrayBuffer>;
37
16
  export interface Frame {
38
17
  header: Header;
39
18
  payload: Uint8Array;
@@ -1,25 +1,5 @@
1
+ import { FrameType } from "./messages.js";
1
2
  export const HEADER_LEN = 10;
2
- export const FrameType = {
3
- Hello: 0x01,
4
- Request: 0x02,
5
- Open: 0x10,
6
- Input: 0x11,
7
- Viewport: 0x12,
8
- Close: 0x13,
9
- Welcome: 0x81,
10
- Reply: 0x82,
11
- Event: 0x83,
12
- Error: 0x8f,
13
- Attached: 0x90,
14
- Snapshot: 0x91,
15
- SnapshotReady: 0x92,
16
- SnapshotEnd: 0x93,
17
- Output: 0x94,
18
- Resized: 0x95,
19
- Exited: 0x96,
20
- Gap: 0x97,
21
- Closed: 0x99,
22
- };
23
3
  const KNOWN_TYPES = new Set(Object.values(FrameType));
24
4
  function isFrameType(byte) {
25
5
  return KNOWN_TYPES.has(byte);
@@ -1,4 +1,46 @@
1
- export declare const VERSION = 1;
1
+ export declare const VERSION = 2;
2
+ /** Each frame type's header byte. */
3
+ export declare const FrameType: {
4
+ /** Opens the connection: version, client and engine */
5
+ readonly Hello: 1;
6
+ /** A method call, answered by `REPLY` or `ERROR` with its `id` */
7
+ readonly Request: 2;
8
+ /** Attaches the channel to a session */
9
+ readonly Open: 16;
10
+ /** Bytes for the PTY */
11
+ readonly Input: 17;
12
+ /** The attachment's size and profile */
13
+ readonly Viewport: 18;
14
+ /** Detaches the channel */
15
+ readonly Close: 19;
16
+ /** Accepts the connection: the server's engine, incarnation and limits */
17
+ readonly Welcome: 129;
18
+ /** A method's result */
19
+ readonly Reply: 130;
20
+ /** A change, once subscribed */
21
+ readonly Event: 131;
22
+ /** A request's or an attachment's failure, or the connection's end */
23
+ readonly Error: 143;
24
+ /** The attachment's start: snapshot or resume */
25
+ readonly Attached: 144;
26
+ /** Snapshot bytes */
27
+ readonly Snapshot: 145;
28
+ /** The snapshot holds the screen; stream frames may follow */
29
+ readonly SnapshotReady: 146;
30
+ /** The last snapshot byte was sent */
31
+ readonly SnapshotEnd: 147;
32
+ /** `offset u64` and PTY bytes from that stream offset */
33
+ readonly Output: 148;
34
+ /** A size marker in the stream */
35
+ readonly Resized: 149;
36
+ /** The end of the stream */
37
+ readonly Exited: 150;
38
+ /** Bytes were not delivered; a new bootstrap follows */
39
+ readonly Gap: 151;
40
+ /** The attachment ended */
41
+ readonly Closed: 153;
42
+ };
43
+ export type FrameType = (typeof FrameType)[keyof typeof FrameType];
2
44
  /** Each method's params and result. */
3
45
  export interface Methods {
4
46
  /** Starts a session: a program on a new PTY. */
@@ -108,9 +150,7 @@ export interface AckParams {
108
150
  export interface Acked {
109
151
  record_ids: string[];
110
152
  }
111
- export type AttachMode = "snapshot" | "resume";
112
153
  export interface Attached {
113
- mode: AttachMode;
114
154
  /** Cursor offset the attachment continues from. */
115
155
  offset: number;
116
156
  /**
@@ -122,9 +162,9 @@ export interface Attached {
122
162
  rows: number;
123
163
  session: Session;
124
164
  /**
125
- * Required in mode `snapshot`, absent otherwise: the total length of the
126
- * snapshot that follows (the sum of the `SNAPSHOT` payloads), so a client can
127
- * size its buffer.
165
+ * Present when a snapshot follows, absent when the attachment resumes: the
166
+ * total length of the snapshot (the sum of the `SNAPSHOT` payloads, possibly
167
+ * 0), so a client can size its buffer.
128
168
  */
129
169
  snapshot_bytes?: number;
130
170
  }
@@ -459,13 +499,13 @@ export interface Gap {
459
499
  to: number;
460
500
  }
461
501
  export interface Hello {
462
- /** Always 1. */
502
+ /** Always 2. */
463
503
  version: number;
464
504
  /** Informational. */
465
505
  client: ClientPeer;
466
506
  /** Engine id; absent for control-only clients. */
467
507
  engine?: string;
468
- /** Capability ids; version 1 defines none. */
508
+ /** Capability ids; version 2 defines none. */
469
509
  capabilities?: string[];
470
510
  }
471
511
  export interface LabelParams {
@@ -876,7 +916,7 @@ export interface Waited {
876
916
  record?: StatusRecord;
877
917
  }
878
918
  export interface Welcome {
879
- /** Always 1. */
919
+ /** Always 2. */
880
920
  version: number;
881
921
  server: Peer;
882
922
  /** Engine id of the server. */
@@ -1,2 +1,43 @@
1
1
  // Generated from the catalog by `cargo xtask protocol`; do not edit.
2
- export const VERSION = 1;
2
+ export const VERSION = 2;
3
+ /** Each frame type's header byte. */
4
+ export const FrameType = {
5
+ /** Opens the connection: version, client and engine */
6
+ Hello: 0x01,
7
+ /** A method call, answered by `REPLY` or `ERROR` with its `id` */
8
+ Request: 0x02,
9
+ /** Attaches the channel to a session */
10
+ Open: 0x10,
11
+ /** Bytes for the PTY */
12
+ Input: 0x11,
13
+ /** The attachment's size and profile */
14
+ Viewport: 0x12,
15
+ /** Detaches the channel */
16
+ Close: 0x13,
17
+ /** Accepts the connection: the server's engine, incarnation and limits */
18
+ Welcome: 0x81,
19
+ /** A method's result */
20
+ Reply: 0x82,
21
+ /** A change, once subscribed */
22
+ Event: 0x83,
23
+ /** A request's or an attachment's failure, or the connection's end */
24
+ Error: 0x8f,
25
+ /** The attachment's start: snapshot or resume */
26
+ Attached: 0x90,
27
+ /** Snapshot bytes */
28
+ Snapshot: 0x91,
29
+ /** The snapshot holds the screen; stream frames may follow */
30
+ SnapshotReady: 0x92,
31
+ /** The last snapshot byte was sent */
32
+ SnapshotEnd: 0x93,
33
+ /** `offset u64` and PTY bytes from that stream offset */
34
+ Output: 0x94,
35
+ /** A size marker in the stream */
36
+ Resized: 0x95,
37
+ /** The end of the stream */
38
+ Exited: 0x96,
39
+ /** Bytes were not delivered; a new bootstrap follows */
40
+ Gap: 0x97,
41
+ /** The attachment ended */
42
+ Closed: 0x99,
43
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/clankermux",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,10 +35,13 @@
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  },
38
+ "dependencies": {
39
+ "xstate": "6.0.0-alpha.71"
40
+ },
38
41
  "devDependencies": {
39
42
  "@types/ws": "^8.18.0",
40
43
  "ajv": "^8.20.0",
41
- "ws": "^8.18.0"
44
+ "ws": "^8.22.2"
42
45
  },
43
46
  "scripts": {
44
47
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.worker.json",