2022-12-06 12:34:08 +01:00
|
|
|
/** SD-UI Backend control and classes.
|
|
|
|
*/
|
2023-04-27 19:56:56 +02:00
|
|
|
;(function() {
|
|
|
|
"use strict"
|
2022-12-06 12:34:08 +01:00
|
|
|
const RETRY_DELAY_IF_BUFFER_IS_EMPTY = 1000 // ms
|
|
|
|
const RETRY_DELAY_IF_SERVER_IS_BUSY = 30 * 1000 // ms, status_code 503, already a task running
|
|
|
|
const RETRY_DELAY_ON_ERROR = 4000 // ms
|
|
|
|
const TASK_STATE_SERVER_UPDATE_DELAY = 1500 // ms
|
|
|
|
const SERVER_STATE_VALIDITY_DURATION = 90 * 1000 // ms - 90 seconds to allow ping to timeout more than once before killing tasks.
|
|
|
|
const HEALTH_PING_INTERVAL = 5000 // ms
|
|
|
|
const IDLE_COOLDOWN = 2500 // ms
|
2022-12-22 10:52:25 +01:00
|
|
|
const CONCURRENT_TASK_INTERVAL = 100 // ms
|
2022-12-06 12:34:08 +01:00
|
|
|
|
2022-12-11 02:31:23 +01:00
|
|
|
/** Connects to an endpoint and resumes connection after reaching end of stream until all data is received.
|
|
|
|
* Allows closing the connection while the server buffers more data.
|
2022-12-06 12:34:08 +01:00
|
|
|
*/
|
|
|
|
class ChunkedStreamReader {
|
2023-04-27 19:56:56 +02:00
|
|
|
#bufferedString = "" // Data received waiting to be read.
|
2022-12-06 12:34:08 +01:00
|
|
|
#url
|
|
|
|
#fetchOptions
|
|
|
|
#response
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
constructor(url, initialContent = "", options = {}) {
|
|
|
|
if (typeof url !== "string" && !(url instanceof String)) {
|
|
|
|
throw new Error("url is not a string.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof initialContent !== "undefined" && typeof initialContent !== "string") {
|
|
|
|
throw new Error("initialContent is not a string.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this.#bufferedString = initialContent
|
|
|
|
this.#url = url
|
2023-04-27 19:56:56 +02:00
|
|
|
this.#fetchOptions = Object.assign(
|
|
|
|
{
|
|
|
|
headers: {
|
2023-04-28 12:20:44 +02:00
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
2023-04-27 19:56:56 +02:00
|
|
|
},
|
|
|
|
options
|
|
|
|
)
|
2022-12-06 12:34:08 +01:00
|
|
|
this.onNext = undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
get url() {
|
|
|
|
if (this.#response.redirected) {
|
|
|
|
return this.#response.url
|
|
|
|
}
|
|
|
|
return this.#url
|
|
|
|
}
|
|
|
|
get bufferedString() {
|
|
|
|
return this.#bufferedString
|
|
|
|
}
|
|
|
|
get status() {
|
|
|
|
this.#response?.status
|
|
|
|
}
|
|
|
|
get statusText() {
|
|
|
|
this.#response?.statusText
|
|
|
|
}
|
|
|
|
|
|
|
|
parse(value) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof value === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if (!isArrayOrTypedArray(value)) {
|
|
|
|
return [value]
|
|
|
|
}
|
|
|
|
if (value.length === 0) {
|
|
|
|
return value
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this.textDecoder === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this.textDecoder = new TextDecoder()
|
|
|
|
}
|
|
|
|
return [this.textDecoder.decode(value)]
|
|
|
|
}
|
|
|
|
onComplete(value) {
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
onError(response) {
|
|
|
|
throw new Error(response.statusText)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
onNext({ value, done }, response) {
|
|
|
|
return { value, done }
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async *[Symbol.asyncIterator]() {
|
|
|
|
return this.open()
|
|
|
|
}
|
|
|
|
async *open() {
|
|
|
|
let value = undefined
|
|
|
|
let done = undefined
|
|
|
|
do {
|
|
|
|
if (this.#response) {
|
|
|
|
await asyncDelay(RETRY_DELAY_IF_BUFFER_IS_EMPTY)
|
|
|
|
}
|
|
|
|
this.#response = await fetch(this.#url, this.#fetchOptions)
|
|
|
|
if (!this.#response.ok) {
|
|
|
|
if (this.#response.status === 425) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// Request status indicate failure
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Stream %o stopped unexpectedly.", this.#response)
|
2022-12-06 12:34:08 +01:00
|
|
|
value = await Promise.resolve(this.onError(this.#response))
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof value === "boolean" && value) {
|
2022-12-06 12:34:08 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
const reader = this.#response.body.getReader()
|
|
|
|
done = false
|
|
|
|
do {
|
|
|
|
const readState = await reader.read()
|
|
|
|
value = this.parse(readState.value)
|
|
|
|
if (value) {
|
2023-04-27 19:56:56 +02:00
|
|
|
for (let sVal of value) {
|
|
|
|
;({ value: sVal, done } = await Promise.resolve(
|
|
|
|
this.onNext({ value: sVal, done: readState.done })
|
|
|
|
))
|
2022-12-06 12:34:08 +01:00
|
|
|
yield sVal
|
|
|
|
if (done) {
|
|
|
|
return this.onComplete(sVal)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (done) {
|
|
|
|
return
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (value && !done)
|
2022-12-06 12:34:08 +01:00
|
|
|
} while (!done && (this.#response.ok || this.#response.status === 425))
|
|
|
|
}
|
|
|
|
*readStreamAsJSON(jsonStr, throwOnError) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof jsonStr !== "string") {
|
|
|
|
throw new Error("jsonStr is not a string.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
do {
|
|
|
|
if (this.#bufferedString.length > 0) {
|
|
|
|
// Append new data when required
|
|
|
|
if (jsonStr.length > 0) {
|
|
|
|
jsonStr = this.#bufferedString + jsonStr
|
|
|
|
} else {
|
|
|
|
jsonStr = this.#bufferedString
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
this.#bufferedString = ""
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (!jsonStr) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Find next delimiter
|
2023-04-27 19:56:56 +02:00
|
|
|
let lastChunkIdx = jsonStr.indexOf("}{")
|
2022-12-06 12:34:08 +01:00
|
|
|
if (lastChunkIdx >= 0) {
|
|
|
|
this.#bufferedString = jsonStr.substring(0, lastChunkIdx + 1)
|
|
|
|
jsonStr = jsonStr.substring(lastChunkIdx + 1)
|
|
|
|
} else {
|
|
|
|
this.#bufferedString = jsonStr
|
2023-04-27 19:56:56 +02:00
|
|
|
jsonStr = ""
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (this.#bufferedString.length <= 0) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// hack for a middleman buffering all the streaming updates, and unleashing them on the poor browser in one shot.
|
|
|
|
// this results in having to parse JSON like {"step": 1}{"step": 2}{"step": 3}{"ste...
|
|
|
|
// which is obviously invalid and can happen at any point while rendering.
|
|
|
|
// So we need to extract only the next {} section
|
2023-04-27 19:56:56 +02:00
|
|
|
try {
|
|
|
|
// Try to parse
|
2022-12-06 12:34:08 +01:00
|
|
|
const jsonObj = JSON.parse(this.#bufferedString)
|
|
|
|
this.#bufferedString = jsonStr
|
2023-04-27 19:56:56 +02:00
|
|
|
jsonStr = ""
|
2022-12-06 12:34:08 +01:00
|
|
|
yield jsonObj
|
|
|
|
} catch (e) {
|
|
|
|
if (throwOnError) {
|
|
|
|
console.error(`Parsing: "${this.#bufferedString}", Buffer: "${jsonStr}"`)
|
|
|
|
}
|
|
|
|
this.#bufferedString += jsonStr
|
|
|
|
if (e instanceof SyntaxError && !throwOnError) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
throw e
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (this.#bufferedString.length > 0 && this.#bufferedString.indexOf("}") >= 0)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
const EVENT_IDLE = "idle"
|
|
|
|
const EVENT_STATUS_CHANGED = "statusChange"
|
|
|
|
const EVENT_UNHANDLED_REJECTION = "unhandledRejection"
|
|
|
|
const EVENT_TASK_QUEUED = "taskQueued"
|
|
|
|
const EVENT_TASK_START = "taskStart"
|
|
|
|
const EVENT_TASK_END = "taskEnd"
|
|
|
|
const EVENT_TASK_ERROR = "task_error"
|
2023-05-28 00:50:23 +02:00
|
|
|
const EVENT_PING = "ping"
|
2023-04-27 19:56:56 +02:00
|
|
|
const EVENT_UNEXPECTED_RESPONSE = "unexpectedResponse"
|
2022-12-06 12:34:08 +01:00
|
|
|
const EVENTS_TYPES = [
|
|
|
|
EVENT_IDLE,
|
|
|
|
EVENT_STATUS_CHANGED,
|
|
|
|
EVENT_UNHANDLED_REJECTION,
|
|
|
|
|
|
|
|
EVENT_TASK_QUEUED,
|
|
|
|
EVENT_TASK_START,
|
|
|
|
EVENT_TASK_END,
|
|
|
|
EVENT_TASK_ERROR,
|
2023-05-28 00:50:23 +02:00
|
|
|
EVENT_PING,
|
2022-12-06 12:34:08 +01:00
|
|
|
|
2023-04-28 12:20:44 +02:00
|
|
|
EVENT_UNEXPECTED_RESPONSE,
|
2022-12-06 12:34:08 +01:00
|
|
|
]
|
|
|
|
Object.freeze(EVENTS_TYPES)
|
|
|
|
const eventSource = new GenericEventSource(EVENTS_TYPES)
|
|
|
|
|
|
|
|
function setServerStatus(msgType, msg) {
|
2023-04-27 19:56:56 +02:00
|
|
|
return eventSource.fireEvent(EVENT_STATUS_CHANGED, { type: msgType, message: msg })
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const ServerStates = {
|
2023-04-27 19:56:56 +02:00
|
|
|
init: "Init",
|
|
|
|
loadingModel: "LoadingModel",
|
|
|
|
online: "Online",
|
|
|
|
rendering: "Rendering",
|
2023-04-28 12:20:44 +02:00
|
|
|
unavailable: "Unavailable",
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
Object.freeze(ServerStates)
|
|
|
|
|
|
|
|
let sessionId = Date.now()
|
2023-04-27 19:56:56 +02:00
|
|
|
let serverState = { status: ServerStates.unavailable, time: Date.now() }
|
2022-12-06 12:34:08 +01:00
|
|
|
|
|
|
|
async function healthCheck() {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (Date.now() < serverState.time + HEALTH_PING_INTERVAL / 2 && isServerAvailable()) {
|
2022-12-06 12:34:08 +01:00
|
|
|
// Ping confirmed online less than half of HEALTH_PING_INTERVAL ago.
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("WARNING! SERVER_STATE_VALIDITY_DURATION has elapsed since the last Ping completed.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
try {
|
|
|
|
let res = undefined
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof sessionId !== "undefined") {
|
|
|
|
res = await fetch("/ping?session_id=" + sessionId)
|
2022-12-06 12:34:08 +01:00
|
|
|
} else {
|
2023-04-27 19:56:56 +02:00
|
|
|
res = await fetch("/ping")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
serverState = await res.json()
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof serverState !== "object" || typeof serverState.status !== "string") {
|
2022-12-06 12:34:08 +01:00
|
|
|
console.error(`Server reply didn't contain a state value.`)
|
2023-04-27 19:56:56 +02:00
|
|
|
serverState = { status: ServerStates.unavailable, time: Date.now() }
|
|
|
|
setServerStatus("error", "offline")
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
2023-05-28 00:50:23 +02:00
|
|
|
|
2022-12-06 12:34:08 +01:00
|
|
|
// Set status
|
2023-04-27 19:56:56 +02:00
|
|
|
switch (serverState.status) {
|
2022-12-06 12:34:08 +01:00
|
|
|
case ServerStates.init:
|
|
|
|
// Wait for init to complete before updating status.
|
|
|
|
break
|
|
|
|
case ServerStates.online:
|
2023-04-27 19:56:56 +02:00
|
|
|
setServerStatus("online", "ready")
|
2022-12-06 12:34:08 +01:00
|
|
|
break
|
|
|
|
case ServerStates.loadingModel:
|
2023-04-27 19:56:56 +02:00
|
|
|
setServerStatus("busy", "loading..")
|
2022-12-06 12:34:08 +01:00
|
|
|
break
|
|
|
|
case ServerStates.rendering:
|
2023-04-27 19:56:56 +02:00
|
|
|
setServerStatus("busy", "rendering..")
|
2022-12-06 12:34:08 +01:00
|
|
|
break
|
2023-04-27 19:56:56 +02:00
|
|
|
default:
|
|
|
|
// Unavailable
|
|
|
|
console.error("Ping received an unexpected server status. Status: %s", serverState.status)
|
|
|
|
setServerStatus("error", serverState.status.toLowerCase())
|
2022-12-06 12:34:08 +01:00
|
|
|
break
|
|
|
|
}
|
|
|
|
serverState.time = Date.now()
|
2023-05-28 00:50:23 +02:00
|
|
|
await eventSource.fireEvent(EVENT_PING, serverState)
|
2022-12-06 12:34:08 +01:00
|
|
|
return true
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e)
|
2023-04-27 19:56:56 +02:00
|
|
|
serverState = { status: ServerStates.unavailable, time: Date.now() }
|
|
|
|
setServerStatus("error", "offline")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
function isServerAvailable() {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof serverState !== "object") {
|
|
|
|
console.error("serverState not set to a value. Connection to server could be lost...")
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("SERVER_STATE_VALIDITY_DURATION elapsed. Connection to server could be lost...")
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
switch (serverState.status) {
|
|
|
|
case ServerStates.loadingModel:
|
|
|
|
case ServerStates.rendering:
|
|
|
|
case ServerStates.online:
|
|
|
|
return true
|
|
|
|
default:
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Unexpected server status. Server could be unavailable... Status: %s", serverState.status)
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function waitUntil(isReadyFn, delay, timeout) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof delay === "number") {
|
2022-12-06 12:34:08 +01:00
|
|
|
const msDelay = delay
|
|
|
|
delay = () => asyncDelay(msDelay)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof delay !== "function") {
|
|
|
|
throw new Error("delay is not a number or a function.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof timeout !== "undefined" && typeof timeout !== "number") {
|
|
|
|
throw new Error("timeout is not a number.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof timeout === "undefined" || timeout < 0) {
|
2022-12-06 12:34:08 +01:00
|
|
|
timeout = Number.MAX_SAFE_INTEGER
|
|
|
|
}
|
|
|
|
timeout = Date.now() + timeout
|
2023-04-27 19:56:56 +02:00
|
|
|
while (
|
|
|
|
timeout > Date.now() &&
|
|
|
|
Date.now() < serverState.time + SERVER_STATE_VALIDITY_DURATION &&
|
|
|
|
!Boolean(await Promise.resolve(isReadyFn()))
|
2022-12-06 12:34:08 +01:00
|
|
|
) {
|
|
|
|
await delay()
|
2023-04-27 19:56:56 +02:00
|
|
|
if (!isServerAvailable()) {
|
|
|
|
// Can fail if ping got frozen/suspended...
|
|
|
|
if ((await healthCheck()) && isServerAvailable()) {
|
|
|
|
// Force a recheck of server status before failure...
|
2022-12-06 12:34:08 +01:00
|
|
|
continue // Continue waiting if last healthCheck confirmed the server is still alive.
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("Connection with server lost.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Date.now() >= serverState.time + SERVER_STATE_VALIDITY_DURATION) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("SERVER_STATE_VALIDITY_DURATION elapsed. Released waitUntil on stale server state.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const TaskStatus = {
|
2023-04-27 19:56:56 +02:00
|
|
|
init: "init",
|
|
|
|
pending: "pending", // Queued locally, not yet posted to server
|
|
|
|
waiting: "waiting", // Waiting to run on server
|
|
|
|
processing: "processing",
|
|
|
|
stopped: "stopped",
|
|
|
|
completed: "completed",
|
2023-04-28 12:20:44 +02:00
|
|
|
failed: "failed",
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
Object.freeze(TaskStatus)
|
|
|
|
|
|
|
|
const TASK_STATUS_ORDER = [
|
|
|
|
TaskStatus.init,
|
|
|
|
TaskStatus.pending,
|
|
|
|
TaskStatus.waiting,
|
2023-04-28 12:20:44 +02:00
|
|
|
TaskStatus.processing,
|
2022-12-06 12:34:08 +01:00
|
|
|
//Don't add status that are final.
|
|
|
|
]
|
|
|
|
|
|
|
|
const task_queue = new Map()
|
|
|
|
const concurrent_generators = new Map()
|
|
|
|
const weak_results = new WeakMap()
|
|
|
|
|
|
|
|
class Task {
|
|
|
|
// Private properties...
|
|
|
|
_reqBody = {} // request body of this task.
|
|
|
|
#reader = undefined
|
|
|
|
#status = TaskStatus.init
|
|
|
|
#id = undefined
|
|
|
|
#exception = undefined
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
constructor(options = {}) {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody = Object.assign({}, options)
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this._reqBody.session_id === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody.session_id = sessionId
|
2023-04-27 19:56:56 +02:00
|
|
|
} else if (
|
|
|
|
this._reqBody.session_id !== SD.sessionId &&
|
|
|
|
String(this._reqBody.session_id) !== String(SD.sessionId)
|
|
|
|
) {
|
|
|
|
throw new Error("Use SD.sessionId to set the request session_id.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this._reqBody.session_id = String(this._reqBody.session_id)
|
|
|
|
}
|
|
|
|
|
|
|
|
get id() {
|
|
|
|
return this.#id
|
|
|
|
}
|
|
|
|
_setId(id) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this.#id !== "undefined") {
|
|
|
|
throw new Error("The task ID can only be set once.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this.#id = id
|
|
|
|
}
|
|
|
|
|
|
|
|
get exception() {
|
|
|
|
return this.#exception
|
|
|
|
}
|
|
|
|
async abort(exception) {
|
|
|
|
if (this.isCompleted || this.isStopped || this.hasFailed) {
|
|
|
|
return
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof exception !== "undefined") {
|
|
|
|
if (typeof exception === "string") {
|
2022-12-06 12:34:08 +01:00
|
|
|
exception = new Error(exception)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof exception !== "object") {
|
|
|
|
throw new Error("exception is not an object.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (!(exception instanceof Error)) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("exception is not an Error or a string.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
const res = await fetch("/image/stop?task=" + this.id)
|
2022-12-06 12:34:08 +01:00
|
|
|
if (!res.ok) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.log("Stop response:", res)
|
2022-12-06 12:34:08 +01:00
|
|
|
throw new Error(res.statusText)
|
|
|
|
}
|
|
|
|
task_queue.delete(this)
|
|
|
|
this.#exception = exception
|
2023-04-27 19:56:56 +02:00
|
|
|
this.#status = exception ? TaskStatus.failed : TaskStatus.stopped
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
get reqBody() {
|
|
|
|
if (this.#status === TaskStatus.init) {
|
|
|
|
return this._reqBody
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Task reqBody cannot be changed after the init state.")
|
2022-12-06 12:34:08 +01:00
|
|
|
return Object.assign({}, this._reqBody)
|
|
|
|
}
|
|
|
|
|
|
|
|
get isPending() {
|
|
|
|
return TASK_STATUS_ORDER.indexOf(this.#status) >= 0
|
|
|
|
}
|
|
|
|
get isCompleted() {
|
|
|
|
return this.#status === TaskStatus.completed
|
|
|
|
}
|
|
|
|
get hasFailed() {
|
|
|
|
return this.#status === TaskStatus.failed
|
|
|
|
}
|
|
|
|
get isStopped() {
|
|
|
|
return this.#status === TaskStatus.stopped
|
|
|
|
}
|
|
|
|
get status() {
|
|
|
|
return this.#status
|
|
|
|
}
|
|
|
|
_setStatus(status) {
|
|
|
|
if (status === this.#status) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const currentIdx = TASK_STATUS_ORDER.indexOf(this.#status)
|
|
|
|
if (currentIdx < 0) {
|
|
|
|
throw Error(`The task status ${this.#status} is final and can't be changed.`)
|
|
|
|
}
|
|
|
|
const newIdx = TASK_STATUS_ORDER.indexOf(status)
|
|
|
|
if (newIdx >= 0 && newIdx < currentIdx) {
|
|
|
|
throw Error(`The task status ${status} can't replace ${this.#status}.`)
|
|
|
|
}
|
|
|
|
this.#status = status
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Send current task to server.
|
|
|
|
* @param {*} [timeout=-1] Optional timeout value in ms
|
|
|
|
* @returns the response from the render request.
|
|
|
|
* @memberof Task
|
|
|
|
*/
|
2023-04-27 19:56:56 +02:00
|
|
|
async post(url, timeout = -1) {
|
|
|
|
if (this.status !== TaskStatus.init && this.status !== TaskStatus.pending) {
|
2022-12-06 12:34:08 +01:00
|
|
|
throw new Error(`Task status ${this.status} is not valid for post.`)
|
|
|
|
}
|
|
|
|
this._setStatus(TaskStatus.pending)
|
|
|
|
Object.freeze(this._reqBody)
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
const abortSignal = timeout >= 0 ? AbortSignal.timeout(timeout) : undefined
|
2022-12-06 12:34:08 +01:00
|
|
|
let res = undefined
|
|
|
|
try {
|
|
|
|
this.checkReqBody()
|
|
|
|
do {
|
|
|
|
abortSignal?.throwIfAborted()
|
|
|
|
res = await fetch(url, {
|
2023-04-27 19:56:56 +02:00
|
|
|
method: "POST",
|
2022-12-06 12:34:08 +01:00
|
|
|
headers: {
|
2023-04-28 12:20:44 +02:00
|
|
|
"Content-Type": "application/json",
|
2022-12-06 12:34:08 +01:00
|
|
|
},
|
|
|
|
body: JSON.stringify(this._reqBody),
|
2023-04-28 12:20:44 +02:00
|
|
|
signal: abortSignal,
|
2022-12-06 12:34:08 +01:00
|
|
|
})
|
|
|
|
// status_code 503, already a task running.
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (res.status === 503 && (await asyncDelay(RETRY_DELAY_IF_SERVER_IS_BUSY)))
|
2022-12-06 12:34:08 +01:00
|
|
|
} catch (err) {
|
|
|
|
this.abort(err)
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
if (!res.ok) {
|
|
|
|
const err = new Error(`Unexpected response HTTP${res.status}. Details: ${res.statusText}`)
|
|
|
|
this.abort(err)
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
return await res.json()
|
|
|
|
}
|
|
|
|
|
|
|
|
static getReader(url) {
|
|
|
|
const reader = new ChunkedStreamReader(url)
|
|
|
|
const parseToString = reader.parse
|
|
|
|
reader.parse = function(value) {
|
|
|
|
value = parseToString.call(this, value)
|
|
|
|
if (!value || value.length <= 0) {
|
|
|
|
return
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
return reader.readStreamAsJSON(value.join(""))
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
reader.onNext = function({ done, value }) {
|
2022-12-06 12:34:08 +01:00
|
|
|
// By default is completed when the return value has a status defined.
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof value === "object" && "status" in value) {
|
2022-12-06 12:34:08 +01:00
|
|
|
done = true
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
return { done, value }
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
return reader
|
|
|
|
}
|
|
|
|
_setReader(reader) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this.#reader !== "undefined") {
|
|
|
|
throw new Error("The task reader can only be set once.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this.#reader = reader
|
|
|
|
}
|
|
|
|
get reader() {
|
|
|
|
if (this.#reader) {
|
|
|
|
return this.#reader
|
|
|
|
}
|
|
|
|
if (!this.streamUrl) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("The task has no stream Url defined.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this.#reader = Task.getReader(this.streamUrl)
|
|
|
|
const task = this
|
|
|
|
const onNext = this.#reader.onNext
|
2023-04-27 19:56:56 +02:00
|
|
|
this.#reader.onNext = function({ done, value }) {
|
|
|
|
if (value && typeof value === "object") {
|
|
|
|
if (
|
|
|
|
task.status === TaskStatus.init ||
|
|
|
|
task.status === TaskStatus.pending ||
|
|
|
|
task.status === TaskStatus.waiting
|
2022-12-06 12:34:08 +01:00
|
|
|
) {
|
|
|
|
task._setStatus(TaskStatus.processing)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ("step" in value && "total_steps" in value) {
|
2022-12-06 12:34:08 +01:00
|
|
|
task.step = value.step
|
|
|
|
task.total_steps = value.total_steps
|
|
|
|
}
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
return onNext.call(this, { done, value })
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
this.#reader.onComplete = function(value) {
|
|
|
|
task.result = value
|
|
|
|
if (task.isPending) {
|
|
|
|
task._setStatus(TaskStatus.completed)
|
|
|
|
}
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
this.#reader.onError = function(response) {
|
|
|
|
const err = new Error(response.statusText)
|
|
|
|
task.abort(err)
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
return this.#reader
|
|
|
|
}
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
async waitUntil({ timeout = -1, callback, status, signal }) {
|
2022-12-06 12:34:08 +01:00
|
|
|
const currentIdx = TASK_STATUS_ORDER.indexOf(this.#status)
|
|
|
|
if (currentIdx <= 0) {
|
|
|
|
return false
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
const stIdx = status ? TASK_STATUS_ORDER.indexOf(status) : currentIdx + 1
|
2022-12-06 12:34:08 +01:00
|
|
|
if (stIdx >= 0 && stIdx <= currentIdx) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if (stIdx < 0 && currentIdx < 0) {
|
|
|
|
return this.#status === (status || TaskStatus.completed)
|
|
|
|
}
|
|
|
|
if (signal?.aborted) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
const task = this
|
2023-04-27 19:56:56 +02:00
|
|
|
switch (this.#status) {
|
2022-12-06 12:34:08 +01:00
|
|
|
case TaskStatus.pending:
|
|
|
|
case TaskStatus.waiting:
|
|
|
|
// Wait for server status to include this task.
|
2022-12-08 06:42:46 +01:00
|
|
|
await waitUntil(
|
|
|
|
async () => {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (
|
|
|
|
task.#id &&
|
|
|
|
typeof serverState.tasks === "object" &&
|
|
|
|
Object.keys(serverState.tasks).includes(String(task.#id))
|
|
|
|
) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
TASK_STATE_SERVER_UPDATE_DELAY,
|
2023-04-27 19:56:56 +02:00
|
|
|
timeout
|
2022-12-06 12:34:08 +01:00
|
|
|
)
|
2023-04-27 19:56:56 +02:00
|
|
|
if (
|
|
|
|
this.#id &&
|
|
|
|
typeof serverState.tasks === "object" &&
|
|
|
|
Object.keys(serverState.tasks).includes(String(task.#id))
|
|
|
|
) {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._setStatus(TaskStatus.waiting)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ((await Promise.resolve(callback?.call(this))) || signal?.aborted) {
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if (stIdx >= 0 && stIdx <= TASK_STATUS_ORDER.indexOf(TaskStatus.waiting)) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
// Wait for task to start on server.
|
2022-12-08 06:42:46 +01:00
|
|
|
await waitUntil(
|
|
|
|
async () => {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (
|
|
|
|
typeof serverState.tasks !== "object" ||
|
|
|
|
serverState.tasks[String(task.#id)] !== "pending"
|
|
|
|
) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
TASK_STATE_SERVER_UPDATE_DELAY,
|
2023-04-27 19:56:56 +02:00
|
|
|
timeout
|
2022-12-06 12:34:08 +01:00
|
|
|
)
|
2023-04-27 19:56:56 +02:00
|
|
|
const state =
|
|
|
|
typeof serverState.tasks === "object" ? serverState.tasks[String(task.#id)] : undefined
|
|
|
|
if (state === "running" || state === "buffer" || state === "completed") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._setStatus(TaskStatus.processing)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) {
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if (stIdx >= 0 && stIdx <= TASK_STATUS_ORDER.indexOf(TaskStatus.processing)) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
case TaskStatus.processing:
|
2022-12-08 06:42:46 +01:00
|
|
|
await waitUntil(
|
|
|
|
async () => {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (
|
|
|
|
typeof serverState.tasks !== "object" ||
|
|
|
|
serverState.tasks[String(task.#id)] !== "running"
|
|
|
|
) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ((await Promise.resolve(callback?.call(task))) || signal?.aborted) {
|
2022-12-08 06:42:46 +01:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
TASK_STATE_SERVER_UPDATE_DELAY,
|
2023-04-27 19:56:56 +02:00
|
|
|
timeout
|
2022-12-06 12:34:08 +01:00
|
|
|
)
|
|
|
|
await Promise.resolve(callback?.call(this))
|
|
|
|
default:
|
|
|
|
return this.#status === (status || TaskStatus.completed)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async enqueue(promiseGenerator, ...args) {
|
|
|
|
if (this.status !== TaskStatus.init) {
|
|
|
|
throw new Error(`Task is in an invalid status ${this.status} to add to queue.`)
|
|
|
|
}
|
|
|
|
this._setStatus(TaskStatus.pending)
|
|
|
|
task_queue.set(this, promiseGenerator)
|
2023-04-27 19:56:56 +02:00
|
|
|
await eventSource.fireEvent(EVENT_TASK_QUEUED, { task: this })
|
2022-12-06 12:34:08 +01:00
|
|
|
await Task.enqueue(promiseGenerator, ...args)
|
2023-04-27 19:56:56 +02:00
|
|
|
await this.waitUntil({ status: TaskStatus.completed })
|
2022-12-06 12:34:08 +01:00
|
|
|
if (this.exception) {
|
|
|
|
throw this.exception
|
|
|
|
}
|
|
|
|
return this.result
|
|
|
|
}
|
|
|
|
static async enqueue(promiseGenerator, ...args) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof promiseGenerator === "undefined") {
|
|
|
|
throw new Error("To enqueue a concurrent task, a *Promise Generator is needed but undefined was found.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
//if (Symbol.asyncIterator in result || Symbol.iterator in result) {
|
2023-04-27 19:56:56 +02:00
|
|
|
//concurrent_generators.set(result, Promise.resolve(args))
|
|
|
|
if (typeof promiseGenerator === "function") {
|
|
|
|
concurrent_generators.set(asGenerator({ callback: promiseGenerator }), Promise.resolve(args))
|
2022-12-06 12:34:08 +01:00
|
|
|
} else {
|
|
|
|
concurrent_generators.set(promiseGenerator, Promise.resolve(args))
|
|
|
|
}
|
|
|
|
await waitUntil(() => !concurrent_generators.has(promiseGenerator), CONCURRENT_TASK_INTERVAL)
|
|
|
|
return weak_results.get(promiseGenerator)
|
|
|
|
}
|
|
|
|
static enqueueNew(task, classCtor, progressCallback) {
|
|
|
|
if (task.status !== TaskStatus.init) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("Task has an invalid status to add to queue.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (!(task instanceof classCtor)) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("Task is not a instance of classCtor.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
let promiseGenerator = undefined
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof progressCallback === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
promiseGenerator = classCtor.start(task)
|
2023-04-27 19:56:56 +02:00
|
|
|
} else if (typeof progressCallback === "function") {
|
2022-12-06 12:34:08 +01:00
|
|
|
promiseGenerator = classCtor.start(task, progressCallback)
|
|
|
|
} else {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error("progressCallback is not a function.")
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
return Task.prototype.enqueue.call(task, promiseGenerator)
|
|
|
|
}
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
static async run(promiseGenerator, { callback, signal, timeout = -1 } = {}) {
|
2022-12-06 12:34:08 +01:00
|
|
|
let value = undefined
|
|
|
|
let done = undefined
|
|
|
|
if (timeout < 0) {
|
|
|
|
timeout = Number.MAX_SAFE_INTEGER
|
|
|
|
}
|
|
|
|
timeout = Date.now() + timeout
|
|
|
|
do {
|
2023-04-27 19:56:56 +02:00
|
|
|
;({ value, done } = await Promise.resolve(promiseGenerator.next(value)))
|
2022-12-06 12:34:08 +01:00
|
|
|
if (value instanceof Promise) {
|
|
|
|
value = await value
|
|
|
|
}
|
|
|
|
if (callback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
;({ value, done } = await Promise.resolve(callback.call(promiseGenerator, { value, done })))
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (value instanceof Promise) {
|
|
|
|
value = await value
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (!done && !signal?.aborted && timeout > Date.now())
|
2022-12-06 12:34:08 +01:00
|
|
|
return value
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
static async *asGenerator({ callback, generator, signal, timeout = -1 } = {}) {
|
2022-12-06 12:34:08 +01:00
|
|
|
let value = undefined
|
|
|
|
let done = undefined
|
|
|
|
if (timeout < 0) {
|
|
|
|
timeout = Number.MAX_SAFE_INTEGER
|
|
|
|
}
|
|
|
|
timeout = Date.now() + timeout
|
|
|
|
do {
|
2023-04-27 19:56:56 +02:00
|
|
|
;({ value, done } = await Promise.resolve(generator.next(value)))
|
2022-12-06 12:34:08 +01:00
|
|
|
if (value instanceof Promise) {
|
|
|
|
value = await value
|
|
|
|
}
|
|
|
|
if (callback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
;({ value, done } = await Promise.resolve(callback.call(generator, { value, done })))
|
2022-12-06 12:34:08 +01:00
|
|
|
if (value instanceof Promise) {
|
|
|
|
value = await value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
value = yield value
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (!done && !signal?.aborted && timeout > Date.now())
|
2022-12-06 12:34:08 +01:00
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const TASK_REQUIRED = {
|
2023-04-27 19:56:56 +02:00
|
|
|
session_id: "string",
|
|
|
|
prompt: "string",
|
|
|
|
negative_prompt: "string",
|
|
|
|
width: "number",
|
|
|
|
height: "number",
|
|
|
|
seed: "number",
|
2022-12-06 12:34:08 +01:00
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
sampler_name: "string",
|
|
|
|
use_stable_diffusion_model: "string",
|
2023-05-18 13:55:45 +02:00
|
|
|
clip_skip: "boolean",
|
2023-04-27 19:56:56 +02:00
|
|
|
num_inference_steps: "number",
|
|
|
|
guidance_scale: "number",
|
2022-12-06 12:34:08 +01:00
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
num_outputs: "number",
|
|
|
|
stream_progress_updates: "boolean",
|
|
|
|
stream_image_progress: "boolean",
|
|
|
|
show_only_filtered_image: "boolean",
|
|
|
|
output_format: "string",
|
2023-04-28 12:20:44 +02:00
|
|
|
output_quality: "number",
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
const TASK_DEFAULTS = {
|
2023-04-27 19:56:56 +02:00
|
|
|
sampler_name: "plms",
|
|
|
|
use_stable_diffusion_model: "sd-v1-4",
|
2023-05-18 13:55:45 +02:00
|
|
|
clip_skip: false,
|
2023-04-27 19:56:56 +02:00
|
|
|
num_inference_steps: 50,
|
|
|
|
guidance_scale: 7.5,
|
|
|
|
negative_prompt: "",
|
2022-12-06 12:34:08 +01:00
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
num_outputs: 1,
|
|
|
|
stream_progress_updates: true,
|
|
|
|
stream_image_progress: true,
|
|
|
|
show_only_filtered_image: true,
|
|
|
|
block_nsfw: false,
|
|
|
|
output_format: "png",
|
|
|
|
output_quality: 75,
|
2023-04-28 12:20:44 +02:00
|
|
|
output_lossless: false,
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
const TASK_OPTIONAL = {
|
2023-04-27 19:56:56 +02:00
|
|
|
device: "string",
|
|
|
|
init_image: "string",
|
|
|
|
mask: "string",
|
|
|
|
save_to_disk_path: "string",
|
|
|
|
use_face_correction: "string",
|
|
|
|
use_upscale: "string",
|
|
|
|
use_vae_model: "string",
|
|
|
|
use_hypernetwork_model: "string",
|
|
|
|
hypernetwork_strength: "number",
|
2023-04-28 12:20:44 +02:00
|
|
|
output_lossless: "boolean",
|
2023-05-25 00:16:14 +02:00
|
|
|
tiling: "string",
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
|
2023-05-25 00:16:14 +02:00
|
|
|
// Higher values will result in...
|
2022-12-06 12:34:08 +01:00
|
|
|
// pytorch_lightning/utilities/seed.py:60: UserWarning: X is not in bounds, numpy accepts from 0 to 4294967295
|
|
|
|
const MAX_SEED_VALUE = 4294967295
|
|
|
|
|
|
|
|
class RenderTask extends Task {
|
2023-04-27 19:56:56 +02:00
|
|
|
constructor(options = {}) {
|
2022-12-06 12:34:08 +01:00
|
|
|
super(options)
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this._reqBody.seed === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody.seed = Math.floor(Math.random() * (MAX_SEED_VALUE + 1))
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (
|
|
|
|
typeof typeof this._reqBody.seed === "number" &&
|
|
|
|
(this._reqBody.seed > MAX_SEED_VALUE || this._reqBody.seed < 0)
|
|
|
|
) {
|
2022-12-06 12:34:08 +01:00
|
|
|
throw new Error(`seed must be in range 0 to ${MAX_SEED_VALUE}.`)
|
|
|
|
}
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
if ("use_cpu" in this._reqBody) {
|
2022-12-06 12:34:08 +01:00
|
|
|
if (this._reqBody.use_cpu) {
|
2023-04-27 19:56:56 +02:00
|
|
|
this._reqBody.device = "cpu"
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
delete this._reqBody.use_cpu
|
|
|
|
}
|
|
|
|
if (this._reqBody.init_image) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this._reqBody.prompt_strength === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody.prompt_strength = 0.8
|
2023-04-27 19:56:56 +02:00
|
|
|
} else if (typeof this._reqBody.prompt_strength !== "number") {
|
|
|
|
throw new Error(
|
|
|
|
`prompt_strength need to be of type number but ${typeof this._reqBody
|
|
|
|
.prompt_strength} was found.`
|
|
|
|
)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if ("modifiers" in this._reqBody) {
|
2022-12-06 12:34:08 +01:00
|
|
|
if (Array.isArray(this._reqBody.modifiers) && this._reqBody.modifiers.length > 0) {
|
|
|
|
this._reqBody.modifiers = this._reqBody.modifiers.filter((val) => val.trim())
|
|
|
|
if (this._reqBody.modifiers.length > 0) {
|
2023-04-27 19:56:56 +02:00
|
|
|
this._reqBody.prompt = `${this._reqBody.prompt}, ${this._reqBody.modifiers.join(", ")}`
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this._reqBody.modifiers === "string" && this._reqBody.modifiers.length > 0) {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody.modifiers = this._reqBody.modifiers.trim()
|
|
|
|
if (this._reqBody.modifiers.length > 0) {
|
|
|
|
this._reqBody.prompt = `${this._reqBody.prompt}, ${this._reqBody.modifiers}`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
delete this._reqBody.modifiers
|
|
|
|
}
|
|
|
|
this.checkReqBody()
|
|
|
|
}
|
|
|
|
|
|
|
|
checkReqBody() {
|
|
|
|
for (const key in TASK_DEFAULTS) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof this._reqBody[key] === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
this._reqBody[key] = TASK_DEFAULTS[key]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (const key in TASK_REQUIRED) {
|
|
|
|
if (typeof this._reqBody[key] !== TASK_REQUIRED[key]) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error(
|
|
|
|
`${key} need to be of type ${TASK_REQUIRED[key]} but ${typeof this._reqBody[key]} was found.`
|
|
|
|
)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
for (const key in this._reqBody) {
|
|
|
|
if (key in TASK_REQUIRED) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if (key in TASK_OPTIONAL) {
|
2022-12-06 17:19:05 +01:00
|
|
|
if (typeof this._reqBody[key] == "undefined") {
|
|
|
|
delete this._reqBody[key]
|
|
|
|
console.warn(`reqBody[${key}] was set to undefined. Removing optional key without value...`)
|
|
|
|
continue
|
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
if (typeof this._reqBody[key] !== TASK_OPTIONAL[key]) {
|
2023-04-27 19:56:56 +02:00
|
|
|
throw new Error(
|
|
|
|
`${key} need to be of type ${TASK_OPTIONAL[key]} but ${typeof this._reqBody[
|
|
|
|
key
|
|
|
|
]} was found.`
|
|
|
|
)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Send current task to server.
|
|
|
|
* @param {*} [timeout=-1] Optional timeout value in ms
|
|
|
|
* @returns the response from the render request.
|
|
|
|
* @memberof Task
|
|
|
|
*/
|
2023-04-27 19:56:56 +02:00
|
|
|
async post(timeout = -1) {
|
|
|
|
performance.mark("make-render-request")
|
|
|
|
if (performance.getEntriesByName("click-makeImage", "mark").length > 0) {
|
|
|
|
performance.measure("diff", "click-makeImage", "make-render-request")
|
|
|
|
console.log(
|
|
|
|
"delay between clicking and making the server request:",
|
|
|
|
performance.getEntriesByName("diff", "measure")[0].duration + " ms"
|
|
|
|
)
|
2022-12-23 06:24:40 +01:00
|
|
|
}
|
2023-01-09 15:03:23 +01:00
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
let jsonResponse = await super.post("/render", timeout)
|
|
|
|
if (typeof jsonResponse?.task !== "number") {
|
|
|
|
console.warn("Endpoint error response: ", jsonResponse)
|
|
|
|
const event = Object.assign({ task: this }, jsonResponse)
|
2022-12-11 06:52:52 +01:00
|
|
|
await eventSource.fireEvent(EVENT_UNEXPECTED_RESPONSE, event)
|
2023-04-27 19:56:56 +02:00
|
|
|
if ("continueWith" in event) {
|
2022-12-06 12:34:08 +01:00
|
|
|
jsonResponse = await Promise.resolve(event.continueWith)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof jsonResponse?.task !== "number") {
|
|
|
|
const err = new Error(jsonResponse?.detail || "Endpoint response does not contains a task ID.")
|
2022-12-06 12:34:08 +01:00
|
|
|
this.abort(err)
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
this._setId(jsonResponse.task)
|
|
|
|
if (jsonResponse.stream) {
|
|
|
|
this.streamUrl = jsonResponse.stream
|
|
|
|
}
|
|
|
|
this._setStatus(TaskStatus.waiting)
|
|
|
|
return jsonResponse
|
|
|
|
}
|
|
|
|
|
|
|
|
enqueue(progressCallback) {
|
|
|
|
return Task.enqueueNew(this, RenderTask, progressCallback)
|
|
|
|
}
|
|
|
|
*start(progressCallback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof progressCallback !== "undefined" && typeof progressCallback !== "function") {
|
|
|
|
throw new Error("progressCallback is not a function. progressCallback type: " + typeof progressCallback)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (this.isStopped) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
this._setStatus(TaskStatus.pending)
|
2023-04-27 19:56:56 +02:00
|
|
|
progressCallback?.call(this, { reqBody: this._reqBody })
|
2022-12-06 12:34:08 +01:00
|
|
|
Object.freeze(this._reqBody)
|
|
|
|
|
|
|
|
// Post task request to backend
|
|
|
|
let renderRequest = undefined
|
|
|
|
try {
|
|
|
|
renderRequest = yield this.post()
|
2023-04-27 19:56:56 +02:00
|
|
|
yield progressCallback?.call(this, { renderResponse: renderRequest })
|
2022-12-06 12:34:08 +01:00
|
|
|
} catch (e) {
|
|
|
|
yield progressCallback?.call(this, { detail: e.message })
|
|
|
|
throw e
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
try {
|
|
|
|
// Wait for task to start on server.
|
2022-12-06 12:34:08 +01:00
|
|
|
yield this.waitUntil({
|
2023-04-27 19:56:56 +02:00
|
|
|
callback: function() {
|
|
|
|
return progressCallback?.call(this, {})
|
|
|
|
},
|
2023-04-28 12:20:44 +02:00
|
|
|
status: TaskStatus.processing,
|
2022-12-06 12:34:08 +01:00
|
|
|
})
|
|
|
|
} catch (e) {
|
|
|
|
this.abort(err)
|
|
|
|
throw e
|
|
|
|
}
|
|
|
|
// Update class status and callback.
|
2023-04-27 19:56:56 +02:00
|
|
|
const taskState = typeof serverState.tasks === "object" ? serverState.tasks[String(this.id)] : undefined
|
|
|
|
switch (taskState) {
|
|
|
|
case "pending": // Session has pending tasks.
|
|
|
|
console.error("Server %o render request %o is still waiting.", serverState, renderRequest)
|
2022-12-06 12:34:08 +01:00
|
|
|
//Only update status if not already set by waitUntil
|
2023-04-27 19:56:56 +02:00
|
|
|
if (this.status === TaskStatus.init || this.status === TaskStatus.pending) {
|
2022-12-06 12:34:08 +01:00
|
|
|
// Set status as Waiting in backend.
|
|
|
|
this._setStatus(TaskStatus.waiting)
|
|
|
|
}
|
|
|
|
break
|
2023-04-27 19:56:56 +02:00
|
|
|
case "running":
|
|
|
|
case "buffer":
|
2022-12-06 12:34:08 +01:00
|
|
|
// Normal expected messages.
|
|
|
|
this._setStatus(TaskStatus.processing)
|
|
|
|
break
|
2023-04-27 19:56:56 +02:00
|
|
|
case "completed":
|
2022-12-06 12:34:08 +01:00
|
|
|
if (this.isPending) {
|
|
|
|
// Set state to processing until we read the reply
|
|
|
|
this._setStatus(TaskStatus.processing)
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Server %o render request %o completed unexpectedly", serverState, renderRequest)
|
2022-12-06 12:34:08 +01:00
|
|
|
break // Continue anyway to try to read cached result.
|
2023-04-27 19:56:56 +02:00
|
|
|
case "error":
|
2022-12-06 12:34:08 +01:00
|
|
|
this._setStatus(TaskStatus.failed)
|
2023-04-27 19:56:56 +02:00
|
|
|
console.error("Server %o render request %o has failed", serverState, renderRequest)
|
2022-12-06 12:34:08 +01:00
|
|
|
break // Still valid, Update UI with error message
|
2023-04-27 19:56:56 +02:00
|
|
|
case "stopped":
|
2022-12-06 12:34:08 +01:00
|
|
|
this._setStatus(TaskStatus.stopped)
|
2023-04-27 19:56:56 +02:00
|
|
|
console.log("Server %o render request %o was stopped", serverState, renderRequest)
|
2022-12-06 12:34:08 +01:00
|
|
|
return false
|
|
|
|
default:
|
|
|
|
if (!progressCallback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
const err = new Error("Unexpected server task state: " + taskState || "Undefined")
|
2022-12-06 12:34:08 +01:00
|
|
|
this.abort(err)
|
|
|
|
throw err
|
|
|
|
}
|
|
|
|
const response = yield progressCallback.call(this, {})
|
|
|
|
if (response instanceof Error) {
|
|
|
|
this.abort(response)
|
|
|
|
throw response
|
|
|
|
}
|
|
|
|
if (!response) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Task started!
|
|
|
|
// Open the reader.
|
|
|
|
const reader = this.reader
|
|
|
|
const task = this
|
|
|
|
reader.onError = function(response) {
|
|
|
|
if (progressCallback) {
|
|
|
|
task.abort(new Error(response.statusText))
|
|
|
|
return progressCallback.call(task, { response, reader })
|
|
|
|
}
|
|
|
|
return Task.prototype.onError.call(task, response)
|
|
|
|
}
|
|
|
|
yield progressCallback?.call(this, { reader })
|
|
|
|
|
|
|
|
//Start streaming the results.
|
|
|
|
const streamGenerator = reader.open()
|
|
|
|
let value = undefined
|
|
|
|
let done = undefined
|
|
|
|
yield progressCallback?.call(this, { stream: streamGenerator })
|
|
|
|
do {
|
2023-04-27 19:56:56 +02:00
|
|
|
;({ value, done } = yield streamGenerator.next())
|
|
|
|
if (typeof value !== "object") {
|
2022-12-06 12:34:08 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
yield progressCallback?.call(this, { update: value })
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (!done)
|
2022-12-06 12:34:08 +01:00
|
|
|
return value
|
|
|
|
}
|
|
|
|
static start(task, progressCallback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof task !== "object") {
|
|
|
|
throw new Error("task is not an object. task type: " + typeof task)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (!(task instanceof Task)) {
|
|
|
|
if (task.reqBody) {
|
|
|
|
task = new RenderTask(task.reqBody)
|
|
|
|
} else {
|
|
|
|
task = new RenderTask(task)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return task.start(progressCallback)
|
|
|
|
}
|
|
|
|
static run(task, progressCallback) {
|
|
|
|
const promiseGenerator = RenderTask.start(task, progressCallback)
|
|
|
|
return Task.run(promiseGenerator)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
class FilterTask extends Task {
|
2023-07-28 15:27:28 +02:00
|
|
|
constructor(options = {}) {
|
|
|
|
super(options)
|
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
/** Send current task to server.
|
|
|
|
* @param {*} [timeout=-1] Optional timeout value in ms
|
|
|
|
* @returns the response from the render request.
|
|
|
|
* @memberof Task
|
|
|
|
*/
|
2023-04-27 19:56:56 +02:00
|
|
|
async post(timeout = -1) {
|
2023-07-28 15:27:28 +02:00
|
|
|
let res = await super.post("/filter", timeout)
|
2022-12-06 12:34:08 +01:00
|
|
|
//this._setId(jsonResponse.task)
|
|
|
|
this._setStatus(TaskStatus.waiting)
|
2023-07-28 15:27:28 +02:00
|
|
|
|
|
|
|
return res
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-07-28 15:27:28 +02:00
|
|
|
checkReqBody() {}
|
2022-12-06 12:34:08 +01:00
|
|
|
enqueue(progressCallback) {
|
|
|
|
return Task.enqueueNew(this, FilterTask, progressCallback)
|
|
|
|
}
|
|
|
|
*start(progressCallback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof progressCallback !== "undefined" && typeof progressCallback !== "function") {
|
|
|
|
throw new Error("progressCallback is not a function. progressCallback type: " + typeof progressCallback)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (this.isStopped) {
|
|
|
|
return
|
|
|
|
}
|
2023-07-28 15:27:28 +02:00
|
|
|
|
|
|
|
this._setStatus(TaskStatus.pending)
|
|
|
|
progressCallback?.call(this, { reqBody: this._reqBody })
|
|
|
|
Object.freeze(this._reqBody)
|
|
|
|
|
|
|
|
// Post task request to backend
|
|
|
|
let renderRes = undefined
|
|
|
|
try {
|
|
|
|
renderRes = yield this.post()
|
|
|
|
yield progressCallback?.call(this, { renderResponse: renderRes })
|
|
|
|
} catch (e) {
|
|
|
|
yield progressCallback?.call(this, { detail: e.message })
|
|
|
|
throw e
|
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
static start(task, progressCallback) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof task !== "object") {
|
|
|
|
throw new Error("task is not an object. task type: " + typeof task)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (!(task instanceof Task)) {
|
|
|
|
if (task.reqBody) {
|
|
|
|
task = new FilterTask(task.reqBody)
|
|
|
|
} else {
|
|
|
|
task = new FilterTask(task)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return task.start(progressCallback)
|
|
|
|
}
|
|
|
|
static run(task, progressCallback) {
|
|
|
|
const promiseGenerator = FilterTask.start(task, progressCallback)
|
|
|
|
return Task.run(promiseGenerator)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-27 19:56:56 +02:00
|
|
|
const getSystemInfo = debounce(
|
|
|
|
async function() {
|
|
|
|
let systemInfo = {
|
|
|
|
devices: {
|
|
|
|
all: {},
|
2023-04-28 12:20:44 +02:00
|
|
|
active: {},
|
2023-04-27 19:56:56 +02:00
|
|
|
},
|
2023-04-28 12:20:44 +02:00
|
|
|
hosts: [],
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
try {
|
|
|
|
const res = await fetch("/get/system_info")
|
|
|
|
if (!res.ok) {
|
|
|
|
console.error("Invalid response fetching devices", res.statusText)
|
|
|
|
return systemInfo
|
|
|
|
}
|
|
|
|
systemInfo = await res.json()
|
|
|
|
} catch (e) {
|
|
|
|
console.error("error fetching system info", e)
|
|
|
|
}
|
|
|
|
return systemInfo
|
|
|
|
},
|
|
|
|
250,
|
|
|
|
true
|
|
|
|
)
|
2022-12-06 12:34:08 +01:00
|
|
|
async function getDevices() {
|
|
|
|
let systemInfo = getSystemInfo()
|
|
|
|
return systemInfo.devices
|
|
|
|
}
|
|
|
|
async function getHosts() {
|
|
|
|
let systemInfo = getSystemInfo()
|
|
|
|
return systemInfo.hosts
|
|
|
|
}
|
|
|
|
|
2023-07-08 19:58:47 +02:00
|
|
|
async function getModels(scanForMalicious = true) {
|
2022-12-06 12:34:08 +01:00
|
|
|
let models = {
|
2023-04-27 19:56:56 +02:00
|
|
|
"stable-diffusion": [],
|
2023-04-28 12:20:44 +02:00
|
|
|
vae: [],
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
try {
|
2023-07-08 19:58:47 +02:00
|
|
|
const res = await fetch("/get/models?scan_for_malicious=" + scanForMalicious)
|
2022-12-06 12:34:08 +01:00
|
|
|
if (!res.ok) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.error("Invalid response fetching models", res.statusText)
|
2022-12-06 12:34:08 +01:00
|
|
|
return models
|
|
|
|
}
|
|
|
|
models = await res.json()
|
2023-04-27 19:56:56 +02:00
|
|
|
console.log("get models response", models)
|
2022-12-06 12:34:08 +01:00
|
|
|
} catch (e) {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.log("get models error", e)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
return models
|
|
|
|
}
|
|
|
|
|
2022-12-08 06:42:46 +01:00
|
|
|
function getServerCapacity() {
|
|
|
|
let activeDevicesCount = Object.keys(serverState?.devices?.active || {}).length
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof window === "object" && window.document.visibilityState === "hidden") {
|
2022-12-08 06:42:46 +01:00
|
|
|
activeDevicesCount = 1 + activeDevicesCount
|
|
|
|
}
|
|
|
|
return activeDevicesCount
|
|
|
|
}
|
|
|
|
|
2022-12-11 06:52:52 +01:00
|
|
|
let idleEventPromise = undefined
|
2022-12-06 12:34:08 +01:00
|
|
|
function continueTasks() {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof navigator?.scheduling?.isInputPending === "function") {
|
2022-12-06 12:34:08 +01:00
|
|
|
const inputPendingOptions = {
|
|
|
|
// Report mouse/pointer move events when queue is empty.
|
|
|
|
// Delay idle after mouse moves stops.
|
2023-04-28 12:20:44 +02:00
|
|
|
includeContinuous: Boolean(task_queue.size <= 0 && concurrent_generators.size <= 0),
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
if (navigator.scheduling.isInputPending(inputPendingOptions)) {
|
|
|
|
// Browser/User still active.
|
|
|
|
return asyncDelay(CONCURRENT_TASK_INTERVAL)
|
|
|
|
}
|
|
|
|
}
|
2022-12-08 06:42:46 +01:00
|
|
|
const serverCapacity = getServerCapacity()
|
2022-12-06 12:34:08 +01:00
|
|
|
if (task_queue.size <= 0 && concurrent_generators.size <= 0) {
|
2022-12-11 06:52:52 +01:00
|
|
|
if (!idleEventPromise?.isPending) {
|
2023-04-27 19:56:56 +02:00
|
|
|
idleEventPromise = makeQuerablePromise(
|
|
|
|
eventSource.fireEvent(EVENT_IDLE, { capacity: serverCapacity, idle: true })
|
|
|
|
)
|
2022-12-11 06:52:52 +01:00
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
// Calling idle could result in task being added to queue.
|
2022-12-22 10:52:25 +01:00
|
|
|
// if (task_queue.size <= 0 && concurrent_generators.size <= 0) {
|
|
|
|
// return asyncDelay(IDLE_COOLDOWN).then(() => idleEventPromise)
|
|
|
|
// }
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
2022-12-08 06:42:46 +01:00
|
|
|
if (task_queue.size < serverCapacity) {
|
2022-12-11 06:52:52 +01:00
|
|
|
if (!idleEventPromise?.isPending) {
|
2023-04-27 19:56:56 +02:00
|
|
|
idleEventPromise = makeQuerablePromise(
|
|
|
|
eventSource.fireEvent(EVENT_IDLE, { capacity: serverCapacity - task_queue.size })
|
|
|
|
)
|
2022-12-11 06:52:52 +01:00
|
|
|
}
|
2022-12-08 06:42:46 +01:00
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
const completedTasks = []
|
|
|
|
for (let [generator, promise] of concurrent_generators.entries()) {
|
|
|
|
if (promise.isPending) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
let value = promise.resolvedValue?.value || promise.resolvedValue
|
|
|
|
if (promise.isRejected) {
|
|
|
|
console.error(promise.rejectReason)
|
2023-04-27 19:56:56 +02:00
|
|
|
const event = { generator, reason: promise.rejectReason }
|
2022-12-06 12:34:08 +01:00
|
|
|
eventSource.fireEvent(EVENT_UNHANDLED_REJECTION, event)
|
2023-04-27 19:56:56 +02:00
|
|
|
if ("continueWith" in event) {
|
2022-12-06 12:34:08 +01:00
|
|
|
value = Promise.resolve(event.continueWith)
|
|
|
|
} else {
|
|
|
|
concurrent_generators.delete(generator)
|
2023-04-27 19:56:56 +02:00
|
|
|
completedTasks.push({ generator, promise })
|
2022-12-06 12:34:08 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (value instanceof Promise) {
|
2023-04-27 19:56:56 +02:00
|
|
|
promise = makeQuerablePromise(value.then((val) => ({ done: promise.resolvedValue?.done, value: val })))
|
2022-12-06 12:34:08 +01:00
|
|
|
concurrent_generators.set(generator, promise)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
weak_results.set(generator, value)
|
|
|
|
if (promise.resolvedValue?.done) {
|
|
|
|
concurrent_generators.delete(generator)
|
2023-04-27 19:56:56 +02:00
|
|
|
completedTasks.push({ generator, promise })
|
2022-12-06 12:34:08 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
promise = generator.next(value)
|
|
|
|
if (!(promise instanceof Promise)) {
|
|
|
|
promise = Promise.resolve(promise)
|
|
|
|
}
|
|
|
|
promise = makeQuerablePromise(promise)
|
|
|
|
concurrent_generators.set(generator, promise)
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let [task, generator] of task_queue.entries()) {
|
|
|
|
const cTsk = completedTasks.find((item) => item.generator === generator)
|
|
|
|
if (cTsk?.promise?.rejectReason || task.hasFailed) {
|
2023-04-27 19:56:56 +02:00
|
|
|
eventSource.fireEvent(EVENT_TASK_ERROR, {
|
|
|
|
task,
|
|
|
|
generator,
|
2023-04-28 12:20:44 +02:00
|
|
|
reason: cTsk?.promise?.rejectReason || task.exception,
|
2023-04-27 19:56:56 +02:00
|
|
|
})
|
2022-12-06 12:34:08 +01:00
|
|
|
task_queue.delete(task)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if (task.isCompleted || task.isStopped || cTsk) {
|
2023-04-27 19:56:56 +02:00
|
|
|
const eventEndArgs = { task, generator }
|
2022-12-06 12:34:08 +01:00
|
|
|
if (task.isStopped) {
|
|
|
|
eventEndArgs.stopped = true
|
|
|
|
}
|
|
|
|
eventSource.fireEvent(EVENT_TASK_END, eventEndArgs)
|
|
|
|
task_queue.delete(task)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if (concurrent_generators.size > serverCapacity) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if (!generator) {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof task.start === "function") {
|
2022-12-06 12:34:08 +01:00
|
|
|
generator = task.start()
|
|
|
|
}
|
|
|
|
} else if (concurrent_generators.has(generator)) {
|
|
|
|
continue
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
const event = { task, generator }
|
2022-12-11 06:52:52 +01:00
|
|
|
const beforeStart = eventSource.fireEvent(EVENT_TASK_START, event) // optional beforeStart promise to wait on before starting task.
|
|
|
|
const promise = makeQuerablePromise(beforeStart.then(() => Promise.resolve(event.beforeStart)))
|
2022-12-06 12:34:08 +01:00
|
|
|
concurrent_generators.set(event.generator, promise)
|
|
|
|
task_queue.set(task, event.generator)
|
|
|
|
}
|
|
|
|
const promises = Array.from(concurrent_generators.values())
|
|
|
|
if (promises.length <= 0) {
|
|
|
|
return asyncDelay(CONCURRENT_TASK_INTERVAL)
|
|
|
|
}
|
|
|
|
return Promise.race(promises).finally(continueTasks)
|
|
|
|
}
|
|
|
|
let taskPromise = undefined
|
|
|
|
function startCheck() {
|
|
|
|
if (taskPromise?.isPending) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
do {
|
|
|
|
if (taskPromise?.resolvedValue instanceof Promise) {
|
|
|
|
taskPromise = makeQuerablePromise(taskPromise.resolvedValue)
|
|
|
|
continue
|
|
|
|
}
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof navigator?.scheduling?.isInputPending === "function" && navigator.scheduling.isInputPending()) {
|
2022-12-06 12:34:08 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
const continuePromise = continueTasks().catch(async function(err) {
|
|
|
|
console.error(err)
|
2023-04-27 19:56:56 +02:00
|
|
|
await eventSource.fireEvent(EVENT_UNHANDLED_REJECTION, { reason: err })
|
2022-12-06 12:34:08 +01:00
|
|
|
await asyncDelay(RETRY_DELAY_ON_ERROR)
|
|
|
|
})
|
|
|
|
taskPromise = makeQuerablePromise(continuePromise)
|
2023-04-27 19:56:56 +02:00
|
|
|
} while (taskPromise?.isResolved)
|
2022-12-06 12:34:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const SD = {
|
|
|
|
ChunkedStreamReader,
|
|
|
|
ServerStates,
|
|
|
|
TaskStatus,
|
|
|
|
Task,
|
|
|
|
RenderTask,
|
|
|
|
FilterTask,
|
|
|
|
|
|
|
|
Events: EVENTS_TYPES,
|
2023-04-27 19:56:56 +02:00
|
|
|
init: async function(options = {}) {
|
|
|
|
if ("events" in options) {
|
2022-12-06 12:34:08 +01:00
|
|
|
for (const key in options.events) {
|
|
|
|
eventSource.addEventListener(key, options.events[key])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
await healthCheck()
|
|
|
|
setInterval(healthCheck, HEALTH_PING_INTERVAL)
|
|
|
|
setInterval(startCheck, CONCURRENT_TASK_INTERVAL)
|
|
|
|
},
|
|
|
|
|
|
|
|
/** Add a new event listener
|
|
|
|
*/
|
|
|
|
addEventListener: (...args) => eventSource.addEventListener(...args),
|
|
|
|
/** Remove the event listener
|
|
|
|
*/
|
|
|
|
removeEventListener: (...args) => eventSource.removeEventListener(...args),
|
|
|
|
|
|
|
|
isServerAvailable,
|
2022-12-08 06:42:46 +01:00
|
|
|
getServerCapacity,
|
2022-12-06 12:34:08 +01:00
|
|
|
|
|
|
|
getSystemInfo,
|
|
|
|
getDevices,
|
|
|
|
getHosts,
|
|
|
|
|
|
|
|
getModels,
|
|
|
|
|
|
|
|
render: (...args) => RenderTask.run(...args),
|
|
|
|
filter: (...args) => FilterTask.run(...args),
|
2023-04-28 12:20:44 +02:00
|
|
|
waitUntil,
|
2023-04-27 19:56:56 +02:00
|
|
|
}
|
2022-12-06 12:34:08 +01:00
|
|
|
|
|
|
|
Object.defineProperties(SD, {
|
|
|
|
serverState: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => serverState,
|
2022-12-06 12:34:08 +01:00
|
|
|
},
|
2022-12-08 06:42:46 +01:00
|
|
|
isAvailable: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => isServerAvailable(),
|
2022-12-08 06:42:46 +01:00
|
|
|
},
|
|
|
|
serverCapacity: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => getServerCapacity(),
|
2022-12-08 06:42:46 +01:00
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
sessionId: {
|
|
|
|
configurable: false,
|
|
|
|
get: () => sessionId,
|
|
|
|
set: (val) => {
|
2023-04-27 19:56:56 +02:00
|
|
|
if (typeof val === "undefined") {
|
2022-12-06 12:34:08 +01:00
|
|
|
throw new Error("Can't set sessionId to undefined.")
|
|
|
|
}
|
|
|
|
sessionId = val
|
2023-04-28 12:20:44 +02:00
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
},
|
|
|
|
MAX_SEED_VALUE: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => MAX_SEED_VALUE,
|
2022-12-06 12:34:08 +01:00
|
|
|
},
|
|
|
|
activeTasks: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => task_queue,
|
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
})
|
|
|
|
Object.defineProperties(getGlobal(), {
|
|
|
|
SD: {
|
|
|
|
configurable: false,
|
2023-04-28 12:20:44 +02:00
|
|
|
get: () => SD,
|
2022-12-06 12:34:08 +01:00
|
|
|
},
|
2023-04-27 19:56:56 +02:00
|
|
|
sessionId: {
|
|
|
|
//TODO Remove in the future in favor of SD.sessionId
|
2022-12-06 12:34:08 +01:00
|
|
|
configurable: false,
|
|
|
|
get: () => {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Deprecated window.sessionId has been replaced with SD.sessionId.")
|
2022-12-06 12:34:08 +01:00
|
|
|
console.trace()
|
|
|
|
return SD.sessionId
|
|
|
|
},
|
|
|
|
set: (val) => {
|
2023-04-27 19:56:56 +02:00
|
|
|
console.warn("Deprecated window.sessionId has been replaced with SD.sessionId.")
|
2022-12-06 12:34:08 +01:00
|
|
|
console.trace()
|
|
|
|
SD.sessionId = val
|
2023-04-28 12:20:44 +02:00
|
|
|
},
|
|
|
|
},
|
2022-12-06 12:34:08 +01:00
|
|
|
})
|
|
|
|
})()
|