Debian Codegraph @

pkg/lib/cockpit-upload-helper.ts

raw
1 /*
2 * Copyright (C) 2024 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from 'cockpit';
7
8 // These are the same values used by the bridge (in channel.py)
9 const BLOCK_SIZE = 16 << 10; // 16kiB
10 const FLOW_WINDOW = 2 << 20; // 2MiB
11
12 function debug(...args: unknown[]) {
13 if (window.debugging == 'all' || window.debugging?.includes('upload'))
14 console.debug('upload', ...args);
15 }
16
17 class UploadError extends Error {
18 name = 'UploadError';
19 }
20
21 class Waiter {
22 unblock = () => { };
23 block(): Promise<void> {
24 return new Promise(resolve => { this.unblock = resolve });
25 }
26 }
27
28 export async function upload(
29 destination: string,
30 contents: Blob,
31 progress?: (bytes_sent: number) => void,
32 signal?: AbortSignal,
33 options?: cockpit.JsonObject
34 ) {
35 let close_message = null as (cockpit.JsonObject | null);
36 let outstanding = 0; // for flow control
37 let delivered = 0; // for progress reporting
38
39 // This variable is the most important thing in this function. The main
40 // upload loop will do work for as long as it can, and then it .block()s on
41 // the waiter until something changes (ack, close, abort, etc). All of
42 // those things call .unblock() to resume the loop.
43 const event_waiter = new Waiter();
44
45 if (signal) {
46 signal.throwIfAborted(); // early exit
47 signal.addEventListener('abort', event_waiter.unblock);
48 }
49
50 const opts = {
51 payload: 'fsreplace1',
52 path: destination,
53 binary: true,
54 size: contents.size,
55 'send-acks': 'bytes',
56 ...options,
57 } as const;
58 debug('requesting channel', opts);
59 const channel = cockpit.channel(opts);
60 channel.addEventListener('control', (_ev, message) => {
61 debug('control', message);
62 if (message.command === 'ack') {
63 cockpit.assert(typeof message.bytes === 'number', 'bytes not a number');
64 delivered += message.bytes;
65 if (progress) {
66 debug('progress', delivered);
67 progress(delivered);
68 }
69 outstanding -= message.bytes;
70 debug('outstanding -- to', outstanding);
71 event_waiter.unblock();
72 }
73 });
74 channel.addEventListener('close', (_ev, message) => {
75 debug('close', message);
76 close_message = message;
77 event_waiter.unblock();
78 });
79
80 try {
81 debug('starting file send', contents);
82
83 /* We want to use the "bring your own buffer" (byob) API so that we can
84 * decide the size of the blocks to read from the file: this is needed
85 * for flow control reasons and also to respect internal limitations in
86 * cockpit-ws. "byob" is not available on WebKit, though:
87 *
88 * https://caniuse.com/mdn-api_readablestreambyobreader
89 *
90 * Check if the API is available, and fake it if not.
91 */
92 let read;
93 if (typeof ReadableStreamBYOBReader === 'function') {
94 const reader = contents.stream().getReader({ mode: 'byob' });
95 read = () => reader.read(new Uint8Array(BLOCK_SIZE));
96 } else {
97 // fallback code (no 'byob' available)
98 const reader = contents.stream().getReader();
99 let buffer: Uint8Array | null = null;
100 read = async () => {
101 // No buffered data? Try a read.
102 if (!buffer) {
103 const { done, value } = await reader.read();
104 if (done) {
105 return { done, value };
106 } else {
107 buffer = value;
108 }
109 }
110
111 // Return the buffered data: if length < size, return it all, else return a slice
112 if (buffer.length < BLOCK_SIZE) {
113 const value = buffer;
114 buffer = null;
115 return { done: false, value };
116 } else {
117 const value = buffer.slice(0, BLOCK_SIZE);
118 buffer = buffer.slice(BLOCK_SIZE);
119 return { done: false, value };
120 }
121 };
122 }
123
124 let eof = false;
125
126 // eslint-disable-next-line no-unmodified-loop-condition
127 while (!close_message) {
128 /* We do the following steps for as long as the channel is open:
129 * - if there is room to write more data, do that
130 * - otherwise, block on the waiter until something changes
131 * - in any case, check for cancellation, repeat
132 * The idea here is that each loop iteration will `await` one
133 * thing, and once it returns, we need to re-evaluate our state.
134 */
135 if (!eof && outstanding < FLOW_WINDOW) {
136 const { done, value } = await read();
137 if (done) {
138 debug('sending done');
139 channel.control({ command: 'done' });
140 eof = true;
141 } else {
142 debug('sending', value.length, 'bytes');
143 channel.send(value);
144 outstanding += value.length;
145 debug('outstanding ++ to', outstanding);
146 }
147 if (signal) {
148 signal.throwIfAborted();
149 }
150 } else {
151 debug('sleeping', outstanding, 'of', FLOW_WINDOW, 'eof', eof);
152 await event_waiter.block();
153 }
154 if (signal) {
155 signal.throwIfAborted();
156 }
157 }
158
159 if (close_message.problem) {
160 throw new UploadError(cockpit.message(close_message));
161 } else {
162 cockpit.assert(typeof close_message.tag === 'string', "tag missing on close message");
163 return close_message.tag;
164 }
165 } finally {
166 debug('finally');
167 channel.close(); // maybe we got aborted
168 }
169 }