sdcpp-unload.js 7.1 KB

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