name.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. // Package model contains types and utilities for parsing, validating, and
  2. // working with model names and digests.
  3. package model
  4. import (
  5. "cmp"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "path/filepath"
  10. "strings"
  11. )
  12. // Errors
  13. var (
  14. // ErrUnqualifiedName represents an error where a name is not fully
  15. // qualified. It is not used directly in this package, but is here
  16. // to avoid other packages inventing their own error type.
  17. // Additionally, it can be conveniently used via [Unqualified].
  18. ErrUnqualifiedName = errors.New("unqualified name")
  19. )
  20. // Unqualified is a helper function that returns an error with
  21. // ErrUnqualifiedName as the cause and the name as the message.
  22. func Unqualified(n Name) error {
  23. return fmt.Errorf("%w: %s", ErrUnqualifiedName, n)
  24. }
  25. // MissingPart is used to indicate any part of a name that was "promised" by
  26. // the presence of a separator, but is missing.
  27. //
  28. // The value was chosen because it is deemed unlikely to be set by a user,
  29. // not a valid part name valid when checked by [Name.IsValid], and easy to
  30. // spot in logs.
  31. const MissingPart = "!MISSING!"
  32. const (
  33. defaultHost = "registry.ollama.ai"
  34. defaultNamespace = "library"
  35. defaultTag = "latest"
  36. )
  37. // DefaultName returns a name with the default values for the host, namespace,
  38. // and tag parts. The model and digest parts are empty.
  39. //
  40. // - The default host is ("registry.ollama.ai")
  41. // - The default namespace is ("library")
  42. // - The default tag is ("latest")
  43. func DefaultName() Name {
  44. return Name{
  45. Host: defaultHost,
  46. Namespace: defaultNamespace,
  47. Tag: defaultTag,
  48. }
  49. }
  50. type partKind int
  51. const (
  52. kindHost partKind = iota
  53. kindNamespace
  54. kindModel
  55. kindTag
  56. kindDigest
  57. )
  58. func (k partKind) String() string {
  59. switch k {
  60. case kindHost:
  61. return "host"
  62. case kindNamespace:
  63. return "namespace"
  64. case kindModel:
  65. return "model"
  66. case kindTag:
  67. return "tag"
  68. case kindDigest:
  69. return "digest"
  70. default:
  71. return "unknown"
  72. }
  73. }
  74. // Name is a structured representation of a model name string, as defined by
  75. // [ParseNameNoDefaults].
  76. //
  77. // It is not guaranteed to be valid. Use [Name.IsValid] to check if the name
  78. // is valid.
  79. type Name struct {
  80. Host string
  81. Namespace string
  82. Model string
  83. Tag string
  84. }
  85. // ParseName parses and assembles a Name from a name string. The
  86. // format of a valid name string is:
  87. //
  88. // s:
  89. // { host } "/" { namespace } "/" { model } ":" { tag } "@" { digest }
  90. // { host } "/" { namespace } "/" { model } ":" { tag }
  91. // { host } "/" { namespace } "/" { model } "@" { digest }
  92. // { host } "/" { namespace } "/" { model }
  93. // { namespace } "/" { model } ":" { tag } "@" { digest }
  94. // { namespace } "/" { model } ":" { tag }
  95. // { namespace } "/" { model } "@" { digest }
  96. // { namespace } "/" { model }
  97. // { model } ":" { tag } "@" { digest }
  98. // { model } ":" { tag }
  99. // { model } "@" { digest }
  100. // { model }
  101. // "@" { digest }
  102. // host:
  103. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." | ":" }*
  104. // length: [1, 350]
  105. // namespace:
  106. // pattern: { alphanum | "_" } { alphanum | "-" | "_" }*
  107. // length: [1, 80]
  108. // model:
  109. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." }*
  110. // length: [1, 80]
  111. // tag:
  112. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." }*
  113. // length: [1, 80]
  114. // digest:
  115. // pattern: { alphanum | "_" } { alphanum | "-" | ":" }*
  116. // length: [1, 80]
  117. //
  118. // Most users should use [ParseName] instead, unless need to support
  119. // different defaults than DefaultName.
  120. //
  121. // The name returned is not guaranteed to be valid. If it is not valid, the
  122. // field values are left in an undefined state. Use [Name.IsValid] to check
  123. // if the name is valid.
  124. func ParseName(s string) Name {
  125. return Merge(ParseNameBare(s), DefaultName())
  126. }
  127. // ParseNameBare parses s as a name string and returns a Name. No merge with
  128. // [DefaultName] is performed.
  129. func ParseNameBare(s string) Name {
  130. var n Name
  131. var promised bool
  132. // "/" is an illegal tag character, so we can use it to split the host
  133. if strings.LastIndex(s, ":") > strings.LastIndex(s, "/") {
  134. s, n.Tag, _ = cutPromised(s, ":")
  135. }
  136. s, n.Model, promised = cutPromised(s, "/")
  137. if !promised {
  138. n.Model = s
  139. return n
  140. }
  141. s, n.Namespace, promised = cutPromised(s, "/")
  142. if !promised {
  143. n.Namespace = s
  144. return n
  145. }
  146. scheme, host, ok := strings.Cut(s, "://")
  147. if !ok {
  148. host = scheme
  149. }
  150. n.Host = host
  151. return n
  152. }
  153. // ParseNameFromFilepath parses a 4-part filepath as a Name. The parts are
  154. // expected to be in the form:
  155. //
  156. // { host } "/" { namespace } "/" { model } "/" { tag }
  157. func ParseNameFromFilepath(s string) (n Name) {
  158. parts := strings.Split(s, string(filepath.Separator))
  159. if len(parts) != 4 {
  160. return Name{}
  161. }
  162. n.Host = parts[0]
  163. n.Namespace = parts[1]
  164. n.Model = parts[2]
  165. n.Tag = parts[3]
  166. if !n.IsFullyQualified() {
  167. return Name{}
  168. }
  169. return n
  170. }
  171. // Merge merges the host, namespace, and tag parts of the two names,
  172. // preferring the non-empty parts of a.
  173. func Merge(a, b Name) Name {
  174. a.Host = cmp.Or(a.Host, b.Host)
  175. a.Namespace = cmp.Or(a.Namespace, b.Namespace)
  176. a.Tag = cmp.Or(a.Tag, b.Tag)
  177. return a
  178. }
  179. // String returns the name string, in the format that [ParseNameNoDefaults]
  180. // accepts as valid, if [Name.IsValid] reports true; otherwise the empty
  181. // string is returned.
  182. func (n Name) String() string {
  183. var b strings.Builder
  184. if n.Host != "" {
  185. b.WriteString(n.Host)
  186. b.WriteByte('/')
  187. }
  188. if n.Namespace != "" {
  189. b.WriteString(n.Namespace)
  190. b.WriteByte('/')
  191. }
  192. b.WriteString(n.Model)
  193. if n.Tag != "" {
  194. b.WriteByte(':')
  195. b.WriteString(n.Tag)
  196. }
  197. return b.String()
  198. }
  199. // DisplayShort returns a short string version of the name.
  200. func (n Name) DisplayShortest() string {
  201. var sb strings.Builder
  202. if n.Host != defaultHost {
  203. sb.WriteString(n.Host)
  204. sb.WriteByte('/')
  205. sb.WriteString(n.Namespace)
  206. sb.WriteByte('/')
  207. } else if n.Namespace != defaultNamespace {
  208. sb.WriteString(n.Namespace)
  209. sb.WriteByte('/')
  210. }
  211. // always include model and tag
  212. sb.WriteString(n.Model)
  213. sb.WriteString(":")
  214. sb.WriteString(n.Tag)
  215. return sb.String()
  216. }
  217. // IsValidNamespace reports whether the provided string is a valid
  218. // namespace.
  219. func IsValidNamespace(s string) bool {
  220. return isValidPart(kindNamespace, s)
  221. }
  222. // IsValid reports whether all parts of the name are present and valid. The
  223. // digest is a special case, and is checked for validity only if present.
  224. //
  225. // Note: The digest check has been removed as is planned to be added back in
  226. // at a later time.
  227. func (n Name) IsValid() bool {
  228. return n.IsFullyQualified()
  229. }
  230. // IsFullyQualified returns true if all parts of the name are present and
  231. // valid without the digest.
  232. func (n Name) IsFullyQualified() bool {
  233. parts := []string{
  234. n.Host,
  235. n.Namespace,
  236. n.Model,
  237. n.Tag,
  238. }
  239. for i, part := range parts {
  240. if !isValidPart(partKind(i), part) {
  241. return false
  242. }
  243. }
  244. return true
  245. }
  246. // Filepath returns a canonical filepath that represents the name with each part from
  247. // host to tag as a directory in the form:
  248. //
  249. // {host}/{namespace}/{model}/{tag}
  250. //
  251. // It uses the system's filepath separator and ensures the path is clean.
  252. //
  253. // It panics if the name is not fully qualified. Use [Name.IsFullyQualified]
  254. // to check if the name is fully qualified.
  255. func (n Name) Filepath() string {
  256. if !n.IsFullyQualified() {
  257. panic("illegal attempt to get filepath of invalid name")
  258. }
  259. return filepath.Join(
  260. n.Host,
  261. n.Namespace,
  262. n.Model,
  263. n.Tag,
  264. )
  265. }
  266. // LogValue returns a slog.Value that represents the name as a string.
  267. func (n Name) LogValue() slog.Value {
  268. return slog.StringValue(n.String())
  269. }
  270. func isValidLen(kind partKind, s string) bool {
  271. switch kind {
  272. case kindHost:
  273. return len(s) >= 1 && len(s) <= 350
  274. case kindTag:
  275. return len(s) >= 1 && len(s) <= 80
  276. default:
  277. return len(s) >= 1 && len(s) <= 80
  278. }
  279. }
  280. func isValidPart(kind partKind, s string) bool {
  281. if !isValidLen(kind, s) {
  282. return false
  283. }
  284. for i := range s {
  285. if i == 0 {
  286. if !isAlphanumericOrUnderscore(s[i]) {
  287. return false
  288. }
  289. continue
  290. }
  291. switch s[i] {
  292. case '_', '-':
  293. case '.':
  294. if kind == kindNamespace {
  295. return false
  296. }
  297. case ':':
  298. if kind != kindHost && kind != kindDigest {
  299. return false
  300. }
  301. default:
  302. if !isAlphanumericOrUnderscore(s[i]) {
  303. return false
  304. }
  305. }
  306. }
  307. return true
  308. }
  309. func isAlphanumericOrUnderscore(c byte) bool {
  310. return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_'
  311. }
  312. func cutLast(s, sep string) (before, after string, ok bool) {
  313. i := strings.LastIndex(s, sep)
  314. if i >= 0 {
  315. return s[:i], s[i+len(sep):], true
  316. }
  317. return s, "", false
  318. }
  319. // cutPromised cuts the last part of s at the last occurrence of sep. If sep is
  320. // found, the part before and after sep are returned as-is unless empty, in
  321. // which case they are returned as MissingPart, which will cause
  322. // [Name.IsValid] to return false.
  323. func cutPromised(s, sep string) (before, after string, ok bool) {
  324. before, after, ok = cutLast(s, sep)
  325. if !ok {
  326. return before, after, false
  327. }
  328. return cmp.Or(before, MissingPart), cmp.Or(after, MissingPart), true
  329. }