name.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. // DefaultName returns a name with the default values for the host, namespace,
  33. // and tag parts. The model and digest parts are empty.
  34. //
  35. // - The default host is ("registry.ollama.ai")
  36. // - The default namespace is ("library")
  37. // - The default tag is ("latest")
  38. func DefaultName() Name {
  39. return Name{
  40. Host: "registry.ollama.ai",
  41. Namespace: "library",
  42. Tag: "latest",
  43. }
  44. }
  45. type partKind int
  46. const (
  47. kindHost partKind = iota
  48. kindNamespace
  49. kindModel
  50. kindTag
  51. kindDigest
  52. )
  53. func (k partKind) String() string {
  54. switch k {
  55. case kindHost:
  56. return "host"
  57. case kindNamespace:
  58. return "namespace"
  59. case kindModel:
  60. return "model"
  61. case kindTag:
  62. return "tag"
  63. case kindDigest:
  64. return "digest"
  65. default:
  66. return "unknown"
  67. }
  68. }
  69. // Name is a structured representation of a model name string, as defined by
  70. // [ParseNameNoDefaults].
  71. //
  72. // It is not guaranteed to be valid. Use [Name.IsValid] to check if the name
  73. // is valid.
  74. type Name struct {
  75. Host string
  76. Namespace string
  77. Model string
  78. Tag string
  79. RawDigest string
  80. }
  81. // ParseName parses and assembles a Name from a name string. The
  82. // format of a valid name string is:
  83. //
  84. // s:
  85. // { host } "/" { namespace } "/" { model } ":" { tag } "@" { digest }
  86. // { host } "/" { namespace } "/" { model } ":" { tag }
  87. // { host } "/" { namespace } "/" { model } "@" { digest }
  88. // { host } "/" { namespace } "/" { model }
  89. // { namespace } "/" { model } ":" { tag } "@" { digest }
  90. // { namespace } "/" { model } ":" { tag }
  91. // { namespace } "/" { model } "@" { digest }
  92. // { namespace } "/" { model }
  93. // { model } ":" { tag } "@" { digest }
  94. // { model } ":" { tag }
  95. // { model } "@" { digest }
  96. // { model }
  97. // "@" { digest }
  98. // host:
  99. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." | ":" }*
  100. // length: [1, 350]
  101. // namespace:
  102. // pattern: { alphanum | "_" } { alphanum | "-" | "_" }*
  103. // length: [1, 80]
  104. // model:
  105. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." }*
  106. // length: [1, 80]
  107. // tag:
  108. // pattern: { alphanum | "_" } { alphanum | "-" | "_" | "." }*
  109. // length: [1, 80]
  110. // digest:
  111. // pattern: { alphanum | "_" } { alphanum | "-" | ":" }*
  112. // length: [1, 80]
  113. //
  114. // Most users should use [ParseName] instead, unless need to support
  115. // different defaults than DefaultName.
  116. //
  117. // The name returned is not guaranteed to be valid. If it is not valid, the
  118. // field values are left in an undefined state. Use [Name.IsValid] to check
  119. // if the name is valid.
  120. func ParseName(s string) Name {
  121. return Merge(ParseNameBare(s), DefaultName())
  122. }
  123. // ParseNameBare parses s as a name string and returns a Name. No merge with
  124. // [DefaultName] is performed.
  125. func ParseNameBare(s string) Name {
  126. var n Name
  127. var promised bool
  128. s, n.RawDigest, promised = cutLast(s, "@")
  129. if promised && n.RawDigest == "" {
  130. n.RawDigest = MissingPart
  131. }
  132. s, n.Tag, _ = cutPromised(s, ":")
  133. s, n.Model, promised = cutPromised(s, "/")
  134. if !promised {
  135. n.Model = s
  136. return n
  137. }
  138. s, n.Namespace, promised = cutPromised(s, "/")
  139. if !promised {
  140. n.Namespace = s
  141. return n
  142. }
  143. n.Host = s
  144. return n
  145. }
  146. // Merge merges the host, namespace, and tag parts of the two names,
  147. // preferring the non-empty parts of a.
  148. func Merge(a, b Name) Name {
  149. a.Host = cmp.Or(a.Host, b.Host)
  150. a.Namespace = cmp.Or(a.Namespace, b.Namespace)
  151. a.Tag = cmp.Or(a.Tag, b.Tag)
  152. return a
  153. }
  154. // String returns the name string, in the format that [ParseNameNoDefaults]
  155. // accepts as valid, if [Name.IsValid] reports true; otherwise the empty
  156. // string is returned.
  157. func (n Name) String() string {
  158. var b strings.Builder
  159. if n.Host != "" {
  160. b.WriteString(n.Host)
  161. b.WriteByte('/')
  162. }
  163. if n.Namespace != "" {
  164. b.WriteString(n.Namespace)
  165. b.WriteByte('/')
  166. }
  167. b.WriteString(n.Model)
  168. if n.Tag != "" {
  169. b.WriteByte(':')
  170. b.WriteString(n.Tag)
  171. }
  172. if n.RawDigest != "" {
  173. b.WriteByte('@')
  174. b.WriteString(n.RawDigest)
  175. }
  176. return b.String()
  177. }
  178. // IsValid reports whether all parts of the name are present and valid. The
  179. // digest is a special case, and is checked for validity only if present.
  180. func (n Name) IsValid() bool {
  181. if n.RawDigest != "" && !isValidPart(kindDigest, n.RawDigest) {
  182. return false
  183. }
  184. return n.IsFullyQualified()
  185. }
  186. // IsFullyQualified returns true if all parts of the name are present and
  187. // valid without the digest.
  188. func (n Name) IsFullyQualified() bool {
  189. var parts = []string{
  190. n.Host,
  191. n.Namespace,
  192. n.Model,
  193. n.Tag,
  194. }
  195. for i, part := range parts {
  196. if !isValidPart(partKind(i), part) {
  197. return false
  198. }
  199. }
  200. return true
  201. }
  202. // Filepath returns a canonical filepath that represents the name with each part from
  203. // host to tag as a directory in the form:
  204. //
  205. // {host}/{namespace}/{model}/{tag}
  206. //
  207. // It uses the system's filepath separator and ensures the path is clean.
  208. //
  209. // It panics if the name is not fully qualified. Use [Name.IsFullyQualified]
  210. // to check if the name is fully qualified.
  211. func (n Name) Filepath() string {
  212. if !n.IsFullyQualified() {
  213. panic("illegal attempt to get filepath of invalid name")
  214. }
  215. return strings.ToLower(filepath.Join(
  216. n.Host,
  217. n.Namespace,
  218. n.Model,
  219. n.Tag,
  220. ))
  221. }
  222. // LogValue returns a slog.Value that represents the name as a string.
  223. func (n Name) LogValue() slog.Value {
  224. return slog.StringValue(n.String())
  225. }
  226. func isValidLen(kind partKind, s string) bool {
  227. switch kind {
  228. case kindHost:
  229. return len(s) >= 1 && len(s) <= 350
  230. case kindTag:
  231. return len(s) >= 1 && len(s) <= 80
  232. default:
  233. return len(s) >= 1 && len(s) <= 80
  234. }
  235. }
  236. func isValidPart(kind partKind, s string) bool {
  237. if !isValidLen(kind, s) {
  238. return false
  239. }
  240. for i := range s {
  241. if i == 0 {
  242. if !isAlphanumericOrUnderscore(s[i]) {
  243. return false
  244. }
  245. continue
  246. }
  247. switch s[i] {
  248. case '_', '-':
  249. case '.':
  250. if kind == kindNamespace {
  251. return false
  252. }
  253. case ':':
  254. if kind != kindHost && kind != kindDigest {
  255. return false
  256. }
  257. default:
  258. if !isAlphanumericOrUnderscore(s[i]) {
  259. return false
  260. }
  261. }
  262. }
  263. return true
  264. }
  265. func isAlphanumericOrUnderscore(c byte) bool {
  266. return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_'
  267. }
  268. func cutLast(s, sep string) (before, after string, ok bool) {
  269. i := strings.LastIndex(s, sep)
  270. if i >= 0 {
  271. return s[:i], s[i+len(sep):], true
  272. }
  273. return s, "", false
  274. }
  275. // cutPromised cuts the last part of s at the last occurrence of sep. If sep is
  276. // found, the part before and after sep are returned as-is unless empty, in
  277. // which case they are returned as MissingPart, which will cause
  278. // [Name.IsValid] to return false.
  279. func cutPromised(s, sep string) (before, after string, ok bool) {
  280. before, after, ok = cutLast(s, sep)
  281. if !ok {
  282. return before, after, false
  283. }
  284. return cmp.Or(before, MissingPart), cmp.Or(after, MissingPart), true
  285. }