Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 52 additions & 10 deletions src/p4d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { auth, refresh } from './auth'
import { Config } from './config'
import { registerInterruptCleanup } from './errors'
import { serviceEnvironment } from './service-environment'
import { DEFAULT_UPLOAD_TIMEOUT_MS, timeoutMillisecondsOrDefault } from './timeouts'
import { ProgressOutput, uploadProgress } from './upload-progress'
import { CLI_USER_AGENT } from './version'

import { readFileSync, statSync } from 'fs'
import type { ClientRequest } from 'http'
import { request } from 'https'
import { basename } from 'path'

Expand Down Expand Up @@ -47,6 +50,31 @@ export function legacyUploadTimeoutMs (): number {
// loopback server; production always uses the https request above.
export type LegacyTransport = typeof request

// Writing the body in slices lets each write callback report how much of it
// the socket has taken, which is what the progress line shows. Only one slice
// is in flight at a time, so Node never buffers more than a slice of it.
const UPLOAD_SLICE_BYTES = 64 * 1024

function writeBody (req: ClientRequest, body: Buffer, onWritten: (sent: number) => void): void {
let offset = 0
const writeNext = (): void => {
// A destroyed request has already settled through its 'error' event.
if (req.destroyed) return
if (offset >= body.length) {
req.end()
return
}
const end = Math.min(offset + UPLOAD_SLICE_BYTES, body.length)
req.write(body.subarray(offset, end), error => {
if (error != null) return
offset = end
onWritten(offset)
writeNext()
})
}
writeNext()
}

async function doit (
gameId: string,
filename: string,
Expand All @@ -55,7 +83,8 @@ async function doit (
makePublic: boolean,
disableImageCompression: boolean,
config: Config,
transport: LegacyTransport
transport: LegacyTransport,
progressOutput: ProgressOutput
): Promise<Response> {
return await new Promise<Response>((resolve, reject) => {
if (config.access_token === undefined) {
Expand Down Expand Up @@ -96,6 +125,10 @@ async function doit (
const settle = (action: () => void): void => {
if (settled) return
settled = true
// End the progress line so what the caller prints next starts on its
// own row, even when the answer arrives before the body is sent.
unregisterProgressInterrupt()
progress.finish()
action()
}
const req = transport({
Expand Down Expand Up @@ -139,8 +172,16 @@ async function doit (
: new LegacyUploadError(`Could not reach the Poki upload service: ${error.message}`, 'network')))
})

req.write(buffer, 'binary')
req.end()
// Created only once the request exists: a request that throws while it
// is being built must not leave a half-drawn progress line behind.
const progress = uploadProgress(buffer.length, progressOutput)
Comment thread
ErikSom marked this conversation as resolved.
Resolved
// An interrupt exits without settling, and its error document would
// otherwise continue the unfinished progress line in the terminal.
const unregisterProgressInterrupt = registerInterruptCleanup(progress.finish)
writeBody(req, buffer, sent => {
progress.update(sent)
if (sent === buffer.length) progress.finish()
})
})
}

Expand Down Expand Up @@ -169,26 +210,27 @@ async function uploadToP4D (
notes: string | undefined,
makePublic: boolean,
disableImageCompression: boolean,
transport: LegacyTransport
transport: LegacyTransport,
progressOutput: ProgressOutput
): Promise<P4dData> {
let config = await auth(false, console.log)
let response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport)
let response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport, progressOutput)

if (response.statusCode === 401 && config.access_type !== 'Token') {
try {
config = await refresh(config, console.log)
} catch (e) {
config = await auth(true, console.log)
}
response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport)
response = await doit(gameId, filename, name, notes, makePublic, disableImageCompression, config, transport, progressOutput)
}

return finalizeP4dResponse(response)
}

