sdcpp-unload.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * @node sdcpp-unload
  3. * @name SD.cpp Unload
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Free the main model slot, the upscaler slot, or both
  7. * @icon eraser
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. serverUrl: {
  13. type: 'string', title: 'Server URL',
  14. description: 'Base address of the sdcpp-restapi server',
  15. default: 'http://localhost:8077'
  16. },
  17. credentialId: {
  18. type: 'string', title: 'Credential',
  19. description: 'A basic credential holding the sdcpp-restapi username and password',
  20. dynamicOptions: { source: 'credentials', filter: { type: ['basic'] } }
  21. },
  22. target: {
  23. type: 'string', title: 'Unload',
  24. enum: ['model', 'upscaler', 'both'],
  25. default: 'model',
  26. description: 'Which slot to free. They are independent - unloading the model leaves the upscaler in place, and the other way round'
  27. },
  28. timeout: { type: 'number', title: 'Timeout (ms)', default: 60000 }
  29. },
  30. required: []
  31. };
  32. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  33. const outputSchema = {
  34. type: 'object',
  35. properties: {
  36. unloadedModel: { type: 'boolean' },
  37. unloadedUpscaler: { type: 'boolean' },
  38. previousModel: { type: 'string', description: 'What was in the main slot before' },
  39. previousUpscaler: { type: 'string' }
  40. }
  41. };
  42. function normalizeServer(url) {
  43. const value = String(url || '').trim();
  44. if (!value) {
  45. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  46. }
  47. return value.replace(/\/+$/, '');
  48. }
  49. function readCredential(credentialId) {
  50. const auth = smartbotic.credentials.get(credentialId);
  51. if (!auth || auth.success !== true) {
  52. throw new Error('SD.cpp: could not read the credential: ' +
  53. ((auth && auth.error) || 'unknown error'));
  54. }
  55. const value = auth.headerValue || '';
  56. if (value.indexOf('Basic ') !== 0) {
  57. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  58. 'username and password');
  59. }
  60. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  61. const separator = decoded.indexOf(':');
  62. if (separator < 1) {
  63. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  64. }
  65. return {
  66. username: decoded.substring(0, separator),
  67. password: decoded.substring(separator + 1)
  68. };
  69. }
  70. function call(options) {
  71. const response = smartbotic.http.request(options);
  72. let body = response.data;
  73. if (typeof body === 'string' && body.length > 0) {
  74. try {
  75. body = JSON.parse(body);
  76. } catch (e) {
  77. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  78. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  79. ' with a body that is not JSON: ' + snippet);
  80. }
  81. }
  82. if (response.status < 200 || response.status >= 300) {
  83. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  84. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  85. }
  86. return body || {};
  87. }
  88. function login(server, credential, timeout) {
  89. const session = call({
  90. method: 'POST',
  91. url: server + '/auth/login',
  92. headers: { 'Content-Type': 'application/json' },
  93. body: JSON.stringify({
  94. username: credential.username,
  95. password: credential.password
  96. }),
  97. timeout: timeout,
  98. what: 'signing in'
  99. });
  100. if (!session.token) {
  101. throw new Error('SD.cpp: the server accepted the login but returned no token');
  102. }
  103. return session.token;
  104. }
  105. // /health is unauthenticated, and it is the only way to find out what is
  106. // already loaded without asking for a token first.
  107. function readHealth(server, timeout) {
  108. return call({
  109. method: 'GET',
  110. url: server + '/health',
  111. timeout: timeout,
  112. what: 'reading server health'
  113. });
  114. }
  115. function putIfSet(target, key, value) {
  116. if (value === undefined || value === null || value === '') {
  117. return;
  118. }
  119. target[key] = value;
  120. }
  121. async function execute(config, input, context) {
  122. const server = normalizeServer(config.serverUrl);
  123. const timeout = config.timeout > 0 ? config.timeout : 60000;
  124. const target = config.target || 'model';
  125. const health = readHealth(server, Math.min(timeout, 15000));
  126. const hadModel = health.model_loaded === true;
  127. const hadUpscaler = health.upscaler_loaded === true;
  128. const wantModel = target === 'model' || target === 'both';
  129. const wantUpscaler = target === 'upscaler' || target === 'both';
  130. // Nothing to free is a success, not an error. A cleanup step at the end of a
  131. // workflow should not fail because an earlier branch already unloaded.
  132. if ((!wantModel || !hadModel) && (!wantUpscaler || !hadUpscaler)) {
  133. smartbotic.log.info('SD.cpp: nothing to unload');
  134. return {
  135. unloadedModel: false,
  136. unloadedUpscaler: false,
  137. previousModel: '',
  138. previousUpscaler: ''
  139. };
  140. }
  141. const credential = readCredential(config.credentialId);
  142. const token = login(server, credential, Math.min(timeout, 30000));
  143. const headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token };
  144. let unloadedModel = false;
  145. let unloadedUpscaler = false;
  146. if (wantModel && hadModel) {
  147. call({ method: 'POST', url: server + '/models/unload', headers: headers,
  148. body: '{}', timeout: timeout, what: 'unloading the model' });
  149. unloadedModel = true;
  150. }
  151. if (wantUpscaler && hadUpscaler) {
  152. call({ method: 'POST', url: server + '/upscaler/unload', headers: headers,
  153. body: '{}', timeout: timeout, what: 'unloading the upscaler' });
  154. unloadedUpscaler = true;
  155. }
  156. smartbotic.log.info('SD.cpp: unloaded' +
  157. (unloadedModel ? ' model ' + (health.model_name || '') : '') +
  158. (unloadedUpscaler ? ' upscaler ' + (health.upscaler_name || '') : ''));
  159. return {
  160. unloadedModel: unloadedModel,
  161. unloadedUpscaler: unloadedUpscaler,
  162. previousModel: unloadedModel ? (health.model_name || '') : '',
  163. previousUpscaler: unloadedUpscaler ? (health.upscaler_name || '') : ''
  164. };
  165. }
  166. module.exports = { configSchema, inputSchema, outputSchema, execute };