// Keep the original six-argument entry point and its human presentation
// compatible for the deprecated default upload workflow. The seventh parameter
// exists for tests only and keeps that call shape intact.
export async function postToP4D (gameId: string, filename: string, name: string, notes: string | undefined, makePublic: boolean, disableImageCompression: boolean, transport: LegacyTransport = request): Promise<P4dData> {
return await uploadToP4D(gameId, filename, name, notes, makePublic, disableImageCompression, transport)
// compatible for the deprecated default upload workflow. The trailing
// parameters exist for tests only and keep that call shape intact.
export async function postToP4D (gameId: string, filename: string, name: string, notes: string | undefined, makePublic: boolean, disableImageCompression: boolean, transport: LegacyTransport = request, progressOutput: ProgressOutput = process.stdout): Promise<P4dData> {
return await uploadToP4D(gameId, filename, name, notes, makePublic, disableImageCompression, transport, progressOutput)
}
89 changes: 89 additions & 0 deletions src/upload-progress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// A live progress line for the deprecated human upload. It renders only when
// the output is a terminal: piped, captured, and CI output never receives it,
// so the documented upload output stays byte-identical for every pipeline that
// reads it.

export interface ProgressOutput {
isTTY?: boolean
columns?: number
write: (text: string) => unknown
}

export interface UploadProgress {
update: (sent: number) => void
finish: () => void
}

const RENDER_INTERVAL_MS = 100
const MIN_BAR_WIDTH = 10
const MAX_BAR_WIDTH = 30
const DEFAULT_COLUMNS = 80

const units = ['B', 'KB', 'MB', 'GB', 'TB']

export function formatBytes (bytes: number): string {
let value = bytes
let unit = 0
// Round before choosing the unit so 999,999 bytes reads 1.0 MB, not 1000.0 KB.
while (unit < units.length - 1 && (unit === 0 ? Math.round(value) : Math.round(value * 10) / 10) >= 1000) {
value /= 1000
unit++
}
return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${units[unit]}`
}

export function uploadProgressLine (sent: number, total: number, elapsedMs: number, columns = DEFAULT_COLUMNS): string {
const fraction = total > 0 ? Math.min(1, Math.max(0, sent / total)) : 1
const percent = `${Math.floor(fraction * 100)}%`.padStart(4)
const rate = elapsedMs > 0 && sent > 0 ? ` ${formatBytes(sent / elapsedMs * 1000)}/s` : ''
const bytes = `${formatBytes(sent)} / ${formatBytes(total)}`
// Every line stays at least one column short of the terminal width. A line
// that wraps puts the carriage return on its last row, so each redraw would
// leave the start of the previous one behind. Narrow terminals shed the
// rate, then the byte counts, then the bar, keeping the percentage.
for (const text of [`${percent} ${bytes}${rate}`, `${percent} ${bytes}`, percent]) {
const room = columns - text.length - 4
if (room < MIN_BAR_WIDTH) continue
const width = Math.min(MAX_BAR_WIDTH, room)
const filled = Math.round(fraction * width)
return `[${'#'.repeat(filled)}${'-'.repeat(width - filled)}] ${text}`
}
if (percent.length < columns) return percent
return percent.trim().slice(0, Math.max(0, columns - 1))
}

export function uploadProgress (total: number, output: ProgressOutput, now: () => number = Date.now): UploadProgress {
if (output.isTTY !== true) return { update: () => {}, finish: () => {} }

const started = now()
let sent = 0
let renderedSent = -1
let renderedAt = -Infinity
let finished = false

const render = (): void => {
renderedAt = now()
renderedSent = sent
// \r returns to the line start and ESC[K clears what a longer previous
// line left behind. libuv translates both for Windows consoles.
output.write(`\r${uploadProgressLine(sent, total, renderedAt - started, output.columns)}\x1b[K`)
}

render()

return {
update: bytes => {
if (finished) return
sent = bytes
if (sent >= total || now() - renderedAt >= RENDER_INTERVAL_MS) render()
},
// Idempotent: the body completing and the response settling both end the
// line, and whichever comes first must leave later output on a fresh row.
finish: () => {
if (finished) return
finished = true
if (renderedSent !== sent) render()
output.write('\n')
}
}
}
Loading
Loading